Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9c122a8913 | |||
| 35f2d3b4e7 | |||
| 261dde435b |
Binary file not shown.
File diff suppressed because one or more lines are too long
+20
-3
@@ -1,22 +1,39 @@
|
||||
# 纵横家 Android 客户端
|
||||
|
||||
版本 `1.0.1` 候选;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。
|
||||
版本 `1.0.8`;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。发布状态以公司安装包仓库的同版正式 Release 为准。
|
||||
|
||||
1.0.8 启动 Android VPN 后,先通过已授权的代理出口完成 HTTPS 验证,再显示已连接。第一个检查站点失败时改用独立站点。验证中可取消,刷新账号信息时可断开。连接验证与普通应用流量分别使用各自的路由规则。Android 继续使用平台为手机分配的代理入口和系统 VPN。
|
||||
|
||||
1.0.7 修复共享安装包仓库分页后漏检 Android 版本,以及无关版本记录格式异常导致整个更新检查失败的问题。自动检查有统一20秒网络截止时间、分页及响应大小上限;发现新版本后提示从公司仓库覆盖安装,保留账号和配置,安装仍需 Android 系统确认。代理速度最低使用 KB/s;极小正样本显示 `<0.1 KB/s`。保留1.0.6的启动租约、授权隔离和电脑同款山水/半透明界面。本版验证包括离线 JVM 回归、五种 APK 的编译与同证书签名核验及 GPL 编译输入绑定;没有切换生产手机上的夜猫,也未把旧版手机验收记到本包。
|
||||
|
||||
1.0.6 保留1.0.5的山水背景和半透明界面,并修复VPN内核启动与停止交错时的启动租约竞态。构建按本轮JUnit XML实际用例计数,必须通过现有10项授权回归及至少8项 `UcvlVpnStartupLeaseTest` 新回归;不固定继承旧版本41项测试结论。新包仍须独立核验签名、GPL编译输入匹配和实体设备VPN行为;编译或单测通过不代表已正式发布,也不替代真实Service/广播、网络切换、休眠恢复及持续会话验收。
|
||||
|
||||
1.0.5 登录和主界面同步电脑同款原创山水图片,采用原生滚动控件、约50%白色透明卡片及深色文字,并适配系统栏和软键盘。仅同步有明确来源的山水PNG,不导入许可不明的人物插图;未修改API、授权、VPN路由或服务逻辑。签名、构建及实际设备验收记录按新包分别保存,不沿用1.0.4的包hash或旧模拟器结果冒称本包已验收。
|
||||
|
||||
1.0.4 纳入2026-09-17的后台授权隔离修复:区分“旧会话停止”和“当前账号撤销”,防止重新登录后的延迟响应误报新账号失效。旧1.0.3候选APK不含此修复。修复历史见`acceptance/AUTH-SESSION-ISOLATION-20260917.md`;1.0.4的构建、签名和本地验证见`acceptance/ACCEPTANCE-1.0.4.md`。本地检查不替代真实服务/设备VPN验收,候选未发布。
|
||||
|
||||
## 2026-09-08:1.0.3 本地候选
|
||||
|
||||
新增启动与手动 Git 更新检查,只提示 `pro.ucvl.cn` 正式 Android Release 的通用 APK;忽略草稿/试用/其它平台,下载路径固定在公司公开安装包仓库。提示不改变 VPN,不共享平台登录令牌。用户同意后打开下载;系统要求的 APK 安装授权仍需确认,尚不是应用内静默下载安装。
|
||||
|
||||
1.0.3 的 34 项单元测试和 APK 构建通过,五种 APK 已沿用公司原证书签名,尚未上传或向员工推送。构建请使用 ASCII 路径:中文目录下本轮 Gradle 测试工作进程未能加载测试类;独立 ASCII 源码副本重编译后全套通过,没有关闭或跳过失败测试。
|
||||
|
||||
## 已实现
|
||||
|
||||
- 公司账号登录、浏览器注册、设备授权、个人信息、套餐/额度/有效期。
|
||||
- 由平台自动分配节点,客户端只显示实际工作节点,不提供节点选择。
|
||||
- 完整保留平台下发的路由规则,支持智能/全局代理;使用 Android VpnService + HEV 隧道接管其他应用。
|
||||
- 仅统计 proxy 出站的速度/流量,两条低高度曲线;直连不计入代理统计。
|
||||
- 仅统计 proxy 出站的速度/流量;速度使用 KB/s 或更大单位,直连不计入代理统计。
|
||||
- Android Keystore 加密会话、同一证书覆盖升级保留配置。
|
||||
- VPN 后台每 60 秒检查授权,401/403 时断开并清除会话;临时网络错误不误当账号撤销。
|
||||
- 退出等待服务停止,TLS 清理在后台线程执行;系统 VPN 关闭后由 Android 恢复原网络。
|
||||
- 兼容后台 `config_contract=2`,连接时把节点地址切换到统一 NPM 公网网关,同时保留每个节点的端口和 Reality SNI;旧后台仍按原配置工作。
|
||||
|
||||
## 验收边界
|
||||
|
||||
`acceptance/` 保存实际测试记录,不把编译成功当作手机实测。原生内核三节点 × 两模式 HTTPS、系统 VPN 独立 UID、退出/后台回收、同证书覆盖升级测试已通过。独立源码副本重新下载依赖并从头构建,通过 26 项单测;生成的 APK 解包内容与候选构建逐项相同。没有 Android 实体手机测试,尚未宣称与 Windows 全功能等价。
|
||||
|
||||
当前没有实现 Android 未知目标失败的全量学习闭环、持续故障自动换节点和应用内下载安装升级流程。公司已确认的规则会随连接配置下发。暂不作为全公司稳定版通知。
|
||||
当前没有实现 Android 未知目标失败的全量学习闭环、持续故障自动换节点和应用内静默下载安装。公司已确认的规则会随连接配置下发。1.0.7没有手机实测:真实 Service/广播、网络切换、休眠恢复和持续会话仍需独立验收,离线回归不替代这些检查。旧1.0.0版本没有本版启动更新提示时,可从公司正式发布页下载同证书 APK 直接覆盖安装。
|
||||
|
||||
## 从源码构建
|
||||
|
||||
|
||||
@@ -1,22 +1,37 @@
|
||||
# 纵横家 Android 客户端
|
||||
|
||||
版本 `1.0.1` 候选;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。
|
||||
版本 `1.0.7`;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。发布状态以公司安装包仓库的同版正式 Release 为准。
|
||||
|
||||
1.0.7 修复共享安装包仓库分页后漏检 Android 版本,以及无关版本记录格式异常导致整个更新检查失败的问题。自动检查有统一20秒网络截止时间、分页及响应大小上限;发现新版本后提示从公司仓库覆盖安装,保留账号和配置,安装仍需 Android 系统确认。代理速度最低使用 KB/s;极小正样本显示 `<0.1 KB/s`。保留1.0.6的启动租约、授权隔离和电脑同款山水/半透明界面。本版验证包括离线 JVM 回归、五种 APK 的编译与同证书签名核验及 GPL 编译输入绑定;没有切换生产手机上的夜猫,也未把旧版手机验收记到本包。
|
||||
|
||||
1.0.6 保留1.0.5的山水背景和半透明界面,并修复VPN内核启动与停止交错时的启动租约竞态。构建按本轮JUnit XML实际用例计数,必须通过现有10项授权回归及至少8项 `UcvlVpnStartupLeaseTest` 新回归;不固定继承旧版本41项测试结论。新包仍须独立核验签名、GPL编译输入匹配和实体设备VPN行为;编译或单测通过不代表已正式发布,也不替代真实Service/广播、网络切换、休眠恢复及持续会话验收。
|
||||
|
||||
1.0.5 登录和主界面同步电脑同款原创山水图片,采用原生滚动控件、约50%白色透明卡片及深色文字,并适配系统栏和软键盘。仅同步有明确来源的山水PNG,不导入许可不明的人物插图;未修改API、授权、VPN路由或服务逻辑。签名、构建及实际设备验收记录按新包分别保存,不沿用1.0.4的包hash或旧模拟器结果冒称本包已验收。
|
||||
|
||||
1.0.4 纳入2026-09-17的后台授权隔离修复:区分“旧会话停止”和“当前账号撤销”,防止重新登录后的延迟响应误报新账号失效。旧1.0.3候选APK不含此修复。修复历史见`acceptance/AUTH-SESSION-ISOLATION-20260917.md`;1.0.4的构建、签名和本地验证见`acceptance/ACCEPTANCE-1.0.4.md`。本地检查不替代真实服务/设备VPN验收,候选未发布。
|
||||
|
||||
## 2026-09-08:1.0.3 本地候选
|
||||
|
||||
新增启动与手动 Git 更新检查,只提示 `pro.ucvl.cn` 正式 Android Release 的通用 APK;忽略草稿/试用/其它平台,下载路径固定在公司公开安装包仓库。提示不改变 VPN,不共享平台登录令牌。用户同意后打开下载;系统要求的 APK 安装授权仍需确认,尚不是应用内静默下载安装。
|
||||
|
||||
1.0.3 的 34 项单元测试和 APK 构建通过,五种 APK 已沿用公司原证书签名,尚未上传或向员工推送。构建请使用 ASCII 路径:中文目录下本轮 Gradle 测试工作进程未能加载测试类;独立 ASCII 源码副本重编译后全套通过,没有关闭或跳过失败测试。
|
||||
|
||||
## 已实现
|
||||
|
||||
- 公司账号登录、浏览器注册、设备授权、个人信息、套餐/额度/有效期。
|
||||
- 由平台自动分配节点,客户端只显示实际工作节点,不提供节点选择。
|
||||
- 完整保留平台下发的路由规则,支持智能/全局代理;使用 Android VpnService + HEV 隧道接管其他应用。
|
||||
- 仅统计 proxy 出站的速度/流量,两条低高度曲线;直连不计入代理统计。
|
||||
- 仅统计 proxy 出站的速度/流量;速度使用 KB/s 或更大单位,直连不计入代理统计。
|
||||
- Android Keystore 加密会话、同一证书覆盖升级保留配置。
|
||||
- VPN 后台每 60 秒检查授权,401/403 时断开并清除会话;临时网络错误不误当账号撤销。
|
||||
- 退出等待服务停止,TLS 清理在后台线程执行;系统 VPN 关闭后由 Android 恢复原网络。
|
||||
- 兼容后台 `config_contract=2`,连接时把节点地址切换到统一 NPM 公网网关,同时保留每个节点的端口和 Reality SNI;旧后台仍按原配置工作。
|
||||
|
||||
## 验收边界
|
||||
|
||||
`acceptance/` 保存实际测试记录,不把编译成功当作手机实测。原生内核三节点 × 两模式 HTTPS、系统 VPN 独立 UID、退出/后台回收、同证书覆盖升级测试已通过。独立源码副本重新下载依赖并从头构建,通过 26 项单测;生成的 APK 解包内容与候选构建逐项相同。没有 Android 实体手机测试,尚未宣称与 Windows 全功能等价。
|
||||
|
||||
当前没有实现 Android 未知目标失败的全量学习闭环、持续故障自动换节点和应用内下载安装升级流程。公司已确认的规则会随连接配置下发。暂不作为全公司稳定版通知。
|
||||
当前没有实现 Android 未知目标失败的全量学习闭环、持续故障自动换节点和应用内静默下载安装。公司已确认的规则会随连接配置下发。1.0.7没有手机实测:真实 Service/广播、网络切换、休眠恢复和持续会话仍需独立验收,离线回归不替代这些检查。旧1.0.0版本没有本版启动更新提示时,可从公司正式发布页下载同证书 APK 直接覆盖安装。
|
||||
|
||||
## 从源码构建
|
||||
|
||||
|
||||
+16
-4
@@ -1,4 +1,9 @@
|
||||
param([switch]$InstrumentationOnly)
|
||||
param(
|
||||
[switch]$InstrumentationOnly,
|
||||
[ValidatePattern('^\d+\.\d+\.\d+$')][string]$Version = '1.0.3',
|
||||
[string]$InputDirectory = '',
|
||||
[ValidatePattern('^[a-z0-9.-]*$')][string]$TestRevision = ''
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$androidRoot = $PSScriptRoot
|
||||
$env:JAVA_HOME = Join-Path $androidRoot '.tools/jdk-staging/jdk-21.0.12.1+1'
|
||||
@@ -13,15 +18,22 @@ $apkSigner = Join-Path $androidRoot '.tools/android-sdk/build-tools/37.0.0/apksi
|
||||
$zipAlign = Join-Path $androidRoot '.tools/android-sdk/build-tools/37.0.0/zipalign.exe'
|
||||
$keyStore = Join-Path $androidRoot '.tools/signing/ucvl-zonghengjia-release.jks'
|
||||
try {
|
||||
if ($InstrumentationOnly) {
|
||||
if ($InputDirectory) {
|
||||
$inputs = @(Get-ChildItem -LiteralPath ([IO.Path]::GetFullPath($InputDirectory)) -Filter '*.apk')
|
||||
if (-not $InstrumentationOnly) { $inputs = @($inputs | Where-Object Name -Like "UCVL-Zonghengjia-$Version-*.apk") }
|
||||
} elseif ($InstrumentationOnly) {
|
||||
$inputs = @(Get-ChildItem -LiteralPath (Join-Path $androidRoot 'V2rayNG/app/build/outputs/apk/androidTest/playstore/release') -Filter '*.apk')
|
||||
} else {
|
||||
$inputs = @(Get-ChildItem -LiteralPath (Join-Path $androidRoot 'V2rayNG/app/build/outputs/apk/playstore/release') -Filter 'UCVL-Zonghengjia-1.0.1-*.apk')
|
||||
$inputs = @(Get-ChildItem -LiteralPath (Join-Path $androidRoot 'V2rayNG/app/build/outputs/apk/playstore/release') -Filter "UCVL-Zonghengjia-$Version-*.apk")
|
||||
}
|
||||
if (-not $inputs.Count) { throw 'No candidate APKs were built.' }
|
||||
foreach ($inputFile in $inputs) {
|
||||
$stageFile = Join-Path $androidRoot ('.tools/signing/aligned-' + $inputFile.Name)
|
||||
$outputFile = Join-Path $androidRoot ('releases/' + $inputFile.Name)
|
||||
$revision = if ($TestRevision) { "-$TestRevision" } else { '' }
|
||||
if ($TestRevision -and -not $InstrumentationOnly) { throw 'TestRevision is only for instrumentation artifacts' }
|
||||
$outputName = if ($InstrumentationOnly) { $inputFile.BaseName + "-$Version$revision.apk" } else { $inputFile.Name }
|
||||
$outputFile = Join-Path $androidRoot ('releases/' + $outputName)
|
||||
if (Test-Path -LiteralPath $outputFile) { throw "Refusing to overwrite existing signed artifact: $outputName" }
|
||||
& $zipAlign -f -p 4 $inputFile.FullName $stageFile
|
||||
if ($LASTEXITCODE) { throw 'APK alignment failed.' }
|
||||
& $apkSigner sign --ks $keyStore --ks-key-alias $signing['keyAlias'] --ks-pass env:UCVL_ANDROID_STORE_PASS --key-pass env:UCVL_ANDROID_KEY_PASS --out $outputFile $stageFile
|
||||
|
||||
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "cn.toplc.zonghengjia"
|
||||
minSdk = 24
|
||||
targetSdk = 37
|
||||
versionCode = 10001
|
||||
versionName = "1.0.1"
|
||||
versionCode = 10008
|
||||
versionName = "1.0.8"
|
||||
multiDexEnabled = true
|
||||
|
||||
val abiFilterList = (properties["ABI_FILTERS"] as? String)?.split(';')
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import android.os.ParcelFileDescriptor
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class UcvlEgressProbeTest {
|
||||
@Test fun rejectsWhenBothExplicitProxyChecksFail() {
|
||||
exerciseProxy(acceptCloudflare = false)
|
||||
}
|
||||
|
||||
@Test fun independentlyVerifiesSecondTlsTargetWhenFirstFails() {
|
||||
exerciseProxy(acceptCloudflare = true)
|
||||
}
|
||||
|
||||
private fun exerciseProxy(acceptCloudflare: Boolean) {
|
||||
val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
|
||||
val device = ParcelFileDescriptor.AutoCloseInputStream(automation.executeShellCommand("getprop ro.kernel.qemu"))
|
||||
assertEquals("1", device.bufferedReader().use { it.readText().trim() })
|
||||
val received = LinkedBlockingQueue<String>()
|
||||
ServerSocket(0, 4, InetAddress.getByName("127.0.0.1")).use { listener ->
|
||||
listener.soTimeout = 15_000
|
||||
val proxy = thread(isDaemon = true, name = "isolated-http-test-proxy") {
|
||||
repeat(2) {
|
||||
listener.accept().use { incoming ->
|
||||
incoming.soTimeout = 10_000
|
||||
val input = incoming.getInputStream().buffered()
|
||||
val header = StringBuilder()
|
||||
while (header.length < 4096 && !header.endsWith("\r\n\r\n")) {
|
||||
val next = input.read()
|
||||
if (next == -1) break
|
||||
header.append(next.toChar())
|
||||
}
|
||||
val verb = header.lineSequence().firstOrNull().orEmpty()
|
||||
received.put(verb)
|
||||
val output = incoming.getOutputStream()
|
||||
if (acceptCloudflare && verb == "CONNECT cp.cloudflare.com:443 HTTP/1.1") {
|
||||
Socket().use { upstream ->
|
||||
upstream.connect(InetSocketAddress("cp.cloudflare.com", 443), 5_000)
|
||||
upstream.soTimeout = 10_000
|
||||
output.write("HTTP/1.1 200 Connection established\r\n\r\n".toByteArray())
|
||||
output.flush()
|
||||
thread(isDaemon = true, name = "isolated-http-test-upload") {
|
||||
runCatching { input.copyTo(upstream.getOutputStream()) }
|
||||
}
|
||||
runCatching { upstream.getInputStream().copyTo(output) }
|
||||
}
|
||||
} else {
|
||||
output.write("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
output.flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val verified = runBlocking { UcvlEgressProbe.succeeds(listener.localPort) }
|
||||
if (acceptCloudflare) assertTrue("Second proxy tunnel must return HTTPS 204", verified) else assertFalse(verified)
|
||||
assertEquals("CONNECT www.gstatic.com:443 HTTP/1.1", received.poll(2, TimeUnit.SECONDS))
|
||||
assertEquals("CONNECT cp.cloudflare.com:443 HTTP/1.1", received.poll(2, TimeUnit.SECONDS))
|
||||
proxy.join(300)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,13 +11,22 @@ import com.v2ray.ang.handler.MmkvManager
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Run only in the dedicated disposable Android acceptance emulator. No production accounts. */
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class UpgradeSmokeTest {
|
||||
private fun requireEmulator() {
|
||||
val descriptor = InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("getprop ro.kernel.qemu")
|
||||
val value = android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).bufferedReader().use { it.readText().trim() }
|
||||
assertEquals("Never change a physical device's account fixture", "1", value)
|
||||
}
|
||||
@Test fun seedUpgrade() {
|
||||
requireEmulator()
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("1.0.0", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
assertEquals(InstrumentationRegistry.getArguments().getString("oldVersion") ?: "1.0.2",
|
||||
context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
UcvlSecureStore.saveToken("ucvl-upgrade-fixture-not-a-real-token")
|
||||
UcvlSecureStore.saveLastLogin("ucvl-upgrade-fixture")
|
||||
MmkvManager.encodeSettings("ucvl_test_expected_device_id", UcvlSecureStore.deviceId())
|
||||
@@ -25,8 +34,10 @@ class UpgradeSmokeTest {
|
||||
}
|
||||
|
||||
@Test fun verifyUpgrade() {
|
||||
requireEmulator()
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("1.0.1", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
assertEquals(InstrumentationRegistry.getArguments().getString("newVersion") ?: "1.0.3",
|
||||
context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
assertEquals("ucvl-upgrade-fixture", UcvlSecureStore.lastLogin())
|
||||
assertEquals(MmkvManager.decodeSettingsString("ucvl_test_expected_device_id"), UcvlSecureStore.deviceId())
|
||||
assertEquals("ucvl-upgrade-fixture-not-a-real-token", UcvlSecureStore.loadToken())
|
||||
@@ -35,6 +46,7 @@ class UpgradeSmokeTest {
|
||||
}
|
||||
|
||||
@Test fun loginVisibleAndEmptyFormIsSafe() {
|
||||
requireEmulator()
|
||||
UcvlSecureStore.clearToken()
|
||||
val inst = InstrumentationRegistry.getInstrumentation()
|
||||
val activity = inst.startActivitySync(Intent(inst.targetContext, UcvlMainActivity::class.java)
|
||||
@@ -48,10 +60,42 @@ class UpgradeSmokeTest {
|
||||
assertTrue(activity.findViewById<TextView>(R.id.loginError).text.contains("请输入"))
|
||||
}
|
||||
inst.waitForIdleSync()
|
||||
inst.uiAutomation.takeScreenshot().useBitmap { bitmap ->
|
||||
// isShown/idle alone can precede the first rendered frame (white screenshot).
|
||||
val rendered = CountDownLatch(1)
|
||||
inst.runOnMainSync {
|
||||
activity.window.decorView.postOnAnimation {
|
||||
activity.window.decorView.postOnAnimation { rendered.countDown() }
|
||||
}
|
||||
}
|
||||
assertTrue("Login did not render two frames", rendered.await(5, TimeUnit.SECONDS))
|
||||
val buttonCenter = IntArray(2)
|
||||
inst.runOnMainSync {
|
||||
val button = activity.findViewById<android.view.View>(R.id.loginButton)
|
||||
button.getLocationOnScreen(buttonCenter)
|
||||
// Sample the colored button away from its rounded corners and centered label.
|
||||
buttonCenter[0] += button.width / 6
|
||||
buttonCenter[1] += button.height / 2
|
||||
}
|
||||
// The scenery can contain a pale header and pale page at the same time.
|
||||
// A filled blue action button distinguishes a rendered frame from the splash.
|
||||
fun painted(bitmap: Bitmap): Boolean {
|
||||
val (x, y) = buttonCenter
|
||||
if (x !in 0 until bitmap.width || y !in 0 until bitmap.height) return false
|
||||
val pixel = bitmap.getPixel(x, y)
|
||||
return android.graphics.Color.blue(pixel) - android.graphics.Color.red(pixel) > 80
|
||||
}
|
||||
var screenshot = inst.uiAutomation.takeScreenshot()
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 10_000
|
||||
while (!painted(screenshot) && android.os.SystemClock.elapsedRealtime() < deadline) {
|
||||
screenshot.recycle()
|
||||
android.os.SystemClock.sleep(200)
|
||||
screenshot = inst.uiAutomation.takeScreenshot()
|
||||
}
|
||||
screenshot.useBitmap { bitmap ->
|
||||
java.io.File(inst.targetContext.filesDir, "acceptance-login.png").outputStream().use {
|
||||
bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
|
||||
}
|
||||
assertTrue("Login frame is still blank after rendering deadline", painted(bitmap))
|
||||
}
|
||||
inst.runOnMainSync { activity.finish() }
|
||||
}
|
||||
|
||||
@@ -161,6 +161,8 @@ object AppConfig {
|
||||
const val MSG_STATE_START = 3
|
||||
const val MSG_STATE_START_SUCCESS = 31
|
||||
const val MSG_STATE_START_FAILURE = 32
|
||||
const val MSG_STATE_VERIFYING = 33
|
||||
const val PREF_UCVL_MANAGED_PROFILE = "ucvl_managed_profile"
|
||||
const val MSG_STATE_STOP = 4
|
||||
const val MSG_STATE_STOP_SUCCESS = 41
|
||||
const val MSG_STATE_RESTART = 5
|
||||
|
||||
@@ -19,6 +19,18 @@ interface ServiceControl {
|
||||
*/
|
||||
fun stopService()
|
||||
|
||||
/** Proxy-only services have no Android VPN lease and retain their old behavior. */
|
||||
fun sessionEpoch(): Long = 0L
|
||||
|
||||
fun isSessionValid(epoch: Long): Boolean = true
|
||||
|
||||
/** Report success only while the service still owns the session being started. */
|
||||
fun reportIfSessionValid(epoch: Long, report: () -> Unit): Boolean {
|
||||
if (!isSessionValid(epoch)) return false
|
||||
report()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Protects the VPN socket.
|
||||
* @param socket The socket to protect.
|
||||
|
||||
@@ -38,6 +38,7 @@ import libv2ray.CoreController
|
||||
import libv2ray.ProcessFinder
|
||||
import java.lang.ref.SoftReference
|
||||
import java.net.InetSocketAddress
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
object CoreServiceManager {
|
||||
|
||||
@@ -46,6 +47,9 @@ object CoreServiceManager {
|
||||
private var currentConfig: ProfileItem? = null
|
||||
private var processFinder: XrayProcessFinder? = null
|
||||
private var browserDialer: IDialerService? = null
|
||||
private val coreLifecycleLock = Any()
|
||||
private val coreGeneration = AtomicLong(0)
|
||||
private val verifiedGeneration = AtomicLong(-1)
|
||||
|
||||
var serviceControl: SoftReference<ServiceControl>? = null
|
||||
set(value) {
|
||||
@@ -111,7 +115,10 @@ object CoreServiceManager {
|
||||
* Checks if the V2Ray service is running.
|
||||
* @return True if the service is running, false otherwise.
|
||||
*/
|
||||
fun isRunning() = coreController.isRunning
|
||||
fun isRunning(): Boolean {
|
||||
val control = serviceControl?.get() ?: return false
|
||||
return coreController.isRunning && control.isSessionValid(control.sessionEpoch())
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the name of the currently running server.
|
||||
@@ -202,26 +209,35 @@ object CoreServiceManager {
|
||||
return false
|
||||
}
|
||||
|
||||
val service = getService()
|
||||
if (service == null) {
|
||||
val control = serviceControl?.get()
|
||||
if (control == null) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Service is null")
|
||||
return false
|
||||
}
|
||||
val service = control.getService()
|
||||
val epoch = control.sessionEpoch()
|
||||
|
||||
try {
|
||||
doStartCoreLoop(service, vpnInterface)
|
||||
requireSession(control, epoch)
|
||||
doStartCoreLoop(service, vpnInterface, control, epoch)
|
||||
return true
|
||||
} catch (e: Exception) {
|
||||
val message = e.message?.takeUnless { it.isBlank() } ?: e.javaClass.simpleName
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-Manager: $message", e)
|
||||
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, message)
|
||||
NotificationManager.cancelNotification()
|
||||
if (serviceControl?.get() === control) stopCoreLoop()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private fun requireSession(control: ServiceControl, epoch: Long) {
|
||||
check(serviceControl?.get() === control && control.isSessionValid(epoch)) {
|
||||
"VPN permission or startup session was revoked"
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(Exception::class)
|
||||
private fun doStartCoreLoop(service: Service, vpnInterface: ParcelFileDescriptor?) {
|
||||
private fun doStartCoreLoop(service: Service, vpnInterface: ParcelFileDescriptor?, control: ServiceControl, epoch: Long) {
|
||||
val guid = MmkvManager.getSelectServer() ?: error("No server selected")
|
||||
val config = MmkvManager.decodeServerConfig(guid) ?: error("Failed to decode server config")
|
||||
|
||||
@@ -231,6 +247,7 @@ object CoreServiceManager {
|
||||
if (!result.status) {
|
||||
error(result.errorMessage.ifBlank { "Failed to get V2Ray config" })
|
||||
}
|
||||
requireSession(control, epoch)
|
||||
|
||||
val mFilter = IntentFilter(AppConfig.BROADCAST_ACTION_SERVICE)
|
||||
mFilter.addAction(Intent.ACTION_SCREEN_ON)
|
||||
@@ -251,7 +268,14 @@ object CoreServiceManager {
|
||||
|
||||
NotificationManager.showNotification(currentConfig)
|
||||
CoreNativeManager.reconcileBrowserDialer(dialerAddr)
|
||||
coreController.startLoop(result.content, tunFd)
|
||||
// Do not hold a VPN lease lock while entering native code: its callbacks
|
||||
// may arrive on another thread. A revoke invalidates that lease at once.
|
||||
synchronized(coreLifecycleLock) {
|
||||
requireSession(control, epoch)
|
||||
coreGeneration.incrementAndGet()
|
||||
coreController.startLoop(result.content, tunFd)
|
||||
}
|
||||
requireSession(control, epoch)
|
||||
|
||||
if (!coreController.isRunning) {
|
||||
error("Core failed to start")
|
||||
@@ -269,9 +293,32 @@ object CoreServiceManager {
|
||||
browserDialer!!.start(service, dialerAddr)
|
||||
}
|
||||
|
||||
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
|
||||
NotificationManager.startSpeedNotification()
|
||||
LogUtil.i(AppConfig.TAG, "StartCore-Manager: Core started successfully")
|
||||
requireSession(control, epoch)
|
||||
val generation = coreGeneration.get()
|
||||
if (service is CoreVpnService && guid == MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE)) {
|
||||
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_VERIFYING, "")
|
||||
service.verifyEgress(epoch) { ready ->
|
||||
if (ready) {
|
||||
reportConnected(service, control, epoch, generation)
|
||||
} else if (coreGeneration.get() == generation && control.reportIfSessionValid(epoch) {
|
||||
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, "代理出口验证失败,请稍后重连。")
|
||||
}) {
|
||||
control.stopService()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
check(reportConnected(service, control, epoch, generation)) { "VPN session was revoked before startup could be reported" }
|
||||
}
|
||||
}
|
||||
|
||||
private fun reportConnected(service: Service, control: ServiceControl, epoch: Long, generation: Long): Boolean {
|
||||
if (serviceControl?.get() !== control || coreGeneration.get() != generation || !coreController.isRunning) return false
|
||||
val reported = control.reportIfSessionValid(epoch) {
|
||||
verifiedGeneration.set(generation)
|
||||
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
|
||||
}
|
||||
if (reported && isRunning()) NotificationManager.startSpeedNotification()
|
||||
return reported
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -282,12 +329,17 @@ object CoreServiceManager {
|
||||
fun stopCoreLoop(): Boolean {
|
||||
val service = getService() ?: return false
|
||||
|
||||
if (coreController.isRunning) {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
coreController.stopLoop()
|
||||
} catch (e: Exception) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to stop V2Ray loop", e)
|
||||
val generation = coreGeneration.get()
|
||||
// Always schedule stop, even when revoke preceded native startup. The
|
||||
// serialized generation check also prevents an old stop killing a new core.
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
synchronized(coreLifecycleLock) {
|
||||
if (coreGeneration.get() == generation) {
|
||||
try {
|
||||
coreController.stopLoop()
|
||||
} catch (e: Exception) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to stop V2Ray loop", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -485,9 +537,15 @@ object CoreServiceManager {
|
||||
val serviceControl = serviceControl?.get() ?: return
|
||||
when (intent?.getIntExtra("key", 0)) {
|
||||
AppConfig.MSG_REGISTER_CLIENT -> {
|
||||
if (coreController.isRunning) {
|
||||
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_RUNNING, "")
|
||||
} else {
|
||||
val epoch = serviceControl.sessionEpoch()
|
||||
if (!coreController.isRunning || !serviceControl.reportIfSessionValid(epoch) {
|
||||
val state = if (verifiedGeneration.get() == coreGeneration.get()) {
|
||||
AppConfig.MSG_STATE_RUNNING
|
||||
} else {
|
||||
AppConfig.MSG_STATE_VERIFYING
|
||||
}
|
||||
MessageUtil.sendMsg2UI(serviceControl.getService(), state, "")
|
||||
}) {
|
||||
MessageUtil.sendMsg2UI(serviceControl.getService(), AppConfig.MSG_STATE_NOT_RUNNING, "")
|
||||
}
|
||||
}
|
||||
@@ -525,9 +583,9 @@ object CoreServiceManager {
|
||||
|
||||
Intent.ACTION_SCREEN_ON -> {
|
||||
LogUtil.i(AppConfig.TAG, "StartCore-Manager: Screen on")
|
||||
NotificationManager.startSpeedNotification()
|
||||
if (isRunning()) NotificationManager.startSpeedNotification()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import android.net.NetworkRequest
|
||||
import android.net.ProxyInfo
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.StrictMode
|
||||
import androidx.annotation.RequiresApi
|
||||
@@ -25,12 +27,15 @@ import com.v2ray.ang.handler.MmkvManager
|
||||
import com.v2ray.ang.handler.NotificationManager
|
||||
import com.v2ray.ang.handler.SettingsManager
|
||||
import com.v2ray.ang.util.LogUtil
|
||||
import com.v2ray.ang.util.MessageUtil
|
||||
import com.v2ray.ang.util.MyContextWrapper
|
||||
import com.v2ray.ang.util.Utils
|
||||
import java.lang.ref.SoftReference
|
||||
import com.v2ray.ang.ucvl.UcvlApiClient
|
||||
import com.v2ray.ang.ucvl.UcvlAuthorizationGuard
|
||||
import com.v2ray.ang.ucvl.UcvlEgressProbe
|
||||
import com.v2ray.ang.ucvl.UcvlSecureStore
|
||||
import com.v2ray.ang.ucvl.UcvlVpnStartupLease
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
@@ -40,11 +45,16 @@ import kotlinx.coroutines.launch
|
||||
|
||||
@SuppressLint("VpnServicePolicy")
|
||||
class CoreVpnService : VpnService(), ServiceControl {
|
||||
private lateinit var mInterface: ParcelFileDescriptor
|
||||
private var isRunning = false
|
||||
@Volatile private var mInterface: ParcelFileDescriptor? = null
|
||||
@Volatile private var isRunning = false
|
||||
@Volatile private var permissionRevoked = false
|
||||
@Volatile private var startupEpoch = 0L
|
||||
private val startupLease = UcvlVpnStartupLease()
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private var tun2SocksService: Tun2SocksControl? = null
|
||||
private val authorizationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private var authorizationJob: Job? = null
|
||||
private var egressJob: Job? = null
|
||||
|
||||
/**destroy
|
||||
* Unfortunately registerDefaultNetworkCallback is going to return our VPN interface: https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e
|
||||
@@ -94,6 +104,9 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
|
||||
override fun onRevoke() {
|
||||
LogUtil.w(AppConfig.TAG, "StartCore-VPN: Permission revoked")
|
||||
// onRevoke may arrive on Binder while establish/startLoop blocks main.
|
||||
// Invalidate first; cleanup must not race those main-thread operations.
|
||||
permissionRevoked = true
|
||||
stopAllService()
|
||||
}
|
||||
|
||||
@@ -103,48 +116,54 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
// }
|
||||
|
||||
override fun onDestroy() {
|
||||
startupLease.invalidate()
|
||||
stopAllServiceOnMain(false)
|
||||
authorizationScope.cancel()
|
||||
super.onDestroy()
|
||||
LogUtil.i(AppConfig.TAG, "StartCore-VPN: Service destroyed")
|
||||
|
||||
// Ensure VPN interface is properly closed when the service is destroyed without
|
||||
// going through stopAllService() (e.g. when killed unexpectedly). isRunning is
|
||||
// set to false at the start of stopAllService(), so this guard prevents a double-close.
|
||||
if (isRunning) {
|
||||
try {
|
||||
if (::mInterface.isInitialized) {
|
||||
mInterface.close()
|
||||
LogUtil.i(AppConfig.TAG, "StartCore-VPN: VPN interface closed in onDestroy")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface in onDestroy", e)
|
||||
}
|
||||
}
|
||||
|
||||
NotificationManager.cancelNotification()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (isRunning) return START_NOT_STICKY
|
||||
if (isSessionValid(startupEpoch)) return START_NOT_STICKY
|
||||
if (permissionRevoked) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val token = UcvlSecureStore.loadToken()
|
||||
if (token.isNullOrBlank()) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
LogUtil.i(AppConfig.TAG, "StartCore-VPN: Service command received")
|
||||
startupEpoch = startupLease.begin()
|
||||
NotificationManager.showNotification(null)
|
||||
setupVpnService()
|
||||
val configured = try {
|
||||
setupVpnService(startupEpoch)
|
||||
} catch (e: Exception) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: VPN setup failed", e)
|
||||
false
|
||||
}
|
||||
if (!configured) {
|
||||
MessageUtil.sendMsg2UI(this, AppConfig.MSG_STATE_START_FAILURE,
|
||||
"VPN permission or interface is no longer available")
|
||||
stopAllService()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
startService()
|
||||
if (isRunning) {
|
||||
if (isSessionValid(startupEpoch)) {
|
||||
authorizationJob?.cancel()
|
||||
authorizationJob = authorizationScope.launch {
|
||||
UcvlApiClient().use { api ->
|
||||
UcvlAuthorizationGuard.watch(token, UcvlSecureStore::loadToken,
|
||||
{ api.profile(it) }, {
|
||||
if (UcvlSecureStore.loadToken() == token) UcvlSecureStore.clearToken()
|
||||
sendBroadcast(Intent(UcvlAuthorizationGuard.ACTION_REVOKED).setPackage(packageName))
|
||||
if (UcvlSecureStore.loadToken() == token) {
|
||||
UcvlSecureStore.clearToken()
|
||||
sendBroadcast(Intent(UcvlAuthorizationGuard.ACTION_REVOKED).setPackage(packageName))
|
||||
}
|
||||
stopAllService()
|
||||
})
|
||||
}, sessionChanged = { stopAllService() })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,11 +176,13 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
}
|
||||
|
||||
override fun startService() {
|
||||
if (!::mInterface.isInitialized) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Interface not initialized")
|
||||
val vpnInterface = mInterface
|
||||
if (vpnInterface == null || !isSessionValid(startupEpoch)) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Interface or VPN session no longer valid")
|
||||
stopAllService()
|
||||
return
|
||||
}
|
||||
if (!CoreServiceManager.startCoreLoop(mInterface)) {
|
||||
if (!CoreServiceManager.startCoreLoop(vpnInterface)) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to start core loop")
|
||||
stopAllService()
|
||||
return
|
||||
@@ -172,6 +193,29 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
stopAllService(true)
|
||||
}
|
||||
|
||||
fun verifyEgress(epoch: Long, report: (Boolean) -> Unit) {
|
||||
egressJob?.cancel()
|
||||
egressJob = authorizationScope.launch {
|
||||
// The managed runtime uses its fixed SOCKS port plus one for HTTP.
|
||||
val ready = UcvlEgressProbe.succeeds(SettingsManager.getSocksPort() + 1)
|
||||
if (isSessionValid(epoch)) report(ready)
|
||||
}
|
||||
}
|
||||
|
||||
override fun sessionEpoch(): Long = startupEpoch
|
||||
|
||||
override fun isSessionValid(epoch: Long): Boolean {
|
||||
if (!startupLease.isValid(epoch) || !isRunning ||
|
||||
mInterface?.fileDescriptor?.valid() != true) return false
|
||||
val prepared = try { prepare(this) == null } catch (_: Exception) { false }
|
||||
return prepared && startupLease.isValid(epoch) && !permissionRevoked
|
||||
}
|
||||
|
||||
override fun reportIfSessionValid(epoch: Long, report: () -> Unit): Boolean {
|
||||
if (!isSessionValid(epoch)) return false
|
||||
return startupLease.reportIfValid(epoch, report)
|
||||
}
|
||||
|
||||
override fun vpnProtect(socket: Int): Boolean {
|
||||
return protect(socket)
|
||||
}
|
||||
@@ -187,28 +231,29 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
* Sets up the VPN service.
|
||||
* Prepares the VPN and configures it if preparation is successful.
|
||||
*/
|
||||
private fun setupVpnService() {
|
||||
private fun setupVpnService(epoch: Long): Boolean {
|
||||
if (!startupLease.isValid(epoch) || permissionRevoked) return false
|
||||
val prepare = prepare(this)
|
||||
if (prepare != null) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Permission not granted")
|
||||
stopSelf()
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
if (configureVpnService() != true) {
|
||||
if (!configureVpnService(epoch)) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Configuration failed")
|
||||
stopSelf()
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
if (!isSessionValid(epoch)) return false
|
||||
runTun2socks()
|
||||
return isSessionValid(epoch)
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the VPN service.
|
||||
* @return True if the VPN service was configured successfully, false otherwise.
|
||||
*/
|
||||
private fun configureVpnService(): Boolean {
|
||||
private fun configureVpnService(epoch: Long): Boolean {
|
||||
val builder = Builder()
|
||||
|
||||
// Configure network settings (addresses, routing and DNS)
|
||||
@@ -219,9 +264,8 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
|
||||
// Close the old interface since the parameters have been changed
|
||||
try {
|
||||
if (::mInterface.isInitialized) {
|
||||
mInterface.close()
|
||||
}
|
||||
mInterface?.close()
|
||||
mInterface = null
|
||||
} catch (e: Exception) {
|
||||
LogUtil.w(AppConfig.TAG, "Failed to close old interface", e)
|
||||
}
|
||||
@@ -231,9 +275,18 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
|
||||
// Create a new interface using the builder and save the parameters
|
||||
try {
|
||||
mInterface = builder.establish()!!
|
||||
if (!startupLease.isValid(epoch) || prepare(this) != null) return false
|
||||
val established = builder.establish() ?: return false
|
||||
// Keep ownership even if a subsequent permission check throws, so
|
||||
// the common failure cleanup always closes the newly created fd.
|
||||
mInterface = established
|
||||
if (!startupLease.isValid(epoch) || permissionRevoked || prepare(this) != null) {
|
||||
established.close()
|
||||
mInterface = null
|
||||
return false
|
||||
}
|
||||
isRunning = true
|
||||
return true
|
||||
return isSessionValid(epoch)
|
||||
} catch (e: Exception) {
|
||||
LogUtil.e(AppConfig.TAG, "Failed to establish VPN interface", e)
|
||||
stopAllService()
|
||||
@@ -363,12 +416,15 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
* Starts the tun2socks process with the appropriate parameters.
|
||||
*/
|
||||
private fun runTun2socks() {
|
||||
val epoch = startupEpoch
|
||||
val vpnInterface = mInterface ?: return
|
||||
if (!isSessionValid(epoch)) return
|
||||
if (SettingsManager.isUsingHevTun()) {
|
||||
tun2SocksService = TProxyService(
|
||||
context = applicationContext,
|
||||
vpnInterface = mInterface,
|
||||
isRunningProvider = { isRunning },
|
||||
restartCallback = { runTun2socks() }
|
||||
vpnInterface = vpnInterface,
|
||||
isRunningProvider = { isSessionValid(epoch) },
|
||||
restartCallback = { mainHandler.post { if (isSessionValid(epoch)) runTun2socks() } }
|
||||
)
|
||||
} else {
|
||||
tun2SocksService = null
|
||||
@@ -378,6 +434,21 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
}
|
||||
|
||||
private fun stopAllService(isForced: Boolean = true) {
|
||||
val epoch = startupEpoch
|
||||
startupLease.invalidate()
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
stopAllServiceOnMain(isForced)
|
||||
} else {
|
||||
mainHandler.post {
|
||||
// A cleanup posted by an older session must not stop a later one.
|
||||
if (startupEpoch == epoch) stopAllServiceOnMain(isForced)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopAllServiceOnMain(isForced: Boolean) {
|
||||
egressJob?.cancel()
|
||||
egressJob = null
|
||||
authorizationJob?.cancel()
|
||||
authorizationJob = null
|
||||
// val configName = defaultDPreference.getPrefString(PREF_CURR_CONFIG_GUID, "")
|
||||
@@ -405,24 +476,14 @@ class CoreVpnService : VpnService(), ServiceControl {
|
||||
//in a row for several times. You will find that later created v2ray core report port in use
|
||||
//which means the first v2ray core somehow failed to stop and release the port.
|
||||
stopSelf()
|
||||
|
||||
// Add a small delay to allow the async core stop operation to complete
|
||||
// before closing the VPN interface, preventing a race condition that can
|
||||
// leave the VPN icon in the status bar after stopping the service.
|
||||
try {
|
||||
Thread.sleep(100)
|
||||
} catch (e: InterruptedException) {
|
||||
LogUtil.w(AppConfig.TAG, "StartCore-VPN: Sleep interrupted", e)
|
||||
}
|
||||
|
||||
try {
|
||||
if (::mInterface.isInitialized) {
|
||||
mInterface.close()
|
||||
LogUtil.i(AppConfig.TAG, "StartCore-VPN: VPN interface closed")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface", e)
|
||||
}
|
||||
}
|
||||
// Close on every failure/destruction, including revoke before native start.
|
||||
val vpnInterface = mInterface
|
||||
mInterface = null
|
||||
try {
|
||||
vpnInterface?.close()
|
||||
} catch (e: Exception) {
|
||||
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
/** Runs in the VPN service, so closing the activity cannot bypass revocation. */
|
||||
object UcvlAuthorizationGuard {
|
||||
@@ -14,23 +15,34 @@ object UcvlAuthorizationGuard {
|
||||
loadToken: () -> String?,
|
||||
check: suspend (String) -> Unit,
|
||||
revoke: () -> Unit,
|
||||
sessionChanged: () -> Unit,
|
||||
intervalMillis: Long = 60_000,
|
||||
) {
|
||||
fun stopIfSessionChanged(): Boolean {
|
||||
if (loadToken() == token) return false
|
||||
// Stop the old tunnel, but do not revoke or hide a replacement login.
|
||||
sessionChanged()
|
||||
return true
|
||||
}
|
||||
while (currentCoroutineContext().isActive) {
|
||||
if (loadToken() != token) { revoke(); return }
|
||||
if (stopIfSessionChanged()) return
|
||||
try {
|
||||
check(token)
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (error: UcvlApiException) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
if (error.statusCode == 401 || error.statusCode == 403) {
|
||||
// A late reply for an old login must never erase a newer login.
|
||||
if (loadToken() == token) revoke()
|
||||
if (!stopIfSessionChanged()) revoke()
|
||||
return
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Transient loss of connectivity is not evidence that an account was revoked.
|
||||
}
|
||||
currentCoroutineContext().ensureActive()
|
||||
// Recheck immediately even after success/temporary failure, not 60 seconds later.
|
||||
if (stopIfSessionChanged()) return
|
||||
delay(intervalMillis)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,12 @@ import java.net.URLEncoder
|
||||
object UcvlConfigBridge {
|
||||
/** Keep the server's complete rules, credentials and node selection. Adapt only local runtime. */
|
||||
fun buildRuntime(config: JsonObject, remarks: String, socksPort: Int, httpPort: Int,
|
||||
socksUsername: String? = null, socksPassword: String? = null): JsonObject {
|
||||
socksUsername: String? = null, socksPassword: String? = null,
|
||||
gatewayAddress: String? = null): JsonObject {
|
||||
require(socksPort in 1024..65535 && httpPort in 1024..65535 && socksPort != httpPort)
|
||||
buildVlessUri(config, remarks) // Validate the supported server contract before saving.
|
||||
val result = config.deepCopy()
|
||||
overrideProxyServerAddress(result, gatewayAddress)
|
||||
buildVlessUri(result, remarks) // Validate the supported server contract before saving.
|
||||
result.addProperty("remarks", remarks)
|
||||
result.add("log", JsonParser.parseString("""{"loglevel":"warning"}"""))
|
||||
val inbounds = JsonArray()
|
||||
@@ -52,11 +54,50 @@ object UcvlConfigBridge {
|
||||
val rules = JsonArray()
|
||||
rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["socks-in","http-in"],"port":"53","outboundTag":"ucvl-dns-out"}"""))
|
||||
rules.add(JsonParser.parseString("""{"type":"field","inboundTag":["ucvl-dns"],"outboundTag":"proxy"}"""))
|
||||
// The app uses the loopback HTTP port for its HTTPS startup checks.
|
||||
// Regular VPN traffic arrives over SOCKS and keeps the platform rules.
|
||||
rules.add(JsonObject().apply {
|
||||
addProperty("type", "field")
|
||||
add("inboundTag", JsonArray().apply { add("http-in") })
|
||||
add("domain", JsonArray().apply {
|
||||
UcvlEgressProbe.targets.forEach { add("full:${it.host}") }
|
||||
})
|
||||
addProperty("outboundTag", "proxy")
|
||||
})
|
||||
originalRules.forEach { rules.add(it.deepCopy()) }
|
||||
routing.add("rules", rules)
|
||||
return result
|
||||
}
|
||||
|
||||
fun overrideProxyServerAddress(config: JsonObject, gatewayAddress: String?): JsonObject {
|
||||
val address = gatewayAddress?.trim().orEmpty()
|
||||
if (address.isEmpty()) return config
|
||||
val outbounds = config.getAsJsonArray("outbounds") ?: return config
|
||||
outbounds.map { it.asJsonObject }
|
||||
.filter { it.get("tag")?.asString == "proxy" }
|
||||
.forEach { outbound ->
|
||||
outbound.getAsJsonObject("settings")?.getAsJsonArray("vnext")
|
||||
?.forEach { it.asJsonObject.addProperty("address", address) }
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
fun isPublicIpv4(value: String): Boolean {
|
||||
val parts = value.split('.').mapNotNull { it.toIntOrNull() }
|
||||
if (parts.size != 4 || parts.any { it !in 0..255 }) return false
|
||||
val (a, b, c) = parts
|
||||
if (a == 0 || a == 10 || a == 127 || a >= 224) return false
|
||||
if (a == 100 && b in 64..127) return false
|
||||
if (a == 169 && b == 254) return false
|
||||
if (a == 172 && b in 16..31) return false
|
||||
if (a == 192 && b == 168) return false
|
||||
if (a == 192 && b == 0 && (c == 0 || c == 2)) return false
|
||||
if (a == 198 && (b == 18 || b == 19)) return false
|
||||
if (a == 198 && b == 51 && c == 100) return false
|
||||
if (a == 203 && b == 0 && c == 113) return false
|
||||
return true
|
||||
}
|
||||
|
||||
fun buildVlessUri(config: JsonObject, remarks: String): String {
|
||||
val outbounds = config.getAsJsonArray("outbounds")
|
||||
?: throw IllegalArgumentException("线路配置没有出站信息。")
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Proxy
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resume
|
||||
|
||||
internal object UcvlEgressProbe {
|
||||
val targets = listOf(
|
||||
"https://www.gstatic.com/generate_204".toHttpUrl(),
|
||||
"https://cp.cloudflare.com/generate_204".toHttpUrl(),
|
||||
)
|
||||
|
||||
suspend fun succeeds(port: Int): Boolean {
|
||||
val client = OkHttpClient.Builder()
|
||||
.proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("127.0.0.1", port)))
|
||||
.followRedirects(false)
|
||||
.followSslRedirects(false)
|
||||
.retryOnConnectionFailure(false)
|
||||
.callTimeout(6, TimeUnit.SECONDS)
|
||||
.build()
|
||||
try {
|
||||
return targets.any { target ->
|
||||
val request = Request.Builder().url(target).build()
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
val call = client.newCall(request)
|
||||
continuation.invokeOnCancellation { call.cancel() }
|
||||
call.enqueue(object : Callback {
|
||||
override fun onFailure(call: Call, e: IOException) = continuation.resume(false)
|
||||
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
response.use { continuation.resume(it.code == 204) }
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
client.connectionPool.evictAll()
|
||||
client.dispatcher.executorService.shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.ArrayAdapter
|
||||
import android.widget.Button
|
||||
@@ -27,6 +28,7 @@ import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import com.v2ray.ang.AppConfig
|
||||
import com.v2ray.ang.R
|
||||
import com.v2ray.ang.BuildConfig
|
||||
@@ -44,6 +46,10 @@ import java.util.Locale
|
||||
|
||||
class UcvlMainActivity : AppCompatActivity() {
|
||||
private val api = UcvlApiClient()
|
||||
private val releases = UcvlReleaseChecker()
|
||||
private var checkingUpdates = false
|
||||
private var availableUpdate: UcvlUpdateOffer? = null
|
||||
private var promptedUpdateVersion: String? = null
|
||||
private val mainViewModel: MainViewModel by viewModels()
|
||||
private var profile: UcvlProfile? = null
|
||||
private var busy = false
|
||||
@@ -81,6 +87,7 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
} else {
|
||||
pendingStart = false
|
||||
setConnectionState(false, "未连接", "需要允许系统 VPN 连接请求")
|
||||
availableUpdate?.let { showUpdateOffer(it, automatic = true) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +103,7 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
if (intent?.action != UcvlTraffic.ACTION) return
|
||||
val up = intent.getLongExtra("up_speed", 0)
|
||||
val down = intent.getLongExtra("down_speed", 0)
|
||||
proxySpeed.text = "↑ ${formatBytes(up)}/s ↓ ${formatBytes(down)}/s"
|
||||
proxySpeed.text = "↑ ${UcvlTrafficFormat.speed(up)} ↓ ${UcvlTrafficFormat.speed(down)}"
|
||||
proxyTotal.text = "本次代理 ${formatBytes(intent.getLongExtra("total", 0))} · 仅统计 proxy 出站"
|
||||
speedPoints.addLast(up to down)
|
||||
while (speedPoints.size > 40) speedPoints.removeFirst()
|
||||
@@ -104,8 +111,22 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun prepareScenicWindow() {
|
||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
|
||||
if (Build.VERSION.SDK_INT < 35) {
|
||||
// Older releases keep the theme's opaque bars, including its night colors.
|
||||
val surface = ContextCompat.getColor(this, R.color.ucvl_surface)
|
||||
window.statusBarColor = surface
|
||||
window.navigationBarColor = surface
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
promptedUpdateVersion = savedInstanceState?.getString("ucvl.promptedUpdateVersion")
|
||||
prepareScenicWindow()
|
||||
setContentView(R.layout.activity_ucvl_main)
|
||||
val root = findViewById<View>(R.id.ucvlRoot)
|
||||
ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
|
||||
@@ -115,6 +136,7 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
insets
|
||||
}
|
||||
WindowCompat.getInsetsController(window, root).isAppearanceLightStatusBars = true
|
||||
WindowCompat.getInsetsController(window, root).isAppearanceLightNavigationBars = true
|
||||
bindViews()
|
||||
setupActions()
|
||||
setupCoreState()
|
||||
@@ -131,6 +153,17 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
showDashboardLoading()
|
||||
refreshProfile(token, initial = true)
|
||||
}
|
||||
checkUpdates(manual = false)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
availableUpdate?.let { showUpdateOffer(it, automatic = true) }
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
outState.putString("ucvl.promptedUpdateVersion", promptedUpdateVersion)
|
||||
super.onSaveInstanceState(outState)
|
||||
}
|
||||
|
||||
private fun bindViews() {
|
||||
@@ -161,6 +194,11 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
private fun setupActions() {
|
||||
findViewById<Button>(R.id.checkUpdatesButton).setOnClickListener {
|
||||
val offer = availableUpdate
|
||||
if (offer == null) checkUpdates(manual = true)
|
||||
else showUpdateOffer(offer, automatic = false)
|
||||
}
|
||||
findViewById<View>(R.id.registerButton).setOnClickListener {
|
||||
openWeb("https://vpn.toplc.cn/register/")
|
||||
}
|
||||
@@ -210,6 +248,9 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
mainViewModel.isRunning.observe(this) { running ->
|
||||
applyRunningState(running == true)
|
||||
}
|
||||
mainViewModel.isStarting.observe(this) {
|
||||
applyRunningState(mainViewModel.isRunning.value == true)
|
||||
}
|
||||
mainViewModel.updateTestResultAction.observe(this) { result ->
|
||||
if (!result.isNullOrBlank() && mainViewModel.isRunning.value == true) {
|
||||
statusDetail.text = result
|
||||
@@ -274,12 +315,12 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
private fun toggleConnection() {
|
||||
if (busy) return
|
||||
if (mainViewModel.isRunning.value == true) {
|
||||
if (mainViewModel.isRunning.value == true || mainViewModel.isStarting.value == true) {
|
||||
CoreServiceManager.stopVService(this)
|
||||
setConnectionState(false, "正在断开", "系统将自动恢复原网络")
|
||||
return
|
||||
}
|
||||
if (busy) return
|
||||
val currentProfile = profile ?: return
|
||||
val route = currentProfile.routeModes.getOrNull(routeSpinner.selectedItemPosition)
|
||||
if (currentProfile.nodes.isEmpty() || route == null) {
|
||||
@@ -313,11 +354,12 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
MmkvManager.encodeSettings(AppConfig.PREF_PER_APP_PROXY, false)
|
||||
MmkvManager.encodeSettings(AppConfig.PREF_APPEND_HTTP_PROXY, false)
|
||||
val raw = UcvlConfigBridge.buildRuntime(response.config, response.node.name, port, port + 1,
|
||||
SettingsManager.getSocksUsername(), SettingsManager.getSocksPassword()).toString()
|
||||
val ownedGuid = MmkvManager.decodeSettingsString(OWNED_PROFILE_KEY).orEmpty()
|
||||
SettingsManager.getSocksUsername(), SettingsManager.getSocksPassword(),
|
||||
response.gateway?.preferredAddress()).toString()
|
||||
val ownedGuid = MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE).orEmpty()
|
||||
val selected = MmkvManager.encodeServerConfig(ownedGuid, CustomFmt.parse(raw))
|
||||
MmkvManager.encodeServerRaw(selected, raw)
|
||||
MmkvManager.encodeSettings(OWNED_PROFILE_KEY, selected)
|
||||
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, selected)
|
||||
MmkvManager.setSelectServer(selected)
|
||||
}
|
||||
MmkvManager.encodeSettings(LAST_NODE_KEY, response.node.slug)
|
||||
@@ -400,7 +442,7 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
val identity = if (value.identityType == "employee") "内部员工" else "外部联系人"
|
||||
accountText.text = "${value.email} · $identity"
|
||||
|
||||
routeSpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, value.routeModes)
|
||||
routeSpinner.adapter = ArrayAdapter(this, R.layout.ucvl_spinner_item, value.routeModes)
|
||||
val lastRoute = MmkvManager.decodeSettingsString(LAST_ROUTE_KEY, "smart").orEmpty()
|
||||
value.routeModes.indexOfFirst { it.id == lastRoute }.takeIf { it >= 0 }?.let(routeSpinner::setSelection)
|
||||
usageChart.setPoints(value.usageHistory.orEmpty().map { it.uploadBytes to it.downloadBytes })
|
||||
@@ -429,13 +471,26 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
val route = profile?.routeModes?.getOrNull(routeSpinner.selectedItemPosition)
|
||||
currentNode.text = "$nodeName · 平台自动调度"
|
||||
setConnectionState(true, "已安全连接", listOfNotNull(nodeName, route?.name).joinToString(" · "))
|
||||
} else if (mainViewModel.isStarting.value == true) {
|
||||
setConnectionState(false, "正在验证连接", "通过 VPN 检查 HTTPS 是否可用")
|
||||
} else if (statusTitle.text != "连接失败" && statusTitle.text != "本地直连") {
|
||||
currentNode.text = "连接后显示实际工作节点"
|
||||
proxySpeed.text = "↑ 0 B/s ↓ 0 B/s"
|
||||
setConnectionState(false, "未连接", "点击连接,由平台策略自动选择节点")
|
||||
}
|
||||
connectButton.text = if (running) "断开" else "连接"
|
||||
routeSpinner.isEnabled = !running && !busy
|
||||
updateConnectControls()
|
||||
}
|
||||
|
||||
private fun updateConnectControls() {
|
||||
val running = mainViewModel.isRunning.value == true
|
||||
val verifying = mainViewModel.isStarting.value == true
|
||||
connectButton.text = when {
|
||||
running -> "断开"
|
||||
verifying -> "取消"
|
||||
else -> "连接"
|
||||
}
|
||||
connectButton.isEnabled = running || verifying || (!busy && profile?.nodes?.isNotEmpty() == true)
|
||||
routeSpinner.isEnabled = !busy && !running && !verifying
|
||||
}
|
||||
|
||||
private fun setConnectionState(connected: Boolean, title: String, detail: String) {
|
||||
@@ -450,15 +505,15 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
private fun setBusy(value: Boolean, message: String = "") {
|
||||
busy = value
|
||||
loginButton.isEnabled = !value
|
||||
connectButton.isEnabled = !value && profile?.nodes?.isNotEmpty() == true
|
||||
updateConnectControls()
|
||||
refreshButton.isEnabled = !value
|
||||
logoutButton.isEnabled = !value
|
||||
exitButton.isEnabled = !value
|
||||
routeSpinner.isEnabled = !value && mainViewModel.isRunning.value != true
|
||||
if (value && dashboardPanel.visibility == View.VISIBLE && message.isNotBlank()) {
|
||||
statusDetail.text = message
|
||||
}
|
||||
loginButton.text = if (value && loginPanel.visibility == View.VISIBLE) "请稍候…" else "安全登录"
|
||||
if (!value) availableUpdate?.let { showUpdateOffer(it, automatic = true) }
|
||||
}
|
||||
|
||||
private fun friendlyError(exception: Exception): String = when (exception) {
|
||||
@@ -467,6 +522,41 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
else -> exception.message?.takeIf { it.isNotBlank() } ?: "网络连接失败,请检查当前网络。"
|
||||
}
|
||||
|
||||
private fun checkUpdates(manual: Boolean) {
|
||||
if (checkingUpdates) return
|
||||
checkingUpdates = true
|
||||
val button = findViewById<Button>(R.id.checkUpdatesButton)
|
||||
val status = findViewById<TextView>(R.id.updateStatus)
|
||||
button.isEnabled = false
|
||||
if (manual) status.text = "正在检查公司 Git…"
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
availableUpdate = releases.latest(BuildConfig.VERSION_NAME)
|
||||
val offer = availableUpdate
|
||||
button.text = offer?.let { "下载新版本 ${it.version}" } ?: "检查软件更新"
|
||||
status.text = if (offer != null) "新版本已发布,可覆盖升级保留配置" else if (manual) "暂无更新的 Android 正式版" else ""
|
||||
if (offer != null && !manual) showUpdateOffer(offer, automatic = true)
|
||||
} catch (cancelled: kotlinx.coroutines.CancellationException) {
|
||||
throw cancelled
|
||||
} catch (_: Exception) {
|
||||
if (manual) status.text = "暂未取得版本信息,VPN 连接不受影响"
|
||||
} finally {
|
||||
checkingUpdates = false
|
||||
button.isEnabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showUpdateOffer(offer: UcvlUpdateOffer, automatic: Boolean) {
|
||||
if (isFinishing || isDestroyed || !lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) return
|
||||
if (automatic && (busy || pendingStart || promptedUpdateVersion == offer.version)) return
|
||||
promptedUpdateVersion = offer.version
|
||||
MaterialAlertDialogBuilder(this).setTitle("发现新版本 ${offer.version}")
|
||||
.setMessage("从公司 Git 下载并使用系统安装器覆盖升级,保留账号和配置。不要先卸载旧版本。Android 要求的安装授权仍需本人确认。")
|
||||
.setPositiveButton("前往下载") { _, _ -> openWeb(offer.url) }
|
||||
.setNegativeButton("暂不更新", null).show()
|
||||
}
|
||||
|
||||
private fun openWeb(url: String) {
|
||||
try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
|
||||
catch (_: android.content.ActivityNotFoundException) {
|
||||
@@ -490,6 +580,7 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
override fun onDestroy() {
|
||||
unregisterReceiver(trafficReceiver)
|
||||
api.close()
|
||||
releases.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -497,7 +588,6 @@ class UcvlMainActivity : AppCompatActivity() {
|
||||
private const val SOURCE_URL = "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android"
|
||||
private const val LAST_NODE_KEY = "ucvl_last_node"
|
||||
private const val LAST_NODE_NAME_KEY = "ucvl_last_node_name"
|
||||
private const val OWNED_PROFILE_KEY = "ucvl_managed_profile"
|
||||
private const val LAST_ROUTE_KEY = "ucvl_last_route"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,11 +49,21 @@ data class UcvlRouteMode(val id: String, val name: String) {
|
||||
}
|
||||
|
||||
data class UcvlConfigResponse(
|
||||
@SerializedName("config_contract") val configContract: Int? = null,
|
||||
val gateway: UcvlGateway? = null,
|
||||
val node: UcvlNode,
|
||||
@SerializedName("route_mode") val routeMode: String,
|
||||
val config: JsonObject,
|
||||
)
|
||||
|
||||
data class UcvlGateway(
|
||||
val host: String = "",
|
||||
val ipv4: String? = null,
|
||||
) {
|
||||
fun preferredAddress(): String? = ipv4?.takeIf(UcvlConfigBridge::isPublicIpv4)
|
||||
?: host.trim().takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
data class UcvlApiError(val error: String? = null)
|
||||
|
||||
class UcvlApiException(val statusCode: Int, message: String) : Exception(message)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
import java.net.Proxy
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
data class UcvlUpdateOffer(val version: String, val url: String, val size: Long)
|
||||
|
||||
/** Anonymous Git lookups never share platform credentials or control the VPN. */
|
||||
class UcvlReleaseChecker : Closeable {
|
||||
private val client = OkHttpClient.Builder().proxy(Proxy.NO_PROXY)
|
||||
.followRedirects(false).followSslRedirects(false)
|
||||
.connectTimeout(10, TimeUnit.SECONDS).callTimeout(20, TimeUnit.SECONDS).build()
|
||||
|
||||
suspend fun latest(current: String): UcvlUpdateOffer? = withContext(Dispatchers.IO) {
|
||||
// One deadline covers every page; a shared cross-platform repository can
|
||||
// place Android releases beyond the first page after many Windows releases.
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20)
|
||||
lookup(current) { page ->
|
||||
val call = client.newCall(Request.Builder().url("$RELEASE_API&page=$page")
|
||||
.header("Accept", "application/json").get().build())
|
||||
call.timeout().deadlineNanoTime(deadline)
|
||||
call.execute().use { response ->
|
||||
if (!response.isSuccessful) throw IOException("暂时无法读取公司 Git 版本列表。")
|
||||
val body = response.body
|
||||
if (body.contentLength() > MAX_METADATA) throw IOException("版本列表过大。")
|
||||
// Bound decoded body size as well, including chunked/gzip responses.
|
||||
val source = body.source()
|
||||
source.request(MAX_METADATA + 1)
|
||||
if (source.buffer.size > MAX_METADATA) throw IOException("版本列表过大。")
|
||||
source.readUtf8()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
client.dispatcher.cancelAll()
|
||||
cleanup.execute {
|
||||
client.connectionPool.evictAll()
|
||||
client.dispatcher.executorService.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RELEASE_API = "https://pro.ucvl.cn/api/v1/repos/admin/ucvl-software-downloads/releases?limit=50"
|
||||
private const val DOWNLOAD_ROOT = "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/"
|
||||
private const val MAX_METADATA = 1024L * 1024
|
||||
private const val MAX_TOTAL_METADATA = 4L * MAX_METADATA
|
||||
private const val PAGE_SIZE = 50
|
||||
private const val MAX_PAGES = 10
|
||||
private val tagPattern = Regex("^android-v(\\d+\\.\\d+\\.\\d+)$")
|
||||
private val versionPattern = Regex("^(\\d+)\\.(\\d+)\\.(\\d+)$")
|
||||
private val cleanup = Executors.newSingleThreadExecutor { work ->
|
||||
Thread(work, "UCVL-release-cleanup").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
private fun parts(version: String): List<Int> = versionPattern.matchEntire(version)?.groupValues
|
||||
?.drop(1)?.map { it.toIntOrNull() ?: throw IOException("无效版本号。") }
|
||||
?: throw IOException("无效版本号。")
|
||||
|
||||
private fun compare(left: List<Int>, right: List<Int>): Int {
|
||||
for (index in 0..2) if (left[index] != right[index]) return left[index].compareTo(right[index])
|
||||
return 0
|
||||
}
|
||||
|
||||
internal fun select(json: String, current: String): UcvlUpdateOffer? {
|
||||
return select(array(json), current)
|
||||
}
|
||||
|
||||
internal suspend fun lookup(current: String, loadPage: suspend (Int) -> String): UcvlUpdateOffer? {
|
||||
val releases = JsonArray()
|
||||
var bytes = 0L
|
||||
for (page in 1..MAX_PAGES) {
|
||||
val text = loadPage(page)
|
||||
val size = text.toByteArray(Charsets.UTF_8).size.toLong()
|
||||
bytes += size
|
||||
if (size > MAX_METADATA || bytes > MAX_TOTAL_METADATA) throw IOException("版本列表过大。")
|
||||
val rows = array(text)
|
||||
releases.addAll(rows)
|
||||
if (rows.size() < PAGE_SIZE) return select(releases, current)
|
||||
}
|
||||
throw IOException("版本列表分页过多,请稍后重试或从公司发布页下载。")
|
||||
}
|
||||
|
||||
private fun array(text: String): JsonArray = try {
|
||||
JsonParser.parseString(text).asJsonArray
|
||||
} catch (error: RuntimeException) {
|
||||
throw IOException("版本列表格式异常。", error)
|
||||
}
|
||||
|
||||
private fun select(rows: JsonArray, current: String): UcvlUpdateOffer? {
|
||||
val installed = parts(current.substringBefore('-').substringBefore('+'))
|
||||
val releases = rows.filter { it.isJsonObject }.map { it.asJsonObject }
|
||||
.mapNotNull { release ->
|
||||
// Malformed records for other products must not hide valid
|
||||
// Android updates. Missing flags remain ineligible.
|
||||
val tag = release.get("tag_name")?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }
|
||||
?.asString.orEmpty()
|
||||
val match = tagPattern.matchEntire(tag) ?: return@mapNotNull null
|
||||
if (!release.isFalse("draft") || !release.isFalse("prerelease")) return@mapNotNull null
|
||||
val version = match.groupValues[1]
|
||||
val parsed = try { parts(version) } catch (_: IOException) { return@mapNotNull null }
|
||||
Triple(release, version, parsed)
|
||||
}
|
||||
val selected = releases.maxWithOrNull { left, right -> compare(left.third, right.third) } ?: return null
|
||||
if (compare(selected.third, installed) <= 0) return null
|
||||
val version = selected.second
|
||||
val filename = "UCVL-Zonghengjia-$version-android-universal.apk"
|
||||
// Universal is an explicit cross-ABI package; never offer an arbitrary
|
||||
// first attachment, a Windows EXE, or a different publisher's APK.
|
||||
val assets = selected.first.get("assets")?.takeIf { it.isJsonArray }?.asJsonArray
|
||||
?.filter { it.isJsonObject }?.map { it.asJsonObject }
|
||||
?.filter { it.get("name")?.takeIf { value -> value.isJsonPrimitive }?.asString == filename }
|
||||
?: throw IOException("正式版本缺少 Android 安装包列表。")
|
||||
if (assets.size != 1) throw IOException("正式版本缺少唯一的 Android 通用安装包。")
|
||||
val size = assets.single().get("size")?.asLong ?: 0
|
||||
if (size <= 0 || size > 250L * 1024 * 1024) throw IOException("安装包大小异常。")
|
||||
return UcvlUpdateOffer(version, "$DOWNLOAD_ROOT${selected.first.get("tag_name").asString}/$filename", size)
|
||||
}
|
||||
|
||||
private fun JsonObject.isFalse(name: String): Boolean = get(name)?.let {
|
||||
it.isJsonPrimitive && it.asJsonPrimitive.isBoolean && !it.asBoolean
|
||||
} == true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
/** Proxy speed uses KB/s or larger units, including idle and very small samples. */
|
||||
object UcvlTrafficFormat {
|
||||
fun speed(bytesPerSecond: Long): String {
|
||||
if (bytesPerSecond <= 0) return "0.0 KB/s"
|
||||
var amount = bytesPerSecond.toDouble() / 1024
|
||||
if (amount < 0.1) return "<0.1 KB/s"
|
||||
val units = arrayOf("KB/s", "MB/s", "GB/s", "TB/s")
|
||||
var unit = 0
|
||||
while (amount >= 1024 && unit < units.lastIndex) { amount /= 1024; unit++ }
|
||||
return String.format(Locale.US, "%.1f %s", amount, units[unit])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* A startup owns one epoch. Android can revoke it on a Binder thread while the
|
||||
* main thread is still establishing the TUN or starting native code.
|
||||
*
|
||||
* Never hold [reportLock] around Android permission calls, native start/stop, or
|
||||
* cleanup. It only orders invalidation with short, final state reports.
|
||||
*/
|
||||
class UcvlVpnStartupLease {
|
||||
private val state = AtomicLong(0)
|
||||
private val reportLock = Any()
|
||||
|
||||
fun begin(): Long = synchronized(reportLock) {
|
||||
val next = (state.get() and -2L) + 3L
|
||||
state.set(next)
|
||||
next
|
||||
}
|
||||
|
||||
fun invalidate() = synchronized(reportLock) {
|
||||
state.set(state.get() and -2L)
|
||||
}
|
||||
|
||||
fun isValid(epoch: Long): Boolean = epoch and 1L == 1L && state.get() == epoch
|
||||
|
||||
fun reportIfValid(epoch: Long, report: () -> Unit): Boolean = synchronized(reportLock) {
|
||||
if (!isValid(epoch)) return@synchronized false
|
||||
report()
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
var keywordFilter = ""
|
||||
val serversCache = mutableListOf<ServersCache>()
|
||||
val isRunning by lazy { MutableLiveData<Boolean>() }
|
||||
val isStarting by lazy { MutableLiveData(false) }
|
||||
val updateListAction by lazy { MutableLiveData<Int>() }
|
||||
val updateTestResultAction by lazy { MutableLiveData<String>() }
|
||||
private val tcpingTestScope by lazy { CoroutineScope(Dispatchers.IO) }
|
||||
@@ -457,15 +458,22 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
when (intent?.getIntExtra("key", 0)) {
|
||||
AppConfig.MSG_STATE_RUNNING -> {
|
||||
isRunning.value = true
|
||||
isStarting.value = false
|
||||
}
|
||||
|
||||
AppConfig.MSG_STATE_NOT_RUNNING -> {
|
||||
isRunning.value = false
|
||||
isStarting.value = false
|
||||
}
|
||||
|
||||
AppConfig.MSG_STATE_VERIFYING -> {
|
||||
isStarting.value = true
|
||||
}
|
||||
|
||||
AppConfig.MSG_STATE_START_SUCCESS -> {
|
||||
getApplication<AngApplication>().toastSuccess(R.string.toast_services_success)
|
||||
isRunning.value = true
|
||||
isStarting.value = false
|
||||
}
|
||||
|
||||
AppConfig.MSG_STATE_START_FAILURE -> {
|
||||
@@ -476,10 +484,12 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
getApplication<AngApplication>().toastError(R.string.toast_services_failure)
|
||||
}
|
||||
isRunning.value = false
|
||||
isStarting.value = false
|
||||
}
|
||||
|
||||
AppConfig.MSG_STATE_STOP_SUCCESS -> {
|
||||
isRunning.value = false
|
||||
isStarting.value = false
|
||||
}
|
||||
|
||||
AppConfig.MSG_MEASURE_DELAY_SUCCESS -> {
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.3 MiB |
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<solid android:color="@color/ucvl_glass_white" />
|
||||
<corners android:radius="18dp" />
|
||||
<stroke android:width="1dp" android:color="@color/ucvl_glass_border" />
|
||||
</shape>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<gradient
|
||||
android:angle="270"
|
||||
android:startColor="#D9F3F7FC"
|
||||
android:centerColor="#26F3F7FC"
|
||||
android:endColor="#D9F3F7FC" />
|
||||
</shape>
|
||||
@@ -1,390 +1,482 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:id="@+id/ucvlRoot"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/ucvl_surface"
|
||||
android:fillViewport="true">
|
||||
android:background="@color/ucvl_surface">
|
||||
|
||||
<LinearLayout
|
||||
<!-- The original desktop artwork stays separate from every native control. -->
|
||||
<ImageView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical">
|
||||
android:layout_height="match_parent"
|
||||
android:alpha="0.86"
|
||||
android:contentDescription="@null"
|
||||
android:importantForAccessibility="no"
|
||||
android:scaleType="centerCrop"
|
||||
android:src="@drawable/ucvl_landscape_header_v1" />
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@drawable/ucvl_scenic_mist"
|
||||
android:importantForAccessibility="no" />
|
||||
|
||||
<androidx.core.widget.NestedScrollView
|
||||
android:id="@+id/ucvlRoot"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:clipToPadding="true"
|
||||
android:fillViewport="true"
|
||||
android:overScrollMode="never">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/ucvl_navy"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="22dp"
|
||||
android:paddingTop="22dp"
|
||||
android:paddingEnd="22dp"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="18dp"
|
||||
android:paddingEnd="18dp"
|
||||
android:paddingBottom="22dp">
|
||||
|
||||
<ImageView
|
||||
android:layout_width="72dp"
|
||||
android:layout_height="72dp"
|
||||
android:contentDescription="@string/app_name"
|
||||
android:src="@drawable/zonghengjia_logo" />
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="26dp"
|
||||
android:paddingBottom="24dp">
|
||||
|
||||
<ImageView
|
||||
android:layout_width="60dp"
|
||||
android:layout_height="60dp"
|
||||
android:contentDescription="@string/app_name"
|
||||
android:src="@drawable/zonghengjia_logo" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="16dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="纵横家"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="28sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:text="智能安全网络 · Android"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="13sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:id="@+id/loginPanel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="16dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
android:background="@drawable/ucvl_glass_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="20dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="优创⁺纵横家"
|
||||
android:textColor="@android:color/white"
|
||||
android:textSize="24sp"
|
||||
android:text="登录纵横家"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="25sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:text="Powered by 优创未来 · Android"
|
||||
android:textColor="#B8DAF4"
|
||||
android:layout_marginTop="6dp"
|
||||
android:text="使用公司分配的用户名或邮箱登录"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/loginInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="28dp"
|
||||
android:minHeight="56dp"
|
||||
android:autofillHints="username"
|
||||
android:background="@drawable/ucvl_input"
|
||||
android:hint="用户名 / 邮箱"
|
||||
android:inputType="textEmailAddress"
|
||||
android:imeOptions="actionNext"
|
||||
android:singleLine="true"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textColorHint="@color/ucvl_muted" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/passwordInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
android:minHeight="56dp"
|
||||
android:autofillHints="password"
|
||||
android:background="@drawable/ucvl_input"
|
||||
android:hint="密码"
|
||||
android:imeOptions="actionDone"
|
||||
android:inputType="textPassword"
|
||||
android:singleLine="true"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textColorHint="@color/ucvl_muted" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/loginError"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:textColor="@color/ucvl_danger"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/loginButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
android:minHeight="54dp"
|
||||
android:text="安全登录"
|
||||
android:textColor="@android:color/white"
|
||||
android:textSize="16sp"
|
||||
app:backgroundTint="@color/ucvl_royal"
|
||||
app:cornerRadius="12dp" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/registerButton"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton"
|
||||
android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:minHeight="48dp"
|
||||
android:text="注册新用户 · 审核后使用"
|
||||
android:maxLines="2"
|
||||
android:singleLine="false"
|
||||
android:textColor="@color/ucvl_royal" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:gravity="center"
|
||||
android:text="账号停用后,设备授权与线路会自动失效"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/loginPanel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="24dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="登录优创⁺纵横家"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="25sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:text="使用公司分配的用户名或邮箱登录"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/loginInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="56dp"
|
||||
android:layout_marginTop="28dp"
|
||||
android:autofillHints="username"
|
||||
android:background="@drawable/ucvl_input"
|
||||
android:hint="用户名 / 邮箱"
|
||||
android:inputType="textEmailAddress"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textColorHint="@color/ucvl_muted" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/passwordInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="56dp"
|
||||
android:layout_marginTop="14dp"
|
||||
android:autofillHints="password"
|
||||
android:background="@drawable/ucvl_input"
|
||||
android:hint="密码"
|
||||
android:imeOptions="actionDone"
|
||||
android:inputType="textPassword"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textColorHint="@color/ucvl_muted" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/loginError"
|
||||
<LinearLayout
|
||||
android:id="@+id/dashboardPanel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:textColor="@color/ucvl_danger"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/loginButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="54dp"
|
||||
android:layout_marginTop="14dp"
|
||||
android:text="安全登录"
|
||||
android:textSize="16sp"
|
||||
app:backgroundTint="@color/ucvl_royal"
|
||||
app:cornerRadius="12dp" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/registerButton"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton"
|
||||
android:layout_width="match_parent" android:layout_height="48dp"
|
||||
android:text="注册新用户 · 审核后使用" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="24dp"
|
||||
android:gravity="center"
|
||||
android:text="账号停用后,设备授权与线路会自动失效"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/dashboardPanel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="18dp"
|
||||
android:visibility="gone">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/welcomeText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="23sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/accountText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<com.google.android.material.card.MaterialCardView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="18dp"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="18dp"
|
||||
app:strokeColor="@color/ucvl_border"
|
||||
app:strokeWidth="1dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:padding="20dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusDot"
|
||||
android:layout_width="36dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center"
|
||||
android:text="●"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="24sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="未连接"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="20sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusDetail"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="点击连接,由平台自动选择节点"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="13sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</com.google.android.material.card.MaterialCardView>
|
||||
|
||||
<com.google.android.material.card.MaterialCardView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="18dp"
|
||||
app:strokeColor="@color/ucvl_border"
|
||||
app:strokeWidth="1dp">
|
||||
android:orientation="vertical"
|
||||
android:visibility="gone">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/ucvl_glass_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="18dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:id="@+id/welcomeText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="当前工作节点"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="23sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/currentNode"
|
||||
android:id="@+id/accountText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:text="连接后显示实际工作节点"
|
||||
android:textColor="@color/ucvl_royal" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="代理模式"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<Spinner
|
||||
android:id="@+id/routeSpinner"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="52dp"
|
||||
android:layout_marginTop="6dp"
|
||||
android:background="@drawable/ucvl_input" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/connectButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="56dp"
|
||||
android:layout_marginTop="20dp"
|
||||
android:text="连接"
|
||||
android:textSize="17sp"
|
||||
app:backgroundTint="@color/ucvl_royal"
|
||||
app:cornerRadius="14dp" />
|
||||
</LinearLayout>
|
||||
</com.google.android.material.card.MaterialCardView>
|
||||
|
||||
<com.google.android.material.card.MaterialCardView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="18dp"
|
||||
app:strokeColor="@color/ucvl_border"
|
||||
app:strokeWidth="1dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="18dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="本期流量"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/usageText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:textColor="@color/ucvl_royal"
|
||||
android:textSize="17sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/usageProgress"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="10dp"
|
||||
android:layout_marginTop="10dp"
|
||||
android:max="100"
|
||||
android:progressTint="@color/ucvl_blue" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/planText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:layout_marginTop="4dp"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<TextView android:id="@+id/proxySpeed" android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:layout_marginTop="14dp"
|
||||
android:text="↑ 0 B/s ↓ 0 B/s" android:textColor="@color/ucvl_royal" />
|
||||
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/speedChart"
|
||||
android:layout_width="match_parent" android:layout_height="56dp"
|
||||
android:contentDescription="近期代理上传蓝线、下载青线速率,每三秒采样" />
|
||||
<TextView android:id="@+id/proxyTotal" android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:text="本次代理 0 B · 仅统计 proxy 出站"
|
||||
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
|
||||
<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp" android:text="近 7 天代理用量 · 蓝色上传 / 青色下载"
|
||||
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
|
||||
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/usageChart"
|
||||
android:layout_width="match_parent" android:layout_height="56dp"
|
||||
android:contentDescription="近七天代理上传和下载用量" />
|
||||
</LinearLayout>
|
||||
</com.google.android.material.card.MaterialCardView>
|
||||
|
||||
<com.google.android.material.card.MaterialCardView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="18dp"
|
||||
app:cardBackgroundColor="@color/ucvl_glass_white"
|
||||
app:cardCornerRadius="18dp"
|
||||
app:cardElevation="0dp"
|
||||
app:strokeColor="@color/ucvl_glass_border"
|
||||
app:strokeWidth="1dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:padding="20dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusDot"
|
||||
android:layout_width="36dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center"
|
||||
android:text="●"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="24sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="未连接"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="20sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/statusDetail"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="点击连接,由平台自动选择节点"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="13sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</com.google.android.material.card.MaterialCardView>
|
||||
|
||||
<com.google.android.material.card.MaterialCardView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
app:cardBackgroundColor="@color/ucvl_glass_white"
|
||||
app:cardCornerRadius="18dp"
|
||||
app:cardElevation="0dp"
|
||||
app:strokeColor="@color/ucvl_glass_border"
|
||||
app:strokeWidth="1dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="18dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="当前工作节点"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/currentNode"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:text="连接后显示实际工作节点"
|
||||
android:textColor="@color/ucvl_royal" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="代理模式"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<Spinner
|
||||
android:id="@+id/routeSpinner"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:minHeight="52dp"
|
||||
android:popupBackground="@android:color/white"
|
||||
android:background="@drawable/ucvl_input" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/connectButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="20dp"
|
||||
android:minHeight="56dp"
|
||||
android:text="连接"
|
||||
android:textColor="@android:color/white"
|
||||
android:textSize="17sp"
|
||||
app:backgroundTint="@color/ucvl_royal"
|
||||
app:cornerRadius="14dp" />
|
||||
</LinearLayout>
|
||||
</com.google.android.material.card.MaterialCardView>
|
||||
|
||||
<com.google.android.material.card.MaterialCardView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
app:cardBackgroundColor="@color/ucvl_glass_white"
|
||||
app:cardCornerRadius="18dp"
|
||||
app:cardElevation="0dp"
|
||||
app:strokeColor="@color/ucvl_glass_border"
|
||||
app:strokeWidth="1dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="18dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="本期流量"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/usageText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:textColor="@color/ucvl_royal"
|
||||
android:textSize="17sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/usageProgress"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="10dp"
|
||||
android:layout_marginTop="10dp"
|
||||
android:max="100"
|
||||
android:progressTint="@color/ucvl_blue" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/planText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<TextView android:id="@+id/proxySpeed" android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:layout_marginTop="14dp"
|
||||
android:text="↑ 0.0 KB/s ↓ 0.0 KB/s" android:textColor="@color/ucvl_royal" />
|
||||
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/speedChart"
|
||||
android:layout_width="match_parent" android:layout_height="56dp"
|
||||
android:contentDescription="近期代理上传蓝线、下载青线速率,每三秒采样" />
|
||||
<TextView android:id="@+id/proxyTotal" android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" android:text="本次代理 0 B · 仅统计 proxy 出站"
|
||||
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
|
||||
<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp" android:text="近 7 天代理用量 · 蓝色上传 / 青色下载"
|
||||
android:textColor="@color/ucvl_muted" android:textSize="12sp" />
|
||||
<com.v2ray.ang.ucvl.UcvlTrafficChart android:id="@+id/usageChart"
|
||||
android:layout_width="match_parent" android:layout_height="56dp"
|
||||
android:contentDescription="近七天代理上传和下载用量" />
|
||||
</LinearLayout>
|
||||
</com.google.android.material.card.MaterialCardView>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/refreshButton"
|
||||
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:minHeight="48dp"
|
||||
android:text="刷新"
|
||||
android:maxLines="2"
|
||||
android:singleLine="false"
|
||||
android:textColor="@color/ucvl_royal"
|
||||
app:backgroundTint="@color/ucvl_glass_white"
|
||||
app:strokeColor="@color/ucvl_border" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/logoutButton"
|
||||
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="10dp"
|
||||
android:layout_weight="1"
|
||||
android:minHeight="48dp"
|
||||
android:text="退出账号"
|
||||
android:maxLines="2"
|
||||
android:singleLine="false"
|
||||
android:textColor="@color/ucvl_royal"
|
||||
app:backgroundTint="@color/ucvl_glass_white"
|
||||
app:strokeColor="@color/ucvl_border" />
|
||||
</LinearLayout>
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/exitButton"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:minHeight="48dp"
|
||||
android:text="断开并退出应用"
|
||||
android:maxLines="2"
|
||||
android:singleLine="false"
|
||||
android:textColor="@color/ucvl_danger" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:gravity="center"
|
||||
android:text="公司策略 · 代理流量统计\nvpn.toplc.cn · © 2026 UCVL"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:orientation="horizontal">
|
||||
android:layout_marginTop="18dp"
|
||||
android:background="@drawable/ucvl_glass_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="8dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/updateStatus"
|
||||
android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:gravity="center" android:textSize="12sp" android:paddingHorizontal="20dp"
|
||||
android:textColor="@color/ucvl_muted" />
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/refreshButton"
|
||||
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="48dp"
|
||||
android:layout_weight="1"
|
||||
android:text="刷新" />
|
||||
|
||||
android:id="@+id/checkUpdatesButton"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton"
|
||||
android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:minHeight="48dp"
|
||||
android:text="检查软件更新"
|
||||
android:maxLines="2"
|
||||
android:singleLine="false"
|
||||
android:textColor="@color/ucvl_royal" />
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/logoutButton"
|
||||
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginStart="10dp"
|
||||
android:layout_weight="1"
|
||||
android:text="退出账号" />
|
||||
android:id="@+id/openSourceButton"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton"
|
||||
android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:minHeight="48dp"
|
||||
android:text="版本与开源许可"
|
||||
android:maxLines="2"
|
||||
android:singleLine="false"
|
||||
android:textColor="@color/ucvl_royal" />
|
||||
</LinearLayout>
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/exitButton"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginTop="4dp"
|
||||
android:text="断开并退出应用"
|
||||
android:textColor="@color/ucvl_danger" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:gravity="center"
|
||||
android:text="公司策略 · 代理流量统计\nvpn.toplc.cn · © 2026 UCVL"
|
||||
android:textColor="@color/ucvl_muted"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/openSourceButton"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton"
|
||||
android:layout_width="match_parent" android:layout_height="48dp"
|
||||
android:text="版本与开源许可" />
|
||||
</LinearLayout>
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
</FrameLayout>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:minHeight="48dp"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingTop="10dp"
|
||||
android:paddingEnd="8dp"
|
||||
android:paddingBottom="10dp"
|
||||
android:textColor="@color/ucvl_text"
|
||||
android:textSize="15sp" />
|
||||
@@ -5,8 +5,10 @@
|
||||
<color name="ucvl_royal">#1167D8</color>
|
||||
<color name="ucvl_surface">#F3F7FC</color>
|
||||
<color name="ucvl_text">#0B284D</color>
|
||||
<color name="ucvl_muted">#7186A1</color>
|
||||
<color name="ucvl_muted">#435F7B</color>
|
||||
<color name="ucvl_success">#15966A</color>
|
||||
<color name="ucvl_danger">#C63F45</color>
|
||||
<color name="ucvl_border">#D8E4F0</color>
|
||||
<color name="ucvl_glass_white">#80FFFFFF</color>
|
||||
<color name="ucvl_glass_border">#B3FFFFFF</color>
|
||||
</resources>
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class UcvlAuthorizationGuardTest {
|
||||
@Test fun revokedLoginStops() = runBlocking {
|
||||
var stopped = false
|
||||
UcvlAuthorizationGuard.watch("old", { "old" }, { throw UcvlApiException(401, "revoked") }, { stopped = true }, 1)
|
||||
UcvlAuthorizationGuard.watch("old", { "old" }, { throw UcvlApiException(401, "revoked") }, { stopped = true }, { fail("Unchanged session") }, 1)
|
||||
assertTrue(stopped)
|
||||
}
|
||||
@Test fun transientFailureDoesNotRevoke() = runBlocking {
|
||||
@@ -18,18 +20,93 @@ class UcvlAuthorizationGuardTest {
|
||||
if (calls == 1) throw java.io.IOException("offline")
|
||||
assertFalse(stopped)
|
||||
throw UcvlApiException(403, "revoked")
|
||||
}, { stopped = true }, 1)
|
||||
}, { stopped = true }, { fail("Unchanged session") }, 1)
|
||||
assertEquals(2, calls)
|
||||
assertTrue(stopped)
|
||||
}
|
||||
@Test fun staleResponseCannotClearNewLogin() = runBlocking {
|
||||
var token = "old"
|
||||
var stopped = false
|
||||
var oldTunnelStopped = false
|
||||
UcvlAuthorizationGuard.watch("old", { token }, {
|
||||
token = "new"
|
||||
throw UcvlApiException(401, "old response")
|
||||
}, { stopped = true }, 1)
|
||||
}, { stopped = true }, { oldTunnelStopped = true }, 1)
|
||||
assertFalse(stopped)
|
||||
assertTrue(oldTunnelStopped)
|
||||
assertEquals("new", token)
|
||||
}
|
||||
|
||||
@Test fun lateSuccessMustNotRevokeNewLogin() = runBlocking {
|
||||
var token = "old"
|
||||
var revoked = false
|
||||
var oldTunnelStopped = false
|
||||
withTimeout(1_000) {
|
||||
UcvlAuthorizationGuard.watch("old", { token }, {
|
||||
token = "new"
|
||||
}, { revoked = true }, { oldTunnelStopped = true }, 60_000)
|
||||
}
|
||||
assertFalse("An old successful request must not revoke a replacement login", revoked)
|
||||
assertTrue("Old tunnel must stop without waiting for the next poll", oldTunnelStopped)
|
||||
assertEquals("new", token)
|
||||
}
|
||||
|
||||
@Test fun replacementBeforeRequestStopsOnlyOldTunnel() = runBlocking {
|
||||
var changes = 0
|
||||
UcvlAuthorizationGuard.watch("old", { "new" }, { fail("Must not query old token") },
|
||||
{ fail("Must not revoke new login") }, { changes++ })
|
||||
assertEquals(1, changes)
|
||||
}
|
||||
|
||||
@Test fun removedLoginStopsOldTunnelWithoutFalseRevocation() = runBlocking {
|
||||
var changes = 0
|
||||
UcvlAuthorizationGuard.watch("old", { null }, { fail("Already logged out") },
|
||||
{ fail("No current login to revoke") }, { changes++ })
|
||||
assertEquals(1, changes)
|
||||
}
|
||||
|
||||
@Test fun lateTransientErrorStopsChangedSessionImmediately() = runBlocking {
|
||||
var token = "old"
|
||||
var changes = 0
|
||||
withTimeout(1_000) {
|
||||
UcvlAuthorizationGuard.watch("old", { token }, {
|
||||
token = "new"
|
||||
throw java.io.IOException("offline")
|
||||
}, { fail("Network errors must not revoke a new login") }, { changes++ }, 60_000)
|
||||
}
|
||||
assertEquals(1, changes)
|
||||
assertEquals("new", token)
|
||||
}
|
||||
|
||||
@Test fun cancelledRequestDoesNotRevokeOrStopAnotherSession() = runBlocking {
|
||||
var cancellationPropagated = false
|
||||
try {
|
||||
UcvlAuthorizationGuard.watch("old", { "old" }, { throw CancellationException("service stopped") },
|
||||
{ fail("Cancelled watcher must not revoke") }, { fail("Cancelled watcher must not stop") })
|
||||
} catch (_: CancellationException) { cancellationPropagated = true }
|
||||
assertTrue(cancellationPropagated)
|
||||
}
|
||||
|
||||
@Test fun sameLoginSuccessKeepsWatchingUntilActuallyRevoked() = runBlocking {
|
||||
var calls = 0
|
||||
var revocations = 0
|
||||
UcvlAuthorizationGuard.watch("old", { "old" }, {
|
||||
calls++
|
||||
if (calls == 2) throw UcvlApiException(403, "revoked")
|
||||
assertEquals(0, revocations)
|
||||
}, { revocations++ }, { fail("Same session") }, 1)
|
||||
assertEquals(2, calls)
|
||||
assertEquals(1, revocations)
|
||||
}
|
||||
|
||||
@Test fun lateForbiddenMustNotRevokeNewLogin() = runBlocking {
|
||||
var token = "old"
|
||||
var changes = 0
|
||||
UcvlAuthorizationGuard.watch("old", { token }, {
|
||||
token = "new"
|
||||
throw UcvlApiException(403, "old forbidden response")
|
||||
}, { fail("New login must survive") }, { changes++ }, 1)
|
||||
assertEquals(1, changes)
|
||||
assertEquals("new", token)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ class UcvlConfigBridgeTest {
|
||||
assertEquals(before, source.toString())
|
||||
assertEquals(source.getAsJsonArray("outbounds")[0], runtime.getAsJsonArray("outbounds")[0])
|
||||
assertEquals(source.getAsJsonObject("routing").getAsJsonArray("rules")[0],
|
||||
runtime.getAsJsonObject("routing").getAsJsonArray("rules")[2])
|
||||
runtime.getAsJsonObject("routing").getAsJsonArray("rules")[3])
|
||||
assertFalse(runtime.has("api"))
|
||||
assertTrue(runtime.getAsJsonArray("inbounds").all { it.asJsonObject.get("listen").asString == "127.0.0.1" })
|
||||
assertTrue(runtime.getAsJsonObject("policy").getAsJsonObject("system").get("statsOutboundUplink").asBoolean)
|
||||
@@ -41,6 +41,34 @@ class UcvlConfigBridgeTest {
|
||||
assertFalse(rules.any { it.asJsonObject.get("network")?.asString == "tcp,udp" })
|
||||
}
|
||||
|
||||
@Test fun forcesOnlyLoopbackHttpConnectivityChecksThroughTheProxy() {
|
||||
val source = fixture()
|
||||
val rules = UcvlConfigBridge.buildRuntime(source, "VPN002", 10808, 10809)
|
||||
.getAsJsonObject("routing").getAsJsonArray("rules")
|
||||
val probe = rules.firstOrNull { rule ->
|
||||
rule.asJsonObject.getAsJsonArray("inboundTag")?.map { it.asString } == listOf("http-in") &&
|
||||
rule.asJsonObject.has("domain")
|
||||
}?.asJsonObject ?: throw AssertionError("HTTPS startup checks can be routed directly")
|
||||
assertEquals("proxy", probe.get("outboundTag").asString)
|
||||
assertEquals(listOf("full:cp.cloudflare.com", "full:www.gstatic.com"),
|
||||
probe.getAsJsonArray("domain").map { it.asString }.sorted())
|
||||
assertTrue(rules.indexOf(probe) < rules.indexOf(source.getAsJsonObject("routing").getAsJsonArray("rules")[0]))
|
||||
}
|
||||
|
||||
@Test fun usesUnifiedNpmGatewayWithoutChangingPortOrRealitySni() {
|
||||
val runtime = UcvlConfigBridge.buildRuntime(
|
||||
fixture(), "VPN002", 10808, 10809, gatewayAddress = "59.110.91.17")
|
||||
val proxy = runtime.getAsJsonArray("outbounds")[0].asJsonObject
|
||||
val server = proxy.getAsJsonObject("settings").getAsJsonArray("vnext")[0].asJsonObject
|
||||
assertEquals("59.110.91.17", server.get("address").asString)
|
||||
assertEquals(11082, server.get("port").asInt)
|
||||
assertEquals("example.com", proxy.getAsJsonObject("streamSettings")
|
||||
.getAsJsonObject("realitySettings").get("serverName").asString)
|
||||
assertTrue(UcvlConfigBridge.isPublicIpv4("59.110.91.17"))
|
||||
assertFalse(UcvlConfigBridge.isPublicIpv4("100.73.44.33"))
|
||||
assertFalse(UcvlConfigBridge.isPublicIpv4("198.18.0.1"))
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun rejectsConflictingLocalPorts() {
|
||||
UcvlConfigBridge.buildRuntime(fixture(), "VPN002", 10808, 10808)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class UcvlReleaseCheckerTest {
|
||||
private fun fixture(version: String = "1.0.3", tag: String = "android-v$version", draft: Boolean = false,
|
||||
preview: Boolean = false, size: Long = 30000000, file: String = "UCVL-Zonghengjia-$version-android-universal.apk") =
|
||||
"""[{"tag_name":"$tag","draft":$draft,"prerelease":$preview,"assets":[
|
||||
{"name":"$file","size":$size,"browser_download_url":"https://example.invalid/unsafe.apk"}]}]"""
|
||||
|
||||
@Test fun usesOnlyCompanyGitCanonicalDownloadAndUniversalApk() {
|
||||
val offer = UcvlReleaseChecker.select(fixture(), "1.0.2")!!
|
||||
assertEquals("1.0.3", offer.version)
|
||||
assertEquals("https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/android-v1.0.3/UCVL-Zonghengjia-1.0.3-android-universal.apk", offer.url)
|
||||
assertEquals(30000000L, offer.size)
|
||||
}
|
||||
@Test fun skipsDraftAndPreviewAndOtherPlatforms() {
|
||||
assertNull(UcvlReleaseChecker.select(fixture(draft = true), "1.0.2"))
|
||||
assertNull(UcvlReleaseChecker.select(fixture(preview = true), "1.0.2"))
|
||||
assertNull(UcvlReleaseChecker.select(fixture(tag = "windows-v9.0.0"), "1.0.2"))
|
||||
}
|
||||
@Test fun comparesVersionsNumericallyWithoutDowngrades() {
|
||||
assertNull(UcvlReleaseChecker.select(fixture(), "1.0.3"))
|
||||
assertNull(UcvlReleaseChecker.select(fixture(), "1.0.4"))
|
||||
assertNotNull(UcvlReleaseChecker.select(fixture(version = "1.0.10"), "1.0.9"))
|
||||
assertNotNull(UcvlReleaseChecker.select(fixture(), "1.0.2+debug"))
|
||||
assertNull(UcvlReleaseChecker.select("[]", "1.0.2"))
|
||||
}
|
||||
@Test(expected = java.io.IOException::class) fun rejectsMissingUniversal() {
|
||||
UcvlReleaseChecker.select(fixture(file = "UCVL-Zonghengjia-1.0.3-android-arm64-v8a.apk"), "1.0.2")
|
||||
}
|
||||
@Test(expected = java.io.IOException::class) fun rejectsOversizedPackage() {
|
||||
UcvlReleaseChecker.select(fixture(size = 251L * 1024 * 1024), "1.0.2")
|
||||
}
|
||||
@Test(expected = java.io.IOException::class) fun rejectsEmptyPackage() {
|
||||
UcvlReleaseChecker.select(fixture(size = 0), "1.0.2")
|
||||
}
|
||||
@Test(expected = java.io.IOException::class) fun rejectsTraversalAttachment() {
|
||||
UcvlReleaseChecker.select(fixture(file = "../unsafe.apk"), "1.0.2")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
|
||||
class UcvlUpgradeReliabilityTest {
|
||||
private fun android(version: String) = """{"tag_name":"android-v$version","draft":false,"prerelease":false,"assets":[{"name":"UCVL-Zonghengjia-$version-android-universal.apk","size":66000000}]}"""
|
||||
private fun fullPage() = "[" + (1..50).joinToString(",") {
|
||||
"""{"tag_name":"windows-v0.3.$it","draft":false,"prerelease":false,"assets":[]}"""
|
||||
} + "]"
|
||||
|
||||
@Test fun findsAndroidAfterFullPageOfWindowsReleases() = runBlocking {
|
||||
val pages = mutableListOf<Int>()
|
||||
val offer = UcvlReleaseChecker.lookup("1.0.6") { page ->
|
||||
pages.add(page)
|
||||
if (page == 1) fullPage() else "[${android("1.0.7")}]"
|
||||
}
|
||||
assertEquals(listOf(1, 2), pages)
|
||||
assertEquals("1.0.7", offer?.version)
|
||||
}
|
||||
|
||||
@Test fun checksAllPagesBeforeChoosingNumericallyNewest() = runBlocking {
|
||||
val first = fullPage().dropLast(1) + ",${android("1.0.7")}]"
|
||||
val offer = UcvlReleaseChecker.lookup("1.0.6") { page ->
|
||||
if (page == 1) first else "[${android("1.0.10")}]"
|
||||
}
|
||||
assertEquals("1.0.10", offer?.version)
|
||||
}
|
||||
|
||||
@Test fun ignoresMalformedUnrelatedAndOverflowingVersionRecords() {
|
||||
val json = """[null,17,{}, {"tag_name":"windows-v9","draft":"broken"},
|
||||
{"tag_name":"android-v99999999999999.0.0","draft":false,"prerelease":false}, ${android("1.0.7")}]"""
|
||||
assertEquals("1.0.7", UcvlReleaseChecker.select(json, "1.0.6")?.version)
|
||||
}
|
||||
|
||||
@Test fun duplicateUniversalApksFailClosed() {
|
||||
val release = android("1.0.7").replace("\"size\":66000000}]", "\"size\":66000000},{\"name\":\"UCVL-Zonghengjia-1.0.7-android-universal.apk\",\"size\":66000000}]")
|
||||
assertThrows(IOException::class.java) { UcvlReleaseChecker.select("[$release]", "1.0.6") }
|
||||
}
|
||||
|
||||
@Test fun refusesUnboundedPagination() = runBlocking {
|
||||
var calls = 0
|
||||
try {
|
||||
UcvlReleaseChecker.lookup("1.0.6") { calls++; fullPage() }
|
||||
fail("Unbounded release list must fail with a retryable error")
|
||||
} catch (_: IOException) {
|
||||
assertEquals(10, calls)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun rejectsOversizedDecodedPageBeforeParsing() = runBlocking {
|
||||
try {
|
||||
UcvlReleaseChecker.lookup("1.0.6") { " ".repeat(1024 * 1024 + 1) }
|
||||
fail("Decoded page must remain bounded")
|
||||
} catch (_: IOException) { }
|
||||
}
|
||||
|
||||
@Test fun emptyPageEndsLookupWithoutDowngrade() = runBlocking {
|
||||
var calls = 0
|
||||
assertNull(UcvlReleaseChecker.lookup("1.0.7") { calls++; "[]" })
|
||||
assertEquals(1, calls)
|
||||
}
|
||||
|
||||
@Test fun speedUsesKilobytesMinimumWithoutOverstatingTinyTransfers() {
|
||||
assertEquals("0.0 KB/s", UcvlTrafficFormat.speed(0))
|
||||
assertEquals("0.0 KB/s", UcvlTrafficFormat.speed(-10))
|
||||
assertEquals("<0.1 KB/s", UcvlTrafficFormat.speed(1))
|
||||
assertEquals("0.1 KB/s", UcvlTrafficFormat.speed(103))
|
||||
assertEquals("1.0 KB/s", UcvlTrafficFormat.speed(1024))
|
||||
assertEquals("1.5 MB/s", UcvlTrafficFormat.speed(1572864))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.v2ray.ang.ucvl
|
||||
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class UcvlVpnStartupLeaseTest {
|
||||
@Test fun initialSessionCannotReportRunning() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
assertFalse(lease.isValid(0))
|
||||
assertFalse(lease.reportIfValid(0) { fail("No startup owns the service") })
|
||||
}
|
||||
|
||||
@Test fun beginCreatesValidSession() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
assertTrue(lease.isValid(lease.begin()))
|
||||
}
|
||||
|
||||
@Test fun replacementInvalidatesOlderStartup() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val old = lease.begin()
|
||||
val replacement = lease.begin()
|
||||
assertNotEquals(old, replacement)
|
||||
assertFalse(lease.isValid(old))
|
||||
assertTrue(lease.isValid(replacement))
|
||||
}
|
||||
|
||||
@Test fun revokeBeforeEstablishPreventsStartup() = revokeAt(Phase.BEFORE_ESTABLISH)
|
||||
@Test fun revokeDuringEstablishClosesInterfaceAndSkipsNative() = revokeAt(Phase.ESTABLISHED)
|
||||
@Test fun revokeDuringNativeStartStopsNativeWithoutSuccess() = revokeAt(Phase.NATIVE_STARTED)
|
||||
@Test fun revokeBeforeSuccessBroadcastPreventsGreenState() = revokeAt(Phase.BEFORE_REPORT)
|
||||
|
||||
@Test fun lateSuccessAfterStopCannotReportRunning() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val epoch = lease.begin()
|
||||
lease.invalidate()
|
||||
assertFalse(lease.reportIfValid(epoch) { fail("Stopped startup cannot revive") })
|
||||
}
|
||||
|
||||
@Test fun oldStartupCannotReportSuccessForReplacementSession() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val old = lease.begin()
|
||||
val replacement = lease.begin()
|
||||
assertFalse(lease.reportIfValid(old) { fail("Stale startup") })
|
||||
assertTrue(lease.reportIfValid(replacement) {})
|
||||
}
|
||||
|
||||
@Test fun registrationAfterRevokeCannotReportRunning() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val epoch = lease.begin()
|
||||
lease.invalidate()
|
||||
assertFalse(lease.reportIfValid(epoch) { fail("Native-running alone is insufficient") })
|
||||
}
|
||||
|
||||
@Test fun repeatedInvalidationCannotResurrectSession() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val epoch = lease.begin()
|
||||
repeat(3) { lease.invalidate() }
|
||||
assertFalse(lease.isValid(epoch))
|
||||
val next = lease.begin()
|
||||
assertNotEquals(epoch, next)
|
||||
assertTrue(lease.isValid(next))
|
||||
}
|
||||
|
||||
@Test fun binderCanInvalidateWhileNativeStartBlocksMain() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val epoch = lease.begin()
|
||||
val starting = CountDownLatch(1)
|
||||
val allowReturn = CountDownLatch(1)
|
||||
val finished = CountDownLatch(1)
|
||||
val success = AtomicBoolean(false)
|
||||
val main = Thread {
|
||||
starting.countDown()
|
||||
try {
|
||||
check(allowReturn.await(2, TimeUnit.SECONDS))
|
||||
success.set(lease.reportIfValid(epoch) {})
|
||||
} finally { finished.countDown() }
|
||||
}
|
||||
main.start()
|
||||
assertTrue(starting.await(2, TimeUnit.SECONDS))
|
||||
// No lock spans simulated establish/native code: Binder never waits for main.
|
||||
lease.invalidate()
|
||||
assertFalse(lease.isValid(epoch))
|
||||
allowReturn.countDown()
|
||||
assertTrue(finished.await(2, TimeUnit.SECONDS))
|
||||
assertFalse(success.get())
|
||||
main.join(2_000)
|
||||
}
|
||||
|
||||
@Test fun healthySessionReportsSuccessExactlyOnceWhenRequested() {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val epoch = lease.begin()
|
||||
var reports = 0
|
||||
assertTrue(lease.reportIfValid(epoch) { reports++ })
|
||||
assertEquals(1, reports)
|
||||
}
|
||||
|
||||
private enum class Phase { BEFORE_ESTABLISH, ESTABLISHED, NATIVE_STARTED, BEFORE_REPORT }
|
||||
|
||||
/** Fake Android/native boundaries exercise the same lease checks as the service. */
|
||||
private fun revokeAt(phase: Phase) {
|
||||
val lease = UcvlVpnStartupLease()
|
||||
val epoch = lease.begin()
|
||||
var interfaceOpen = false
|
||||
var nativeRunning = false
|
||||
var success = false
|
||||
fun boundary(at: Phase): Boolean {
|
||||
if (phase == at) lease.invalidate()
|
||||
return lease.isValid(epoch)
|
||||
}
|
||||
try {
|
||||
if (!boundary(Phase.BEFORE_ESTABLISH)) return
|
||||
interfaceOpen = true
|
||||
if (!boundary(Phase.ESTABLISHED)) return
|
||||
nativeRunning = true
|
||||
if (!boundary(Phase.NATIVE_STARTED)) return
|
||||
if (!boundary(Phase.BEFORE_REPORT)) return
|
||||
success = lease.reportIfValid(epoch) {}
|
||||
} finally {
|
||||
if (!lease.isValid(epoch)) {
|
||||
interfaceOpen = false
|
||||
nativeRunning = false
|
||||
}
|
||||
assertFalse("Revoked TUN must close", interfaceOpen)
|
||||
assertFalse("Late native start must stop", nativeRunning)
|
||||
assertFalse("Revoked startup cannot show connected", success)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# Android 1.0.3 本地候选验收
|
||||
|
||||
## 2026-09-17 源码追加:后台授权会话隔离
|
||||
|
||||
已在隔离单测复现并修复旧会话成功回包导致新登录误报授权失效,以及会话已替换时旧隧道停止不及时的问题。修复前定向4项中1失败;修复后定向10项、全量41项全部通过,0跳过。详见[会话隔离验收](AUTH-SESSION-ISOLATION-20260917.md)。**本次只编译源码并运行JVM测试,未重新打包/签名/安装/发布;下方1.0.3旧APK哈希不包含此次源码修复,不能混用验收证据。**
|
||||
|
||||
## 2026-09-08 至 09-09 原候选包记录
|
||||
|
||||
时间:2026-09-08,状态复核于 2026-09-09。未发布 1.0.3 安装包、未通知员工;对应 GPL 源码和验收记录已同步公司公共 Git 的 `codex/overnight-20260908` 维护分支,尚未合并正式分支。源码同步不代表真机 VPN 验收完成。
|
||||
|
||||
- 公司 Git 正式版检查:独立无凭据 HTTP 客户端,忽略草稿/试用版,只允许规范的公司 Git 下载链接;失败不停止 VPN。更新由用户确认后浏览器下载,尚不是应用内自动安装。
|
||||
- 34 项 JVM 单元测试通过,包括 7 项更新解析测试。Windows 中文工程路径导致 Gradle 测试加载失败,采用独立 ASCII 构建副本后全量通过,未忽略失败的测试。
|
||||
- 1.0.3 五种 APK 已按原公司证书签名,签名 v2/v3 检查通过;旧 1.0.2 与新包证书一致。
|
||||
- 专用 Android 模拟器 `ucvl_acceptance` 上:覆盖安装 1.0.2 → 1.0.3,保留合成会话、登录名与设备标识;随后清除合成会话,验证登录输入控件及空提交提示。证据 `upgrade-1.0.3.json`。没有对实体手机操作,没有登录生产账号,没有修改主机网络。
|
||||
- 初始测试截屏在绘制前呈白屏,不能作为视觉验收。随后实际重新启动应用并等待界面稳定,`login-rendered-1.0.3.png` 已复核:登录/注册/更新入口完整显示,无截断。手动检查更新实际访问公司 Git 并显示“暂无更新的 Android 正式版”(服务器目前只有试用版),记录 `update-ui-1.0.3.xml`。
|
||||
- 增强后的截图测试包 visual4 已重新编译、同证书安装并执行通过,`login-instrumentation-visual4.png` 保存实际登录及空提交错误提示。visual2/3 的截图断言曾失败;复核图像发现 visual3 已正常绘制,是采样落在白色标题字形导致误判,已改为检查右侧无文字的深浅背景对比并保留失败证据。这不改变 APK 本体。
|
||||
- 未完成:真实手机 VPN 授权、所有节点连接/切换、休眠/换网/长连接、Codex 认证业务、断线恢复和更新下载→系统安装流程。不能以模拟器安装测试替代。
|
||||
|
||||
Universal APK SHA256:`866d17bc303aa9cbc71b71c954ddd1f3ed50251326fc035a9e1d140ff230ee66`。
|
||||
@@ -0,0 +1,25 @@
|
||||
# Android 1.0.4 isolated candidate
|
||||
|
||||
Status: local signed candidate built and verified on 2026-09-24. Not published, not installed on a physical device, and not accepted as a stable release.
|
||||
|
||||
VersionName 1.0.4 / base versionCode 10004; the existing playstore ABI mapping produces APK versionCode 4010004 (previous candidate: 4010003). Includes the 2026-09-17 authorization-session isolation fix without changing the VPN or network policy.
|
||||
|
||||
The candidate was built in a fresh ASCII directory using cached JDK 21 / SDK 37 / Gradle 9.4.1 with `--offline --no-daemon --max-workers=2`. All 41 JVM tests passed with zero failures/errors/skips, including 10 authorization lifecycle cases for old success/401/403 responses, replaced or removed login, transient failure, and cancellation. All five ABI/universal release APKs were assembled. No emulator, Android service instrumentation or production API was used.
|
||||
|
||||
All five APK manifests independently report package `cn.toplc.zonghengjia`, versionName `1.0.4`, versionCode `4010004`. APK Signature Scheme v2/v3 verification passed. The certificate SHA256 is `0f1a09870d6ee1e73b62138f99463e7066f4228ce28b7f16ff0aeccca59ea14f`, independently compared with retained 1.0.2 and 1.0.3 universal APKs. Signing material was not exported. Old APKs remain unchanged.
|
||||
|
||||
| Artifact suffix | Bytes | SHA256 |
|
||||
| --- | ---: | --- |
|
||||
| android-universal.apk | 64228400 | `fc8ef82ba2ef28cb26991401c8ea5feca492f929a7bad4aa6b39e4787baaf416` |
|
||||
| android-arm64-v8a.apk | 27503013 | `7527441177d858b48975aa882d1313e7cb693653ced5c5de6d17fd3abce83a9f` |
|
||||
| android-armeabi-v7a.apk | 27855275 | `4121ea1f442cc3ec507ede50a19587bcaca983d147ec3af6ad27b7c62f229ca5` |
|
||||
| android-x86_64.apk | 28387740 | `f24a1f9b753030a4bd68278d685a03d0fdb7d8e0e34e96bd16e8fa6eba164125` |
|
||||
| android-x86.apk | 28842387 | `bd912c09f338f57f34806914fa45f86a8d7792a56bb24552ebf5a13888234b61` |
|
||||
|
||||
Every APK filename starts with `UCVL-Zonghengjia-1.0.4-`. The immutable build-input manifest SHA256 is `404c9c802321c39c2589c7d7c10e0e2d418af6e2d03d86f7de2ee8354f3bedeb`. The candidate report additionally binds signed APK ZIP-entry bytes to the unsigned Gradle outputs and the GPL snapshot to each compiled source input; seven AAR/JNI inputs are checked against the existing public restoration locks.
|
||||
|
||||
The first wrapper run stopped after successful Gradle completion because its PowerShell result aggregation used dictionaries with Measure-Object. The aggregation was corrected, and signing resumed against the same verified input manifest and completed outputs; tests/build were not falsely reported failed or silently rerun against different source.
|
||||
|
||||
Remaining device gates: real Android VPN permission and data path, service/broadcast behavior when a login replaces an in-flight authorization request, disconnect/recovery, Wi-Fi/mobile transitions, sleep/wake and authenticated sustained business traffic. JVM tests and APK signatures do not establish these results.
|
||||
|
||||
GPL source is exported separately using the publication tool that excludes the private Zero3 helper. No phone, board, host network, iOS or remote Git operation is part of this candidate preparation.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Android 1.0.7 verification scope — 2026-11-07
|
||||
|
||||
This release uses package `cn.toplc.zonghengjia`, base version code `10007`, and APK version code `4010007` for all four ABIs and the universal APK.
|
||||
|
||||
Changes: bounded pagination when checking the shared company release repository; unrelated malformed records do not hide Android updates; a new-version prompt after the foreground activity becomes ready; and proxy speed displayed in KB/s or larger units. Download links remain canonical company universal APK links. Download confirmation opens a browser; Android's own installation confirmation remains required. No VPN shutdown is performed by the release checker.
|
||||
|
||||
The malformed-record regression was reproduced against the retained 1.0.6 checker: the existing `select` method threw `IllegalStateException: Not a JSON Object: null`. The new regression suite exercises this case, releases beyond a full first page, numeric newest-version selection across pages, duplicate package rejection, pagination and decoded-size bounds, empty lists, and minimum-unit speed formatting.
|
||||
|
||||
The release build runs the complete offline JVM suite, preserving the authorization and startup-lease regressions. Test totals are taken from the new build's JUnit XML and bound to its input manifest. Each signed APK is checked for package/version, v2/v3 signatures, the original company signing certificate, and unchanged compiled ZIP entries. The matching GPL source archive is bound to every compiled source input and the seven locked restorable binary dependencies.
|
||||
|
||||
The original company certificate fingerprint is `0f1a09870d6ee1e73b62138f99463e7066f4228ce28b7f16ff0aeccca59ea14f`. Retained 1.0.0, 1.0.2, 1.0.3 and 1.0.6 universal packages use this same certificate, supporting an in-place signed upgrade without uninstalling or deleting app data.
|
||||
|
||||
No physical phone, TV, ADB session, emulator, mobile VPN, Nightowl service, router, or host network was modified for this release. Physical-device VPN behavior, the actual automatic dialog and cover-installation interaction, Service/broadcast races, network transitions, sleep/wake, and sustained authenticated traffic were not tested with this APK. Offline checks do not imply those checks passed.
|
||||
|
||||
Old 1.0.0 installations may need the first upgrade downloaded from the release page because they predate the later release checker. Newer installations can use the company update button. The package does not perform silent installation and does not claim Windows/Tailscale feature parity.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Android 后台授权检查:旧会话与新登录隔离
|
||||
|
||||
状态:本地源码候选修复,未发布APK,未在手机安装。版本号仍为1.0.3;此前1.0.3已签名候选包不包含本次修复,不可将其旧哈希作为本次修复后的二进制证据。
|
||||
|
||||
## 复现与原因
|
||||
|
||||
原UcvlAuthorizationGuard在检查开始时发现保存的令牌不等于该VPN的令牌,会调用与401/403相同的revoke回调。该回调虽然不清除较新的令牌,却无条件发送AUTHORIZATION_REVOKED广播,使新登录界面被退回登录页。成功或暂时性失败的旧请求还要等下一轮60秒检查才停止旧隧道;旧401/403回包遇到新令牌时则直接返回,没有调用停止旧隧道回调。
|
||||
|
||||
隔离复现:新增lateSuccessMustNotRevokeNewLogin,在授权请求中模拟令牌由old变为new。原代码执行4项测试,3通过、该项真实失败;证据android-auth-before-20260917.json/.log。全部为合成令牌和回调,不是生产网络或真实用户账号复现。
|
||||
|
||||
## 修复
|
||||
|
||||
- 将sessionChanged(只停止旧VPN)与revoke(当前令牌确实被401/403拒绝)分离。
|
||||
- 请求前、成功/临时失败后立即核对会话,发生变化不等待下一次60秒轮询。
|
||||
- 旧401/403响应属于已替换会话时停止旧隧道,但不撤销新令牌。
|
||||
- CoreVpnService只有确认仍属于同一令牌时才清除令牌并发出撤销广播;替换/退出会话仅停止旧服务。
|
||||
- 协程取消继续向上传播,不把取消视为账号撤销;保持临时断网不撤销同一会话的策略。
|
||||
|
||||
这不是新增自动换节点功能,也不声称修复了Activity所有网络请求或所有换网问题。
|
||||
|
||||
## 验证
|
||||
|
||||
独立ASCII临时副本:`C:/Users/Administrator/AppData/Local/Temp/ucvl-auth-20260917-907433b0081d432aa9a6d763f8bb061b`。使用已有JDK21、Android SDK37、Gradle9.4.1缓存,全程--offline、--no-daemon;没有启动模拟器或读取签名私钥。
|
||||
|
||||
1. 原代码定向回归:4项,1项失败(预期暴露缺陷)。
|
||||
2. 修复后定向回归:10项全部通过,0跳过。覆盖同会话撤销、临时离线、旧401/403、旧成功响应、预先替换/退出、取消、持续检查;成功和临时失败的会话变更需在1秒上限内退出,不等60秒。
|
||||
3. 全量`:app:testPlaystoreReleaseUnitTest`:**41项全部通过,0失败、0错误、0跳过**。包括授权10、桥接5、版本解析7和其余19项;修复后的主应用Kotlin及测试Kotlin编译通过。
|
||||
4. 没有运行assemble、签名、APK安装、VPN授权、换网或真实服务广播/UI仪器测试。不等于Android实机、Codex长连接或全平台验收。
|
||||
|
||||
定向复测证据android-auth-after-20260917.json/.log,全量证据android-auth-full-20260917.json/.log。复现工具`tools/Test-SessionGuard-Isolated.ps1`,首次不要删除原源码/旧安装,测试仅复制到专用临时目录;不会连接公司生产API。
|
||||
|
||||
本次源文件SHA256:
|
||||
|
||||
| 文件 | SHA256 |
|
||||
| --- | --- |
|
||||
| UcvlAuthorizationGuard.kt | 5C7B01D602EB0F5B45BBE88D7F12E3BC70FED4296AE5B6578C2F25A918FD87C4 |
|
||||
| CoreVpnService.kt | 4F55A79F7179D26AF622998C9A70A0D2C64BC1C60B56DDC9E10BA06EE921D850 |
|
||||
| UcvlAuthorizationGuardTest.kt | ACB7BD96F1D1766D59B4D42DC12295621EDEE98E9DCCF78FE566B83770ADF919 |
|
||||
|
||||
下一步:在专用Android设备/模拟器做真实service生命周期、重新登录后旧响应/撤销广播、断网恢复验证,再在实体手机补VPN及长连接验收,之后方可决定发布。当前旧候选APK、公司Git公开版本、Windows现用安装、生产后台/节点均未修改,没有员工通知。
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"phase": "after",
|
||||
"started_at": "2026-09-17T10:51:11.1475501+08:00",
|
||||
"runtime": "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ucvl-auth-20260917-907433b0081d432aa9a6d763f8bb061b",
|
||||
"offline": true,
|
||||
"exit_code": 0,
|
||||
"suites": [
|
||||
{
|
||||
"name": "com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest",
|
||||
"tests": 10,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
}
|
||||
],
|
||||
"source_copied": true,
|
||||
"emulator_started": false,
|
||||
"device_installed": false,
|
||||
"apk_published": false,
|
||||
"network_modified": false
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"phase": "before",
|
||||
"started_at": "2026-09-17T08:59:15.9076805+08:00",
|
||||
"runtime": "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ucvl-auth-20260917-907433b0081d432aa9a6d763f8bb061b",
|
||||
"offline": true,
|
||||
"exit_code": 1,
|
||||
"suites": [
|
||||
{
|
||||
"name": "com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest",
|
||||
"tests": 4,
|
||||
"failures": 1,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
}
|
||||
],
|
||||
"source_copied": true,
|
||||
"emulator_started": false,
|
||||
"device_installed": false,
|
||||
"apk_published": false,
|
||||
"network_modified": false
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"phase": "full",
|
||||
"started_at": "2026-09-17T12:10:25.1756796+08:00",
|
||||
"runtime": "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ucvl-auth-20260917-907433b0081d432aa9a6d763f8bb061b",
|
||||
"offline": true,
|
||||
"exit_code": 0,
|
||||
"suites": [
|
||||
{
|
||||
"name": "com.v2ray.ang.fmt.ShadowsocksFmtTest",
|
||||
"tests": 15,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
{
|
||||
"name": "com.v2ray.ang.HttpUtilTest",
|
||||
"tests": 1,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
{
|
||||
"name": "com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest",
|
||||
"tests": 10,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
{
|
||||
"name": "com.v2ray.ang.ucvl.UcvlConfigBridgeTest",
|
||||
"tests": 5,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
{
|
||||
"name": "com.v2ray.ang.ucvl.UcvlReleaseCheckerTest",
|
||||
"tests": 7,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
{
|
||||
"name": "com.v2ray.ang.UtilsTest",
|
||||
"tests": 3,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
}
|
||||
],
|
||||
"source_copied": true,
|
||||
"emulator_started": false,
|
||||
"device_installed": false,
|
||||
"apk_published": false,
|
||||
"network_modified": false
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 168 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 169 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 170 KiB |
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"url": "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/android-v1.0.1-candidate.1/UCVL-Zonghengjia-1.0.1-android-universal.apk",
|
||||
"release": "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/tag/android-v1.0.1-candidate.1",
|
||||
"source_zip": "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android/archive/android-v1.0.1-candidate.1.zip",
|
||||
"version": "1.0.1",
|
||||
"size": 64220208,
|
||||
"sha256": "87747619f838f432c94c90785e6523bf5a9e82bb3a138b47ba3c9e293e172d45",
|
||||
"anonymous_download_verified": true,
|
||||
"prerelease": true,
|
||||
"physical_android_device_tested": false,
|
||||
"stable_update_changed": false,
|
||||
"employee_notification_sent": false,
|
||||
"windows_and_macos_source_private": true
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"repository": "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android",
|
||||
"source_zip": "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android/archive/android-v1.0.1-candidate.1.zip",
|
||||
"commit": "0a8bdc9fff9cc865d0619fc67d94bca5de5ac83a",
|
||||
"tag": "android-v1.0.1-candidate.1",
|
||||
"anonymous_download_verified": true,
|
||||
"source_files": 971,
|
||||
"bytes": 2450691,
|
||||
"sha256": "eb22a45f8d2e2cf77edf7f8fa6e058ea04383260c40d8e336bffed2dc97cd16b",
|
||||
"other_source_repositories": {
|
||||
"ucvl-zonghengjia": "not anonymously readable",
|
||||
"ucvl-zonghengjia-macos": "not anonymously readable"
|
||||
},
|
||||
"binary_release_created": false
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"timestamp": "2026-09-03T11:00:29.868500+08:00",
|
||||
"host_network_changed": false,
|
||||
"separate_uid_no_explicit_proxy": true,
|
||||
"physical_android_device_tested": false,
|
||||
"results": [],
|
||||
"pass": false,
|
||||
"baseline": {
|
||||
"transport_vpn": false,
|
||||
"uid": 10150,
|
||||
"explicit_proxy": false,
|
||||
"results": [
|
||||
{
|
||||
"target": "www.google.com",
|
||||
"pass": false,
|
||||
"error_type": "ConnectException"
|
||||
},
|
||||
{
|
||||
"target": "api.openai.com",
|
||||
"pass": false,
|
||||
"error_type": "ConnectException"
|
||||
},
|
||||
{
|
||||
"target": "chatgpt.com",
|
||||
"pass": false,
|
||||
"error_type": "ConnectException"
|
||||
},
|
||||
{
|
||||
"target": "vpn.toplc.cn",
|
||||
"status": 200,
|
||||
"pass": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"error": "Connect test exited early: ngOs.open(ForwardingOs.java:563)\n\tat libcore.io.BlockGuardOs.open(BlockGuardOs.java:274)\n\tat libcore.io.ForwardingOs.open(ForwardingOs.java:563)\n\tat android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8591)\n\tat libcore.io.IoBridge.open(IoBridge.java:560)\n\t... 37 more\n\nINSTRUMENTATION_STATUS: stream=\nError in connectFromDashboard(com.v2ray.ang.ucvl.VpnLifecycleTest):\njava.io.FileNotFoundException: /data/user/0/cn.toplc.zonghengjia/files/vpn-acceptance-fixture.json: open failed: EACCES (Permission denied)\n\tat libcore.io.IoBridge.open(IoBridge.java:574)\n\tat java.io.FileInputStream.<init>(FileInputStream.java:179)\n\tat kotlin.io.FilesKt__FileReadWriteKt.readText(FileReadWrite.kt:135)\n\tat kotlin.io.FilesKt__FileReadWriteKt.readText$default(FileReadWrite.kt:135)\n\tat com.v2ray.ang.ucvl.VpnLifecycleTest.connectFromDashboard(VpnLifecycleTest.kt:22)\n\t... 32 trimmed\nCaused by: android.system.ErrnoException: open failed: EACCES (Permission denied)\n\tat libcore.io.Linux.open(Native Method)\n\tat libcore.io.ForwardingOs.open(ForwardingOs.java:563)\n\tat libcore.io.BlockGuardOs.open(BlockGuardOs.java:274)\n\tat libcore.io.ForwardingOs.open(ForwardingOs.java:563)\n\tat android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8591)\n\tat libcore.io.IoBridge.open(IoBridge.java:560)\n\t... 37 more\n\nINSTRUMENTATION_STATUS: test=connectFromDashboard\nINSTRUMENTATION_STATUS_CODE: -2\nINSTRUMENTATION_RESULT: stream=\n\nTime: 0.011\nThere was 1 failure:\n1) connectFromDashboard(com.v2ray.ang.ucvl.VpnLifecycleTest)\njava.io.FileNotFoundException: /data/user/0/cn.toplc.zonghengjia/files/vpn-acceptance-fixture.json: open failed: EACCES (Permission denied)\n\tat libcore.io.IoBridge.open(IoBridge.java:574)\n\tat java.io.FileInputStream.<init>(FileInputStream.java:179)\n\tat kotlin.io.FilesKt__FileReadWriteKt.readText(FileReadWrite.kt:135)\n\tat kotlin.io.FilesKt__FileReadWriteKt.readText$default(FileReadWrite.kt:135)\n\tat com.v2ray.ang.ucvl.VpnLifecycleTest.connectFromDashboard(VpnLifecycleTest.kt:22)\n\t... 32 trimmed\nCaused by: android.system.ErrnoException: open failed: EACCES (Permission denied)\n\tat libcore.io.Linux.open(Native Method)\n\tat libcore.io.ForwardingOs.open(ForwardingOs.java:563)\n\tat libcore.io.BlockGuardOs.open(BlockGuardOs.java:274)\n\tat libcore.io.ForwardingOs.open(ForwardingOs.java:563)\n\tat android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8591)\n\tat libcore.io.IoBridge.open(IoBridge.java:560)\n\t... 37 more\n\nFAILURES!!!\nTests run: 1, Failures: 1\n\n\nINSTRUMENTATION_CODE: -1\n"
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"timestamp": "2026-09-08T22:13:37.462276+08:00",
|
||||
"serial": "emulator-5554",
|
||||
"old_version": "1.0.2",
|
||||
"new_version": "1.0.3",
|
||||
"passed": true,
|
||||
"physical_device_tested": false,
|
||||
"host_network_modified": false,
|
||||
"authenticated_vpn_connection_tested": false,
|
||||
"steps": [
|
||||
"seed_synthetic_session_on_1.0.2",
|
||||
"cover_upgrade_preserves_encrypted_session_login_and_device_id",
|
||||
"login_visible_empty_submission_safe_fixture_cleared"
|
||||
],
|
||||
"apk_sha256": "866d17bc303aa9cbc71b71c954ddd1f3ed50251326fc035a9e1d140ff230ee66"
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"BuildInputManifestSha256": "b018aec0675debe39dca37f105a325039d018f6b0b84ecb56c962529f6e5ce0d",
|
||||
"FullProductionAcceptance": false,
|
||||
"OriginalSourceFiles": 1010,
|
||||
"PhysicalDeviceTested": false,
|
||||
"PrivateHelperExcluded": true,
|
||||
"ReleaseMetadata": {
|
||||
"FrozenCandidateFlagsPreserved": true,
|
||||
"FullProductionAcceptance": false,
|
||||
"LimitedUiAndBasicVpnAcceptance": false,
|
||||
"OfflineValidationOnly": true,
|
||||
"PhysicalDeviceTested": false,
|
||||
"SourceLicense": "GPL-3.0",
|
||||
"UpdateBehavior": "New-version prompt opens browser APK download; Android controls installation. No silent installation.",
|
||||
"download_url": "https://pro.ucvl.cn/admin/ucvl-software-downloads/releases/download/android-v1.0.7/UCVL-Zonghengjia-1.0.7-android-universal.apk",
|
||||
"mandatory": false,
|
||||
"packages": {
|
||||
"UCVL-Zonghengjia-1.0.7-android-arm64-v8a.apk": {
|
||||
"sha256": "904f08376817de724a30dc453d9c8be7a8c44dd5210f532913ae06435bc71a21",
|
||||
"size": 29837957
|
||||
},
|
||||
"UCVL-Zonghengjia-1.0.7-android-armeabi-v7a.apk": {
|
||||
"sha256": "6e76f211c45efa4ca83bf8eb66b21ce73b5c6508e211583ff082b704ee907515",
|
||||
"size": 30190219
|
||||
},
|
||||
"UCVL-Zonghengjia-1.0.7-android-universal.apk": {
|
||||
"sha256": "0ca806fd5cab0bb517724be6584c78a1bb2259d6db425fd2c50f33bbc8ac5a8b",
|
||||
"size": 66563344
|
||||
},
|
||||
"UCVL-Zonghengjia-1.0.7-android-x86.apk": {
|
||||
"sha256": "495463f27190af4cbca71dffd92539d68f49bf647b897b6adef5b0c52bfe9299",
|
||||
"size": 31177331
|
||||
},
|
||||
"UCVL-Zonghengjia-1.0.7-android-x86_64.apk": {
|
||||
"sha256": "356416c6dc98e3e66091d97f310f05c7b5f305fe24d45746e98d5de252be54f5",
|
||||
"size": 30722684
|
||||
},
|
||||
"UCVL-Zonghengjia-1.0.7-source.zip": {
|
||||
"sha256": "d6bc9b5d5e6928c434485fea445cef3950e627e34d2cc12eb0c9cfc445b1c93d",
|
||||
"size": 12453339
|
||||
}
|
||||
},
|
||||
"platform": "android",
|
||||
"sha256": "0ca806fd5cab0bb517724be6584c78a1bb2259d6db425fd2c50f33bbc8ac5a8b",
|
||||
"size": 66563344,
|
||||
"validation": {
|
||||
"authorization_lifecycle_jvm_tests": 10,
|
||||
"compiled_public_inputs": 394,
|
||||
"locked_restorable_binary_inputs": 7,
|
||||
"offline_unit_tests": 62,
|
||||
"physical_device_tested": false,
|
||||
"physical_receipt_sha256": null,
|
||||
"source_files": 1010,
|
||||
"unverified": [
|
||||
"Phone installation and APK upgrade",
|
||||
"System VPN permission and data path",
|
||||
"Service/broadcast lifecycle",
|
||||
"Wi-Fi/mobile and sleep/wake recovery",
|
||||
"Sustained business session"
|
||||
]
|
||||
},
|
||||
"version": "1.0.7",
|
||||
"version_code": 4010007
|
||||
},
|
||||
"SourceArchiveSha256": "d6bc9b5d5e6928c434485fea445cef3950e627e34d2cc12eb0c9cfc445b1c93d",
|
||||
"SourceInventorySha256": "9e2235fa58e75a6e51cadcfce33f8130b4f875851a883a638fbcad09bc07dddb",
|
||||
"Status": "released-with-offline-validation-only",
|
||||
"Tag": "android-v1.0.7",
|
||||
"Version": "1.0.7"
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
# Local candidate only. Uses cached dependencies; never starts adb or an emulator.
|
||||
param([string]$JobDirectory = '',[switch]$ResumeAfterBuild)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
$tempRoot = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath())
|
||||
if ($ResumeAfterBuild -and -not $JobDirectory) { throw 'Resume requires the exact completed build directory' }
|
||||
if (-not $JobDirectory) { $JobDirectory = Join-Path $tempRoot ('ucvl-android-104-' + [guid]::NewGuid().ToString('N')) }
|
||||
$job = [IO.Path]::GetFullPath($JobDirectory)
|
||||
if ([IO.Path]::GetDirectoryName($job) -ine $tempRoot -or [IO.Path]::GetFileName($job) -cnotmatch '^ucvl-android-104-[a-f0-9]{32}$' -or $job -match '[^\x00-\x7F]') {
|
||||
throw 'A fresh scoped ASCII temporary directory is required'
|
||||
}
|
||||
if ((Test-Path -LiteralPath $job) -and -not $ResumeAfterBuild) { throw 'Candidate directory already exists' }
|
||||
foreach ($name in @('universal','arm64-v8a','armeabi-v7a','x86','x86_64')) {
|
||||
if (Test-Path -LiteralPath (Join-Path $repo "releases/UCVL-Zonghengjia-1.0.4-android-$name.apk")) { throw 'Signed 1.0.4 candidate already exists; do not replace it' }
|
||||
}
|
||||
$buildText = Get-Content -LiteralPath (Join-Path $repo 'V2rayNG/app/build.gradle.kts') -Raw
|
||||
if ($buildText -notmatch 'versionCode = 10004' -or $buildText -notmatch 'versionName = "1.0.4"') { throw 'Source version mismatch' }
|
||||
$project = Join-Path $job 'project'
|
||||
$source = Join-Path $repo 'V2rayNG'
|
||||
function Save-Json([string]$Name,$Value) {
|
||||
[IO.File]::WriteAllText((Join-Path $job "evidence/$Name"),($Value | ConvertTo-Json -Depth 12),[Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
$env:JAVA_HOME = Join-Path $repo '.tools/jdk-staging/jdk-21.0.12.1+1'
|
||||
$env:ANDROID_HOME = Join-Path $repo '.tools/android-sdk'
|
||||
if (-not $ResumeAfterBuild) {
|
||||
$null = New-Item -ItemType Directory -Path $job,$project,(Join-Path $job 'evidence'),(Join-Path $job 'artifacts')
|
||||
foreach ($name in @('gradlew','gradlew.bat','gradle.properties','settings.gradle.kts','build.gradle.kts','gradle')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source $name) -Destination $project -Recurse
|
||||
}
|
||||
$null = New-Item -ItemType Directory -Path (Join-Path $project 'app')
|
||||
foreach ($name in @('src','libs','build.gradle.kts','proguard-rules.pro')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source "app/$name") -Destination (Join-Path $project 'app') -Recurse
|
||||
}
|
||||
$inputs = @(Get-ChildItem -LiteralPath $project -File -Recurse | Sort-Object FullName | ForEach-Object {
|
||||
[ordered]@{Path=[IO.Path]::GetRelativePath($project,$_.FullName).Replace('\','/');Bytes=$_.Length;Sha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash}
|
||||
})
|
||||
Save-Json 'build-inputs.json' $inputs
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
$started = [DateTimeOffset]::Now
|
||||
Push-Location $project
|
||||
try {
|
||||
& ./gradlew.bat --offline --no-daemon --max-workers=2 :app:testPlaystoreReleaseUnitTest :app:assemblePlaystoreRelease *> (Join-Path $job 'evidence/gradle.log')
|
||||
$buildExit = $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
$suites = @(Get-ChildItem -LiteralPath (Join-Path $project 'app/build/test-results/testPlaystoreReleaseUnitTest') -Filter 'TEST-*.xml' -File -ErrorAction SilentlyContinue | ForEach-Object {
|
||||
[xml]$xml = Get-Content -LiteralPath $_.FullName -Raw
|
||||
[pscustomobject]@{Name=$xml.testsuite.name;Tests=[int]$xml.testsuite.tests;Failures=[int]$xml.testsuite.failures;Errors=[int]$xml.testsuite.errors;Skipped=[int]$xml.testsuite.skipped}
|
||||
})
|
||||
$tests = [ordered]@{StartedAt=$started.ToString('O');ExitCode=$buildExit;Offline=$true;Suites=$suites;BuildInputsSha256=$inputsHash;PhysicalDeviceTested=$false;EmulatorStarted=$false;Published=$false}
|
||||
Save-Json 'tests.json' $tests
|
||||
} else {
|
||||
$tests = Get-Content -LiteralPath (Join-Path $job 'evidence/tests.json') -Raw | ConvertFrom-Json
|
||||
$suites = $tests.Suites
|
||||
$buildExit = $tests.ExitCode
|
||||
$inputs = Get-Content -LiteralPath (Join-Path $job 'evidence/build-inputs.json') -Raw | ConvertFrom-Json
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
if ($inputsHash -ne $tests.BuildInputsSha256) { throw 'Completed build input manifest changed' }
|
||||
}
|
||||
if ($buildExit -ne 0) { throw "Gradle failed ($buildExit); evidence retained at $job" }
|
||||
if (($suites | Measure-Object Tests -Sum).Sum -ne 41 -or ($suites | Measure-Object Failures -Sum).Sum -ne 0 -or ($suites | Measure-Object Errors -Sum).Sum -ne 0 -or ($suites | Measure-Object Skipped -Sum).Sum -ne 0) {
|
||||
throw 'Unexpected unit test coverage or failures'
|
||||
}
|
||||
foreach ($row in $inputs) {
|
||||
if ((Get-FileHash -LiteralPath (Join-Path $project $row.Path)).Hash -ne $row.Sha256 -or (Get-FileHash -LiteralPath (Join-Path $source $row.Path)).Hash -ne $row.Sha256) {
|
||||
throw "Input changed during build: $($row.Path)"
|
||||
}
|
||||
}
|
||||
& (Join-Path $repo 'Sign-Candidate.ps1') -Version '1.0.4' -InputDirectory (Join-Path $project 'app/build/outputs/apk/playstore/release') *> (Join-Path $job 'evidence/signing.log')
|
||||
$java = Join-Path $env:JAVA_HOME 'bin/java.exe'
|
||||
$signer = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/lib/apksigner.jar'
|
||||
$aapt = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/aapt.exe'
|
||||
$expectedCertificate = '0f1a09870d6ee1e73b62138f99463e7066f4228ce28b7f16ff0aeccca59ea14f'
|
||||
foreach ($version in @('1.0.2','1.0.3')) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs (Join-Path $repo "releases/UCVL-Zonghengjia-$version-android-universal.apk") 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate) { throw "Old $version signing identity differs" }
|
||||
}
|
||||
$packages = @(foreach ($file in Get-ChildItem -LiteralPath (Join-Path $repo 'releases') -Filter 'UCVL-Zonghengjia-1.0.4-android-*.apk' -File | Sort-Object Name) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs $file.FullName 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate -or $verification -notmatch 'v2\): true' -or $verification -notmatch 'v3\): true') { throw "Candidate signature mismatch: $($file.Name)" }
|
||||
$copy = Join-Path $job "artifacts/$($file.Name)"
|
||||
Copy-Item -LiteralPath $file.FullName -Destination $copy
|
||||
$badging = (& $aapt dump badging $copy 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $badging -notmatch "package: name='cn.toplc.zonghengjia' versionCode='4010004' versionName='1.0.4'") { throw "Candidate manifest mismatch: $($file.Name)" }
|
||||
[ordered]@{Name=$file.Name;Bytes=$file.Length;Sha256=(Get-FileHash -LiteralPath $copy).Hash;Version='1.0.4';VersionCode=4010004;SignerSha256=$expectedCertificate;V2=$true;V3=$true}
|
||||
})
|
||||
if ($packages.Count -ne 5) { throw 'Expected all five ABI/universal packages' }
|
||||
Save-Json 'candidate.json' ([ordered]@{Version='1.0.4';VersionCode=4010004;BaseVersionCode=10004;JobDirectory=$job;BuiltAt=[DateTimeOffset]::Now.ToString('O');Packages=$packages;BuildInputsSha256=$inputsHash;UnitTests=41;AuthorizationLifecycleJvmTests=10;SameSignerAs=@('1.0.2','1.0.3');PhysicalDeviceTested=$false;AndroidServiceBroadcastTested=$false;StableReleaseAccepted=$false;Published=$false})
|
||||
Write-Output "CANDIDATE_JOB=$job"
|
||||
Write-Output 'CANDIDATE_BUILD_SIGN_VERIFY_PASSED'
|
||||
@@ -0,0 +1,92 @@
|
||||
# Local candidate only. Uses cached dependencies; never starts adb or an emulator.
|
||||
param([string]$JobDirectory = '',[switch]$ResumeAfterBuild)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
$tempRoot = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath())
|
||||
if ($ResumeAfterBuild -and -not $JobDirectory) { throw 'Resume requires the exact completed build directory' }
|
||||
if (-not $JobDirectory) { $JobDirectory = Join-Path $tempRoot ('ucvl-android-105-' + [guid]::NewGuid().ToString('N')) }
|
||||
$job = [IO.Path]::GetFullPath($JobDirectory)
|
||||
if ([IO.Path]::GetDirectoryName($job) -ine $tempRoot -or [IO.Path]::GetFileName($job) -cnotmatch '^ucvl-android-105-[a-f0-9]{32}$' -or $job -match '[^\x00-\x7F]') {
|
||||
throw 'A fresh scoped ASCII temporary directory is required'
|
||||
}
|
||||
if ((Test-Path -LiteralPath $job) -and -not $ResumeAfterBuild) { throw 'Candidate directory already exists' }
|
||||
foreach ($name in @('universal','arm64-v8a','armeabi-v7a','x86','x86_64')) {
|
||||
if (Test-Path -LiteralPath (Join-Path $repo "releases/UCVL-Zonghengjia-1.0.5-android-$name.apk")) { throw 'Signed 1.0.5 candidate already exists; do not replace it' }
|
||||
}
|
||||
$buildText = Get-Content -LiteralPath (Join-Path $repo 'V2rayNG/app/build.gradle.kts') -Raw
|
||||
if ($buildText -notmatch 'versionCode = 10005' -or $buildText -notmatch 'versionName = "1.0.5"') { throw 'Source version mismatch' }
|
||||
$project = Join-Path $job 'project'
|
||||
$source = Join-Path $repo 'V2rayNG'
|
||||
function Save-Json([string]$Name,$Value) {
|
||||
[IO.File]::WriteAllText((Join-Path $job "evidence/$Name"),($Value | ConvertTo-Json -Depth 12),[Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
$env:JAVA_HOME = Join-Path $repo '.tools/jdk-staging/jdk-21.0.12.1+1'
|
||||
$env:ANDROID_HOME = Join-Path $repo '.tools/android-sdk'
|
||||
if (-not $ResumeAfterBuild) {
|
||||
$null = New-Item -ItemType Directory -Path $job,$project,(Join-Path $job 'evidence'),(Join-Path $job 'artifacts')
|
||||
foreach ($name in @('gradlew','gradlew.bat','gradle.properties','settings.gradle.kts','build.gradle.kts','gradle')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source $name) -Destination $project -Recurse
|
||||
}
|
||||
$null = New-Item -ItemType Directory -Path (Join-Path $project 'app')
|
||||
foreach ($name in @('src','libs','build.gradle.kts','proguard-rules.pro')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source "app/$name") -Destination (Join-Path $project 'app') -Recurse
|
||||
}
|
||||
$inputs = @(Get-ChildItem -LiteralPath $project -File -Recurse | Sort-Object FullName | ForEach-Object {
|
||||
[ordered]@{Path=[IO.Path]::GetRelativePath($project,$_.FullName).Replace('\','/');Bytes=$_.Length;Sha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash}
|
||||
})
|
||||
Save-Json 'build-inputs.json' $inputs
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
$started = [DateTimeOffset]::Now
|
||||
Push-Location $project
|
||||
try {
|
||||
& ./gradlew.bat --offline --no-daemon --max-workers=2 :app:testPlaystoreReleaseUnitTest :app:assemblePlaystoreRelease *> (Join-Path $job 'evidence/gradle.log')
|
||||
$buildExit = $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
$suites = @(Get-ChildItem -LiteralPath (Join-Path $project 'app/build/test-results/testPlaystoreReleaseUnitTest') -Filter 'TEST-*.xml' -File -ErrorAction SilentlyContinue | ForEach-Object {
|
||||
[xml]$xml = Get-Content -LiteralPath $_.FullName -Raw
|
||||
[pscustomobject]@{Name=$xml.testsuite.name;Tests=[int]$xml.testsuite.tests;Failures=[int]$xml.testsuite.failures;Errors=[int]$xml.testsuite.errors;Skipped=[int]$xml.testsuite.skipped}
|
||||
})
|
||||
$tests = [ordered]@{StartedAt=$started.ToString('O');ExitCode=$buildExit;Offline=$true;Suites=$suites;BuildInputsSha256=$inputsHash;PhysicalDeviceTested=$false;EmulatorStarted=$false;Published=$false}
|
||||
Save-Json 'tests.json' $tests
|
||||
} else {
|
||||
$tests = Get-Content -LiteralPath (Join-Path $job 'evidence/tests.json') -Raw | ConvertFrom-Json
|
||||
$suites = $tests.Suites
|
||||
$buildExit = $tests.ExitCode
|
||||
$inputs = Get-Content -LiteralPath (Join-Path $job 'evidence/build-inputs.json') -Raw | ConvertFrom-Json
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
if ($inputsHash -ne $tests.BuildInputsSha256) { throw 'Completed build input manifest changed' }
|
||||
}
|
||||
if ($buildExit -ne 0) { throw "Gradle failed ($buildExit); evidence retained at $job" }
|
||||
if (($suites | Measure-Object Tests -Sum).Sum -ne 41 -or ($suites | Measure-Object Failures -Sum).Sum -ne 0 -or ($suites | Measure-Object Errors -Sum).Sum -ne 0 -or ($suites | Measure-Object Skipped -Sum).Sum -ne 0) {
|
||||
throw 'Unexpected unit test coverage or failures'
|
||||
}
|
||||
foreach ($row in $inputs) {
|
||||
if ((Get-FileHash -LiteralPath (Join-Path $project $row.Path)).Hash -ne $row.Sha256 -or (Get-FileHash -LiteralPath (Join-Path $source $row.Path)).Hash -ne $row.Sha256) {
|
||||
throw "Input changed during build: $($row.Path)"
|
||||
}
|
||||
}
|
||||
& (Join-Path $repo 'Sign-Candidate.ps1') -Version '1.0.5' -InputDirectory (Join-Path $project 'app/build/outputs/apk/playstore/release') *> (Join-Path $job 'evidence/signing.log')
|
||||
$java = Join-Path $env:JAVA_HOME 'bin/java.exe'
|
||||
$signer = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/lib/apksigner.jar'
|
||||
$aapt = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/aapt.exe'
|
||||
$expectedCertificate = '0f1a09870d6ee1e73b62138f99463e7066f4228ce28b7f16ff0aeccca59ea14f'
|
||||
foreach ($version in @('1.0.2','1.0.3')) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs (Join-Path $repo "releases/UCVL-Zonghengjia-$version-android-universal.apk") 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate) { throw "Old $version signing identity differs" }
|
||||
}
|
||||
$packages = @(foreach ($file in Get-ChildItem -LiteralPath (Join-Path $repo 'releases') -Filter 'UCVL-Zonghengjia-1.0.5-android-*.apk' -File | Sort-Object Name) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs $file.FullName 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate -or $verification -notmatch 'v2\): true' -or $verification -notmatch 'v3\): true') { throw "Candidate signature mismatch: $($file.Name)" }
|
||||
$copy = Join-Path $job "artifacts/$($file.Name)"
|
||||
Copy-Item -LiteralPath $file.FullName -Destination $copy
|
||||
$badging = (& $aapt dump badging $copy 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $badging -notmatch "package: name='cn.toplc.zonghengjia' versionCode='4010005' versionName='1.0.5'") { throw "Candidate manifest mismatch: $($file.Name)" }
|
||||
[ordered]@{Name=$file.Name;Bytes=$file.Length;Sha256=(Get-FileHash -LiteralPath $copy).Hash;Version='1.0.5';VersionCode=4010005;SignerSha256=$expectedCertificate;V2=$true;V3=$true}
|
||||
})
|
||||
if ($packages.Count -ne 5) { throw 'Expected all five ABI/universal packages' }
|
||||
Save-Json 'candidate.json' ([ordered]@{Version='1.0.5';VersionCode=4010005;BaseVersionCode=10005;JobDirectory=$job;BuiltAt=[DateTimeOffset]::Now.ToString('O');Packages=$packages;BuildInputsSha256=$inputsHash;UnitTests=41;AuthorizationLifecycleJvmTests=10;SameSignerAs=@('1.0.2','1.0.3');PhysicalDeviceTested=$false;AndroidServiceBroadcastTested=$false;StableReleaseAccepted=$false;Published=$false})
|
||||
Write-Output "CANDIDATE_JOB=$job"
|
||||
Write-Output 'CANDIDATE_BUILD_SIGN_VERIFY_PASSED'
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# Local candidate only. Uses cached dependencies; never starts adb or an emulator.
|
||||
param([string]$JobDirectory = '',[switch]$ResumeAfterBuild)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
$tempRoot = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath())
|
||||
if ($ResumeAfterBuild -and -not $JobDirectory) { throw 'Resume requires the exact completed build directory' }
|
||||
if (-not $JobDirectory) { $JobDirectory = Join-Path $tempRoot ('ucvl-android-106-' + [guid]::NewGuid().ToString('N')) }
|
||||
$job = [IO.Path]::GetFullPath($JobDirectory)
|
||||
if ([IO.Path]::GetDirectoryName($job) -ine $tempRoot -or [IO.Path]::GetFileName($job) -cnotmatch '^ucvl-android-106-[a-f0-9]{32}$' -or $job -match '[^\x00-\x7F]') {
|
||||
throw 'A fresh scoped ASCII temporary directory is required'
|
||||
}
|
||||
if ((Test-Path -LiteralPath $job) -and -not $ResumeAfterBuild) { throw 'Candidate directory already exists' }
|
||||
foreach ($name in @('universal','arm64-v8a','armeabi-v7a','x86','x86_64')) {
|
||||
if (Test-Path -LiteralPath (Join-Path $repo "releases/UCVL-Zonghengjia-1.0.6-android-$name.apk")) { throw 'Signed 1.0.6 candidate already exists; do not replace it' }
|
||||
}
|
||||
$buildText = Get-Content -LiteralPath (Join-Path $repo 'V2rayNG/app/build.gradle.kts') -Raw
|
||||
if ($buildText -notmatch 'versionCode = 10006' -or $buildText -notmatch 'versionName = "1.0.6"') { throw 'Source version mismatch' }
|
||||
$project = Join-Path $job 'project'
|
||||
$source = Join-Path $repo 'V2rayNG'
|
||||
function Save-Json([string]$Name,$Value) {
|
||||
[IO.File]::WriteAllText((Join-Path $job "evidence/$Name"),($Value | ConvertTo-Json -Depth 12),[Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
function Read-UnitTestSuites {
|
||||
@(Get-ChildItem -LiteralPath (Join-Path $project 'app/build/test-results/testPlaystoreReleaseUnitTest') -Filter 'TEST-*.xml' -File -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object {
|
||||
[xml]$xml = Get-Content -LiteralPath $_.FullName -Raw
|
||||
[pscustomobject]@{
|
||||
Name=[string]$xml.testsuite.name
|
||||
Tests=[int]$xml.testsuite.tests
|
||||
Failures=[int]$xml.testsuite.failures
|
||||
Errors=[int]$xml.testsuite.errors
|
||||
Skipped=[int]$xml.testsuite.skipped
|
||||
TestCases=@($xml.testsuite.testcase).Count
|
||||
ReportName=$_.Name
|
||||
ReportSha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash
|
||||
}
|
||||
})
|
||||
}
|
||||
$env:JAVA_HOME = Join-Path $repo '.tools/jdk-staging/jdk-21.0.12.1+1'
|
||||
$env:ANDROID_HOME = Join-Path $repo '.tools/android-sdk'
|
||||
if (-not $ResumeAfterBuild) {
|
||||
$null = New-Item -ItemType Directory -Path $job,$project,(Join-Path $job 'evidence'),(Join-Path $job 'artifacts')
|
||||
foreach ($name in @('gradlew','gradlew.bat','gradle.properties','settings.gradle.kts','build.gradle.kts','gradle')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source $name) -Destination $project -Recurse
|
||||
}
|
||||
$null = New-Item -ItemType Directory -Path (Join-Path $project 'app')
|
||||
foreach ($name in @('src','libs','build.gradle.kts','proguard-rules.pro')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source "app/$name") -Destination (Join-Path $project 'app') -Recurse
|
||||
}
|
||||
$inputs = @(Get-ChildItem -LiteralPath $project -File -Recurse | Sort-Object FullName | ForEach-Object {
|
||||
[ordered]@{Path=[IO.Path]::GetRelativePath($project,$_.FullName).Replace('\','/');Bytes=$_.Length;Sha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash}
|
||||
})
|
||||
Save-Json 'build-inputs.json' $inputs
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
$started = [DateTimeOffset]::Now
|
||||
Push-Location $project
|
||||
try {
|
||||
& ./gradlew.bat --offline --no-daemon --max-workers=2 :app:testPlaystoreReleaseUnitTest :app:assemblePlaystoreRelease *> (Join-Path $job 'evidence/gradle.log')
|
||||
$buildExit = $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
$suites = @(Read-UnitTestSuites)
|
||||
$tests = [ordered]@{StartedAt=$started.ToString('O');ExitCode=$buildExit;Offline=$true;Suites=$suites;BuildInputsSha256=$inputsHash;PhysicalDeviceTested=$false;EmulatorStarted=$false;Published=$false}
|
||||
Save-Json 'tests.json' $tests
|
||||
} else {
|
||||
$tests = Get-Content -LiteralPath (Join-Path $job 'evidence/tests.json') -Raw | ConvertFrom-Json
|
||||
$suites = @(Read-UnitTestSuites)
|
||||
if (($tests.Suites | ConvertTo-Json -Depth 5 -Compress) -cne ($suites | ConvertTo-Json -Depth 5 -Compress)) { throw 'Completed JUnit XML evidence changed' }
|
||||
$buildExit = $tests.ExitCode
|
||||
$inputs = Get-Content -LiteralPath (Join-Path $job 'evidence/build-inputs.json') -Raw | ConvertFrom-Json
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
if ($inputsHash -ne $tests.BuildInputsSha256) { throw 'Completed build input manifest changed' }
|
||||
}
|
||||
if ($buildExit -ne 0) { throw "Gradle failed ($buildExit); evidence retained at $job" }
|
||||
$totalUnitTests = [int]($suites | Measure-Object Tests -Sum).Sum
|
||||
$authorizationSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest' })
|
||||
$startupLeaseSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlVpnStartupLeaseTest' })
|
||||
if ($totalUnitTests -lt 41 -or ($suites | Measure-Object Failures -Sum).Sum -ne 0 -or ($suites | Measure-Object Errors -Sum).Sum -ne 0 -or ($suites | Measure-Object Skipped -Sum).Sum -ne 0) {
|
||||
throw 'Unexpected unit test coverage or failures'
|
||||
}
|
||||
if ($authorizationSuites.Count -ne 1 -or $authorizationSuites[0].Tests -ne 10 -or $startupLeaseSuites.Count -ne 1 -or $startupLeaseSuites[0].Tests -lt 8) {
|
||||
throw 'Required authorization or VPN startup lease regressions missing'
|
||||
}
|
||||
foreach ($suite in $suites) {
|
||||
if (-not $suite.Name -or $suite.Tests -lt 1 -or $suite.Tests -ne $suite.TestCases) { throw 'JUnit suite count differs from actual test cases' }
|
||||
}
|
||||
$authorizationUnitTests = [int]$authorizationSuites[0].Tests
|
||||
$startupLeaseUnitTests = [int]$startupLeaseSuites[0].Tests
|
||||
foreach ($row in $inputs) {
|
||||
if ((Get-FileHash -LiteralPath (Join-Path $project $row.Path)).Hash -ne $row.Sha256 -or (Get-FileHash -LiteralPath (Join-Path $source $row.Path)).Hash -ne $row.Sha256) {
|
||||
throw "Input changed during build: $($row.Path)"
|
||||
}
|
||||
}
|
||||
& (Join-Path $repo 'Sign-Candidate.ps1') -Version '1.0.6' -InputDirectory (Join-Path $project 'app/build/outputs/apk/playstore/release') *> (Join-Path $job 'evidence/signing.log')
|
||||
$java = Join-Path $env:JAVA_HOME 'bin/java.exe'
|
||||
$signer = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/lib/apksigner.jar'
|
||||
$aapt = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/aapt.exe'
|
||||
$expectedCertificate = '0f1a09870d6ee1e73b62138f99463e7066f4228ce28b7f16ff0aeccca59ea14f'
|
||||
foreach ($version in @('1.0.2','1.0.3')) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs (Join-Path $repo "releases/UCVL-Zonghengjia-$version-android-universal.apk") 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate) { throw "Old $version signing identity differs" }
|
||||
}
|
||||
$packages = @(foreach ($file in Get-ChildItem -LiteralPath (Join-Path $repo 'releases') -Filter 'UCVL-Zonghengjia-1.0.6-android-*.apk' -File | Sort-Object Name) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs $file.FullName 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate -or $verification -notmatch 'v2\): true' -or $verification -notmatch 'v3\): true') { throw "Candidate signature mismatch: $($file.Name)" }
|
||||
$copy = Join-Path $job "artifacts/$($file.Name)"
|
||||
Copy-Item -LiteralPath $file.FullName -Destination $copy
|
||||
$badging = (& $aapt dump badging $copy 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $badging -notmatch "package: name='cn.toplc.zonghengjia' versionCode='4010006' versionName='1.0.6'") { throw "Candidate manifest mismatch: $($file.Name)" }
|
||||
[ordered]@{Name=$file.Name;Bytes=$file.Length;Sha256=(Get-FileHash -LiteralPath $copy).Hash;Version='1.0.6';VersionCode=4010006;SignerSha256=$expectedCertificate;V2=$true;V3=$true}
|
||||
})
|
||||
if ($packages.Count -ne 5) { throw 'Expected all five ABI/universal packages' }
|
||||
Save-Json 'candidate.json' ([ordered]@{Version='1.0.6';VersionCode=4010006;BaseVersionCode=10006;JobDirectory=$job;BuiltAt=[DateTimeOffset]::Now.ToString('O');Packages=$packages;BuildInputsSha256=$inputsHash;UnitTests=$totalUnitTests;AuthorizationLifecycleJvmTests=$authorizationUnitTests;StartupLeaseJvmTests=$startupLeaseUnitTests;SameSignerAs=@('1.0.2','1.0.3');PhysicalDeviceTested=$false;AndroidServiceBroadcastTested=$false;StableReleaseAccepted=$false;Published=$false})
|
||||
Write-Output "CANDIDATE_JOB=$job"
|
||||
Write-Output 'CANDIDATE_BUILD_SIGN_VERIFY_PASSED'
|
||||
@@ -0,0 +1,116 @@
|
||||
# Local candidate only. Uses cached dependencies; never starts adb or an emulator.
|
||||
param([string]$JobDirectory = '',[switch]$ResumeAfterBuild)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
||||
$tempRoot = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath())
|
||||
if ($ResumeAfterBuild -and -not $JobDirectory) { throw 'Resume requires the exact completed build directory' }
|
||||
if (-not $JobDirectory) { $JobDirectory = Join-Path $tempRoot ('ucvl-android-107-' + [guid]::NewGuid().ToString('N')) }
|
||||
$job = [IO.Path]::GetFullPath($JobDirectory)
|
||||
if ([IO.Path]::GetDirectoryName($job) -ine $tempRoot -or [IO.Path]::GetFileName($job) -cnotmatch '^ucvl-android-107-[a-f0-9]{32}$' -or $job -match '[^\x00-\x7F]') {
|
||||
throw 'A fresh scoped ASCII temporary directory is required'
|
||||
}
|
||||
if ((Test-Path -LiteralPath $job) -and -not $ResumeAfterBuild) { throw 'Candidate directory already exists' }
|
||||
foreach ($name in @('universal','arm64-v8a','armeabi-v7a','x86','x86_64')) {
|
||||
if (Test-Path -LiteralPath (Join-Path $repo "releases/UCVL-Zonghengjia-1.0.7-android-$name.apk")) { throw 'Signed 1.0.7 candidate already exists; do not replace it' }
|
||||
}
|
||||
$buildText = Get-Content -LiteralPath (Join-Path $repo 'V2rayNG/app/build.gradle.kts') -Raw
|
||||
if ($buildText -notmatch 'versionCode = 10007' -or $buildText -notmatch 'versionName = "1.0.7"') { throw 'Source version mismatch' }
|
||||
$project = Join-Path $job 'project'
|
||||
$source = Join-Path $repo 'V2rayNG'
|
||||
function Save-Json([string]$Name,$Value) {
|
||||
[IO.File]::WriteAllText((Join-Path $job "evidence/$Name"),($Value | ConvertTo-Json -Depth 12),[Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
function Read-UnitTestSuites {
|
||||
@(Get-ChildItem -LiteralPath (Join-Path $project 'app/build/test-results/testPlaystoreReleaseUnitTest') -Filter 'TEST-*.xml' -File -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object {
|
||||
[xml]$xml = Get-Content -LiteralPath $_.FullName -Raw
|
||||
[pscustomobject]@{
|
||||
Name=[string]$xml.testsuite.name
|
||||
Tests=[int]$xml.testsuite.tests
|
||||
Failures=[int]$xml.testsuite.failures
|
||||
Errors=[int]$xml.testsuite.errors
|
||||
Skipped=[int]$xml.testsuite.skipped
|
||||
TestCases=@($xml.testsuite.testcase).Count
|
||||
ReportName=$_.Name
|
||||
ReportSha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash
|
||||
}
|
||||
})
|
||||
}
|
||||
$env:JAVA_HOME = Join-Path $repo '.tools/jdk-staging/jdk-21.0.12.1+1'
|
||||
$env:ANDROID_HOME = Join-Path $repo '.tools/android-sdk'
|
||||
if (-not $ResumeAfterBuild) {
|
||||
$null = New-Item -ItemType Directory -Path $job,$project,(Join-Path $job 'evidence'),(Join-Path $job 'artifacts')
|
||||
foreach ($name in @('gradlew','gradlew.bat','gradle.properties','settings.gradle.kts','build.gradle.kts','gradle')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source $name) -Destination $project -Recurse
|
||||
}
|
||||
$null = New-Item -ItemType Directory -Path (Join-Path $project 'app')
|
||||
foreach ($name in @('src','libs','build.gradle.kts','proguard-rules.pro')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source "app/$name") -Destination (Join-Path $project 'app') -Recurse
|
||||
}
|
||||
$inputs = @(Get-ChildItem -LiteralPath $project -File -Recurse | Sort-Object FullName | ForEach-Object {
|
||||
[ordered]@{Path=[IO.Path]::GetRelativePath($project,$_.FullName).Replace('\','/');Bytes=$_.Length;Sha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash}
|
||||
})
|
||||
Save-Json 'build-inputs.json' $inputs
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
$started = [DateTimeOffset]::Now
|
||||
Push-Location $project
|
||||
try {
|
||||
& ./gradlew.bat --offline --no-daemon --max-workers=2 :app:testPlaystoreReleaseUnitTest :app:assemblePlaystoreRelease *> (Join-Path $job 'evidence/gradle.log')
|
||||
$buildExit = $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
$suites = @(Read-UnitTestSuites)
|
||||
$tests = [ordered]@{StartedAt=$started.ToString('O');ExitCode=$buildExit;Offline=$true;Suites=$suites;BuildInputsSha256=$inputsHash;PhysicalDeviceTested=$false;EmulatorStarted=$false;Published=$false}
|
||||
Save-Json 'tests.json' $tests
|
||||
} else {
|
||||
$tests = Get-Content -LiteralPath (Join-Path $job 'evidence/tests.json') -Raw | ConvertFrom-Json
|
||||
$suites = @(Read-UnitTestSuites)
|
||||
if (($tests.Suites | ConvertTo-Json -Depth 5 -Compress) -cne ($suites | ConvertTo-Json -Depth 5 -Compress)) { throw 'Completed JUnit XML evidence changed' }
|
||||
$buildExit = $tests.ExitCode
|
||||
$inputs = Get-Content -LiteralPath (Join-Path $job 'evidence/build-inputs.json') -Raw | ConvertFrom-Json
|
||||
$inputsHash = (Get-FileHash -LiteralPath (Join-Path $job 'evidence/build-inputs.json')).Hash
|
||||
if ($inputsHash -ne $tests.BuildInputsSha256) { throw 'Completed build input manifest changed' }
|
||||
}
|
||||
if ($buildExit -ne 0) { throw "Gradle failed ($buildExit); evidence retained at $job" }
|
||||
$totalUnitTests = [int]($suites | Measure-Object Tests -Sum).Sum
|
||||
$authorizationSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest' })
|
||||
$startupLeaseSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlVpnStartupLeaseTest' })
|
||||
$upgradeSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlUpgradeReliabilityTest' })
|
||||
if ($totalUnitTests -lt 41 -or ($suites | Measure-Object Failures -Sum).Sum -ne 0 -or ($suites | Measure-Object Errors -Sum).Sum -ne 0 -or ($suites | Measure-Object Skipped -Sum).Sum -ne 0) {
|
||||
throw 'Unexpected unit test coverage or failures'
|
||||
}
|
||||
if ($authorizationSuites.Count -ne 1 -or $authorizationSuites[0].Tests -ne 10 -or $startupLeaseSuites.Count -ne 1 -or $startupLeaseSuites[0].Tests -lt 8) {
|
||||
throw 'Required authorization or VPN startup lease regressions missing'
|
||||
}
|
||||
if ($upgradeSuites.Count -ne 1 -or $upgradeSuites[0].Tests -ne 8) { throw 'Required Android 1.0.7 upgrade regressions missing' }
|
||||
foreach ($suite in $suites) {
|
||||
if (-not $suite.Name -or $suite.Tests -lt 1 -or $suite.Tests -ne $suite.TestCases) { throw 'JUnit suite count differs from actual test cases' }
|
||||
}
|
||||
$authorizationUnitTests = [int]$authorizationSuites[0].Tests
|
||||
$startupLeaseUnitTests = [int]$startupLeaseSuites[0].Tests
|
||||
foreach ($row in $inputs) {
|
||||
if ((Get-FileHash -LiteralPath (Join-Path $project $row.Path)).Hash -ne $row.Sha256 -or (Get-FileHash -LiteralPath (Join-Path $source $row.Path)).Hash -ne $row.Sha256) {
|
||||
throw "Input changed during build: $($row.Path)"
|
||||
}
|
||||
}
|
||||
& (Join-Path $repo 'Sign-Candidate.ps1') -Version '1.0.7' -InputDirectory (Join-Path $project 'app/build/outputs/apk/playstore/release') *> (Join-Path $job 'evidence/signing.log')
|
||||
$java = Join-Path $env:JAVA_HOME 'bin/java.exe'
|
||||
$signer = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/lib/apksigner.jar'
|
||||
$aapt = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/aapt.exe'
|
||||
$expectedCertificate = '0f1a09870d6ee1e73b62138f99463e7066f4228ce28b7f16ff0aeccca59ea14f'
|
||||
foreach ($version in @('1.0.2','1.0.3')) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs (Join-Path $repo "releases/UCVL-Zonghengjia-$version-android-universal.apk") 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate) { throw "Old $version signing identity differs" }
|
||||
}
|
||||
$packages = @(foreach ($file in Get-ChildItem -LiteralPath (Join-Path $repo 'releases') -Filter 'UCVL-Zonghengjia-1.0.7-android-*.apk' -File | Sort-Object Name) {
|
||||
$verification = (& $java -jar $signer verify --verbose --print-certs $file.FullName 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $verification -notmatch $expectedCertificate -or $verification -notmatch 'v2\): true' -or $verification -notmatch 'v3\): true') { throw "Candidate signature mismatch: $($file.Name)" }
|
||||
$copy = Join-Path $job "artifacts/$($file.Name)"
|
||||
Copy-Item -LiteralPath $file.FullName -Destination $copy
|
||||
$badging = (& $aapt dump badging $copy 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $badging -notmatch "package: name='cn.toplc.zonghengjia' versionCode='4010007' versionName='1.0.7'") { throw "Candidate manifest mismatch: $($file.Name)" }
|
||||
[ordered]@{Name=$file.Name;Bytes=$file.Length;Sha256=(Get-FileHash -LiteralPath $copy).Hash;Version='1.0.7';VersionCode=4010007;SignerSha256=$expectedCertificate;V2=$true;V3=$true}
|
||||
})
|
||||
if ($packages.Count -ne 5) { throw 'Expected all five ABI/universal packages' }
|
||||
Save-Json 'candidate.json' ([ordered]@{Version='1.0.7';VersionCode=4010007;BaseVersionCode=10007;JobDirectory=$job;BuiltAt=[DateTimeOffset]::Now.ToString('O');Packages=$packages;BuildInputsSha256=$inputsHash;UnitTests=$totalUnitTests;AuthorizationLifecycleJvmTests=$authorizationUnitTests;StartupLeaseJvmTests=$startupLeaseUnitTests;SameSignerAs=@('1.0.2','1.0.3');PhysicalDeviceTested=$false;AndroidServiceBroadcastTested=$false;StableReleaseAccepted=$false;Published=$false})
|
||||
Write-Output "CANDIDATE_JOB=$job"
|
||||
Write-Output 'CANDIDATE_BUILD_SIGN_VERIFY_PASSED'
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Bind isolated APKs to their exact build inputs and reviewed GPL source. No network or devices."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import zipfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
VERSION = '1.0.4'
|
||||
LOCKED_BINARY_INPUTS = {
|
||||
'app/libs/libv2ray.aar': '3d43b9344723e9c0625527de4f2bea0ee02c21180224e5ecab3384af143ca6d0',
|
||||
'app/libs/quickie-foss-1.14.0.aar': '4d90e9cb37e07b57eaa3a839be2abdc422c0ce9ac8e969720a2a71c968cd771f',
|
||||
'app/libs/Toasty-1.5.2.aar': '57866e731ebe3ef82328942cd4d96cf940b2406c9440f33857f69777027f36b5',
|
||||
'app/libs/arm64-v8a/libhev-socks5-tunnel.so': '4eb0b2353f4fb6d45f43cca39fe72197ce9df8c8f5ba5a82feac87abceb9ea7a',
|
||||
'app/libs/armeabi-v7a/libhev-socks5-tunnel.so': '816c48bab1785fcdaaf7fc2f49dc6b0733cf11e68b9379640d22d6a539f306ff',
|
||||
'app/libs/x86/libhev-socks5-tunnel.so': '6e42da45387d76630a8ffd52ea45cd5738395da39df31dba1a48806fa79d3572',
|
||||
'app/libs/x86_64/libhev-socks5-tunnel.so': 'c61a54f38f61feb73b465d2245fe6e4746c2efba7e9024de8de025ce3fc9206e',
|
||||
}
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
with Path(path).open('x', encoding='utf-8', newline='\n') as stream:
|
||||
json.dump(value, stream, indent=2, ensure_ascii=False)
|
||||
stream.write('\n')
|
||||
|
||||
|
||||
def main(job):
|
||||
job = Path(job).resolve()
|
||||
if not re.fullmatch(r'ucvl-android-104-[a-f0-9]{32}', job.name):
|
||||
raise RuntimeError('Unexpected candidate job')
|
||||
candidate = json.loads((job / 'evidence/candidate.json').read_text(encoding='utf-8'))
|
||||
if candidate['Version'] != VERSION or candidate['VersionCode'] != 4010004 or candidate['Published']:
|
||||
raise RuntimeError('Unexpected candidate contract')
|
||||
inputs_path = job / 'evidence/build-inputs.json'
|
||||
if digest(inputs_path) != candidate['BuildInputsSha256'].lower():
|
||||
raise RuntimeError('Build input manifest changed')
|
||||
inputs = json.loads(inputs_path.read_text(encoding='utf-8'))
|
||||
public = job / 'public-source-final'
|
||||
matched = 0
|
||||
binary_inputs = []
|
||||
for row in inputs:
|
||||
name, expected = row['Path'], row['Sha256'].lower()
|
||||
if digest(job / 'project' / name) != expected or digest(REPO / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('Build/source drift: ' + name)
|
||||
if name in LOCKED_BINARY_INPUTS:
|
||||
if expected != LOCKED_BINARY_INPUTS[name]:
|
||||
raise RuntimeError('Dependency differs from public restoration lock: ' + name)
|
||||
binary_inputs.append({'path': name, 'sha256': expected})
|
||||
else:
|
||||
if digest(public / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('GPL snapshot does not match compiled input: ' + name)
|
||||
matched += 1
|
||||
if len(binary_inputs) != len(LOCKED_BINARY_INPUTS):
|
||||
raise RuntimeError('Missing locked binary dependencies')
|
||||
|
||||
inventory = []
|
||||
forbidden = {'.jks', '.keystore', '.p12', '.pfx', '.pem', '.apk', '.aar', '.so', '.idsig', '.log'}
|
||||
for path in sorted(public.rglob('*')):
|
||||
if not path.is_file():
|
||||
continue
|
||||
name = path.relative_to(public).as_posix()
|
||||
if path.is_symlink() or name.casefold().startswith('zero3-helper/') or any(part.casefold() in {'.git', '.tools', 'build', 'releases', '.gradle'} for part in path.relative_to(public).parts):
|
||||
raise RuntimeError('Private/generated directory exported: ' + name)
|
||||
if path.suffix.casefold() in forbidden or path.name in {'signing.properties', 'local.properties'}:
|
||||
raise RuntimeError('Private/binary build input exported: ' + name)
|
||||
if re.search(rb'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----', path.read_bytes()):
|
||||
raise RuntimeError('Private key marker exported: ' + name)
|
||||
inventory.append({'path': name, 'bytes': path.stat().st_size, 'sha256': digest(path)})
|
||||
required = ['LICENSE', 'README.md', 'README-UPSTREAM.md', 'SOURCE-PROVENANCE.json', 'Restore-Dependencies.py',
|
||||
'V2rayNG/app/src/main/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuard.kt',
|
||||
'V2rayNG/app/src/test/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuardTest.kt']
|
||||
if any(not (public / name).is_file() for name in required):
|
||||
raise RuntimeError('GPL source snapshot incomplete')
|
||||
output = REPO / '.tools/candidates' / ('android-1.0.4-20260924-' + job.name.rsplit('-', 1)[1][:8] + '-final')
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
packages = []
|
||||
for package in candidate['Packages']:
|
||||
signed = job / 'artifacts' / package['Name']
|
||||
if digest(signed) != package['Sha256'].lower():
|
||||
raise RuntimeError('Signed APK changed')
|
||||
unsigned = job / 'project/app/build/outputs/apk/playstore/release' / package['Name']
|
||||
with zipfile.ZipFile(unsigned) as before, zipfile.ZipFile(signed) as after:
|
||||
added = set(after.namelist()) - set(before.namelist())
|
||||
if before.testzip() is not None or after.testzip() is not None or set(before.namelist()) - set(after.namelist()):
|
||||
raise RuntimeError('Signed APK removed or corrupted compiled entries')
|
||||
if added != {'META-INF/MANIFEST.MF', 'META-INF/UCVL-ZON.RSA', 'META-INF/UCVL-ZON.SF'}:
|
||||
raise RuntimeError('Unexpected entries added during signing')
|
||||
for name in before.namelist():
|
||||
if before.read(name) != after.read(name):
|
||||
raise RuntimeError('APK entry modified after build: ' + name)
|
||||
dex = {name: hashlib.sha256(after.read(name)).hexdigest() for name in after.namelist() if re.fullmatch(r'classes\d*\.dex', name)}
|
||||
shutil.copy2(signed, output / signed.name)
|
||||
packages.append({**package, 'DexSha256': dex, 'AllUnsignedZipEntriesPreserved': True, 'AddedSigningMetadata': sorted(added)})
|
||||
|
||||
save(output / 'android-1.0.4-source-inventory.json', inventory)
|
||||
source_archive = output / 'UCVL-Zonghengjia-1.0.4-source.zip'
|
||||
with zipfile.ZipFile(source_archive, 'x', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
||||
for row in inventory:
|
||||
archive.write(public / row['path'], 'UCVL-Zonghengjia-1.0.4-source/' + row['path'])
|
||||
with zipfile.ZipFile(source_archive) as archive:
|
||||
if archive.testzip() is not None or len(archive.namelist()) != len(inventory):
|
||||
raise RuntimeError('Source archive verification failed')
|
||||
report = {
|
||||
'Version': VERSION, 'BaseVersionCode': 10004, 'ApkVersionCode': 4010004,
|
||||
'Packages': packages, 'SourceArchive': source_archive.name, 'SourceArchiveSha256': digest(source_archive),
|
||||
'SourceInventorySha256': digest(output / 'android-1.0.4-source-inventory.json'), 'SourceFiles': len(inventory),
|
||||
'CompiledPublicSourceInputsMatched': matched, 'LockedRestorableBinaryInputs': binary_inputs,
|
||||
'BuildInputManifestSha256': digest(inputs_path), 'UnitTests': 41, 'AuthorizationLifecycleJvmTests': 10,
|
||||
'OriginalCompanySignerMatches102And103': True, 'PrivateZero3Excluded': True,
|
||||
'PhysicalDeviceTested': False, 'AndroidServiceBroadcastTested': False, 'EmulatorStarted': False,
|
||||
'StableReleaseAccepted': False, 'Published': False,
|
||||
'RemainingGates': ['Physical Android VPN permission and data path', 'Real Service/broadcast lifecycle for replaced login',
|
||||
'Wi-Fi/mobile transitions, sleep/wake and recovery', 'Authenticated sustained business session'],
|
||||
}
|
||||
save(output / 'android-1.0.4-candidate.json', report)
|
||||
shutil.copytree(job / 'evidence', output / 'local-evidence')
|
||||
shutil.copytree(job / 'source-evidence-final', output / 'source-export-evidence')
|
||||
with (output / 'SHA256SUMS.txt').open('x', encoding='ascii', newline='\n') as stream:
|
||||
for path in sorted(output.iterdir()):
|
||||
if path.is_file() and path.name != 'SHA256SUMS.txt':
|
||||
stream.write(digest(path) + ' ' + path.name + '\n')
|
||||
print(json.dumps({'output': str(output), 'source_files': len(inventory), 'source_sha256': digest(source_archive),
|
||||
'public_compiled_inputs_matched': matched, 'packages': packages}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('job')
|
||||
main(parser.parse_args().job)
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Bind isolated APKs to their exact build inputs and reviewed GPL source. No network or devices."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import zipfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
VERSION = '1.0.5'
|
||||
LOCKED_BINARY_INPUTS = {
|
||||
'app/libs/libv2ray.aar': '3d43b9344723e9c0625527de4f2bea0ee02c21180224e5ecab3384af143ca6d0',
|
||||
'app/libs/quickie-foss-1.14.0.aar': '4d90e9cb37e07b57eaa3a839be2abdc422c0ce9ac8e969720a2a71c968cd771f',
|
||||
'app/libs/Toasty-1.5.2.aar': '57866e731ebe3ef82328942cd4d96cf940b2406c9440f33857f69777027f36b5',
|
||||
'app/libs/arm64-v8a/libhev-socks5-tunnel.so': '4eb0b2353f4fb6d45f43cca39fe72197ce9df8c8f5ba5a82feac87abceb9ea7a',
|
||||
'app/libs/armeabi-v7a/libhev-socks5-tunnel.so': '816c48bab1785fcdaaf7fc2f49dc6b0733cf11e68b9379640d22d6a539f306ff',
|
||||
'app/libs/x86/libhev-socks5-tunnel.so': '6e42da45387d76630a8ffd52ea45cd5738395da39df31dba1a48806fa79d3572',
|
||||
'app/libs/x86_64/libhev-socks5-tunnel.so': 'c61a54f38f61feb73b465d2245fe6e4746c2efba7e9024de8de025ce3fc9206e',
|
||||
}
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
with Path(path).open('x', encoding='utf-8', newline='\n') as stream:
|
||||
json.dump(value, stream, indent=2, ensure_ascii=False)
|
||||
stream.write('\n')
|
||||
|
||||
|
||||
def main(job):
|
||||
job = Path(job).resolve()
|
||||
if not re.fullmatch(r'ucvl-android-105-[a-f0-9]{32}', job.name):
|
||||
raise RuntimeError('Unexpected candidate job')
|
||||
candidate = json.loads((job / 'evidence/candidate.json').read_text(encoding='utf-8'))
|
||||
if candidate['Version'] != VERSION or candidate['VersionCode'] != 4010005 or candidate['Published']:
|
||||
raise RuntimeError('Unexpected candidate contract')
|
||||
inputs_path = job / 'evidence/build-inputs.json'
|
||||
if digest(inputs_path) != candidate['BuildInputsSha256'].lower():
|
||||
raise RuntimeError('Build input manifest changed')
|
||||
inputs = json.loads(inputs_path.read_text(encoding='utf-8'))
|
||||
public = job / 'public-source-final'
|
||||
matched = 0
|
||||
binary_inputs = []
|
||||
for row in inputs:
|
||||
name, expected = row['Path'], row['Sha256'].lower()
|
||||
if digest(job / 'project' / name) != expected or digest(REPO / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('Build/source drift: ' + name)
|
||||
if name in LOCKED_BINARY_INPUTS:
|
||||
if expected != LOCKED_BINARY_INPUTS[name]:
|
||||
raise RuntimeError('Dependency differs from public restoration lock: ' + name)
|
||||
binary_inputs.append({'path': name, 'sha256': expected})
|
||||
else:
|
||||
if digest(public / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('GPL snapshot does not match compiled input: ' + name)
|
||||
matched += 1
|
||||
if len(binary_inputs) != len(LOCKED_BINARY_INPUTS):
|
||||
raise RuntimeError('Missing locked binary dependencies')
|
||||
|
||||
inventory = []
|
||||
forbidden = {'.jks', '.keystore', '.p12', '.pfx', '.pem', '.apk', '.aar', '.so', '.idsig', '.log'}
|
||||
for path in sorted(public.rglob('*')):
|
||||
if not path.is_file():
|
||||
continue
|
||||
name = path.relative_to(public).as_posix()
|
||||
if path.is_symlink() or name.casefold().startswith('zero3-helper/') or any(part.casefold() in {'.git', '.tools', 'build', 'releases', '.gradle'} for part in path.relative_to(public).parts):
|
||||
raise RuntimeError('Private/generated directory exported: ' + name)
|
||||
if path.suffix.casefold() in forbidden or path.name in {'signing.properties', 'local.properties'}:
|
||||
raise RuntimeError('Private/binary build input exported: ' + name)
|
||||
if re.search(rb'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----', path.read_bytes()):
|
||||
raise RuntimeError('Private key marker exported: ' + name)
|
||||
inventory.append({'path': name, 'bytes': path.stat().st_size, 'sha256': digest(path)})
|
||||
required = ['LICENSE', 'README.md', 'README-UPSTREAM.md', 'SOURCE-PROVENANCE.json', 'Restore-Dependencies.py',
|
||||
'V2rayNG/app/src/main/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuard.kt',
|
||||
'V2rayNG/app/src/test/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuardTest.kt']
|
||||
if any(not (public / name).is_file() for name in required):
|
||||
raise RuntimeError('GPL source snapshot incomplete')
|
||||
output = REPO / '.tools/candidates' / ('android-1.0.5-20261016-' + job.name.rsplit('-', 1)[1][:8] + '-final')
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
packages = []
|
||||
for package in candidate['Packages']:
|
||||
signed = job / 'artifacts' / package['Name']
|
||||
if digest(signed) != package['Sha256'].lower():
|
||||
raise RuntimeError('Signed APK changed')
|
||||
unsigned = job / 'project/app/build/outputs/apk/playstore/release' / package['Name']
|
||||
with zipfile.ZipFile(unsigned) as before, zipfile.ZipFile(signed) as after:
|
||||
added = set(after.namelist()) - set(before.namelist())
|
||||
if before.testzip() is not None or after.testzip() is not None or set(before.namelist()) - set(after.namelist()):
|
||||
raise RuntimeError('Signed APK removed or corrupted compiled entries')
|
||||
if added != {'META-INF/MANIFEST.MF', 'META-INF/UCVL-ZON.RSA', 'META-INF/UCVL-ZON.SF'}:
|
||||
raise RuntimeError('Unexpected entries added during signing')
|
||||
for name in before.namelist():
|
||||
if before.read(name) != after.read(name):
|
||||
raise RuntimeError('APK entry modified after build: ' + name)
|
||||
dex = {name: hashlib.sha256(after.read(name)).hexdigest() for name in after.namelist() if re.fullmatch(r'classes\d*\.dex', name)}
|
||||
shutil.copy2(signed, output / signed.name)
|
||||
packages.append({**package, 'DexSha256': dex, 'AllUnsignedZipEntriesPreserved': True, 'AddedSigningMetadata': sorted(added)})
|
||||
|
||||
save(output / 'android-1.0.5-source-inventory.json', inventory)
|
||||
source_archive = output / 'UCVL-Zonghengjia-1.0.5-source.zip'
|
||||
with zipfile.ZipFile(source_archive, 'x', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
||||
for row in inventory:
|
||||
archive.write(public / row['path'], 'UCVL-Zonghengjia-1.0.5-source/' + row['path'])
|
||||
with zipfile.ZipFile(source_archive) as archive:
|
||||
if archive.testzip() is not None or len(archive.namelist()) != len(inventory):
|
||||
raise RuntimeError('Source archive verification failed')
|
||||
report = {
|
||||
'Version': VERSION, 'BaseVersionCode': 10005, 'ApkVersionCode': 4010005,
|
||||
'Packages': packages, 'SourceArchive': source_archive.name, 'SourceArchiveSha256': digest(source_archive),
|
||||
'SourceInventorySha256': digest(output / 'android-1.0.5-source-inventory.json'), 'SourceFiles': len(inventory),
|
||||
'CompiledPublicSourceInputsMatched': matched, 'LockedRestorableBinaryInputs': binary_inputs,
|
||||
'BuildInputManifestSha256': digest(inputs_path), 'UnitTests': 41, 'AuthorizationLifecycleJvmTests': 10,
|
||||
'OriginalCompanySignerMatches102And103': True, 'PrivateZero3Excluded': True,
|
||||
'PhysicalDeviceTested': False, 'AndroidServiceBroadcastTested': False, 'EmulatorStarted': False,
|
||||
'StableReleaseAccepted': False, 'Published': False,
|
||||
'RemainingGates': ['Physical Android VPN permission and data path', 'Real Service/broadcast lifecycle for replaced login',
|
||||
'Wi-Fi/mobile transitions, sleep/wake and recovery', 'Authenticated sustained business session'],
|
||||
}
|
||||
save(output / 'android-1.0.5-candidate.json', report)
|
||||
shutil.copytree(job / 'evidence', output / 'local-evidence')
|
||||
shutil.copytree(job / 'source-evidence-final', output / 'source-export-evidence')
|
||||
with (output / 'SHA256SUMS.txt').open('x', encoding='ascii', newline='\n') as stream:
|
||||
for path in sorted(output.iterdir()):
|
||||
if path.is_file() and path.name != 'SHA256SUMS.txt':
|
||||
stream.write(digest(path) + ' ' + path.name + '\n')
|
||||
print(json.dumps({'output': str(output), 'source_files': len(inventory), 'source_sha256': digest(source_archive),
|
||||
'public_compiled_inputs_matched': matched, 'packages': packages}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('job')
|
||||
main(parser.parse_args().job)
|
||||
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Bind isolated APKs to their exact build inputs and reviewed GPL source. No network or devices."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
VERSION = '1.0.6'
|
||||
LOCKED_BINARY_INPUTS = {
|
||||
'app/libs/libv2ray.aar': '3d43b9344723e9c0625527de4f2bea0ee02c21180224e5ecab3384af143ca6d0',
|
||||
'app/libs/quickie-foss-1.14.0.aar': '4d90e9cb37e07b57eaa3a839be2abdc422c0ce9ac8e969720a2a71c968cd771f',
|
||||
'app/libs/Toasty-1.5.2.aar': '57866e731ebe3ef82328942cd4d96cf940b2406c9440f33857f69777027f36b5',
|
||||
'app/libs/arm64-v8a/libhev-socks5-tunnel.so': '4eb0b2353f4fb6d45f43cca39fe72197ce9df8c8f5ba5a82feac87abceb9ea7a',
|
||||
'app/libs/armeabi-v7a/libhev-socks5-tunnel.so': '816c48bab1785fcdaaf7fc2f49dc6b0733cf11e68b9379640d22d6a539f306ff',
|
||||
'app/libs/x86/libhev-socks5-tunnel.so': '6e42da45387d76630a8ffd52ea45cd5738395da39df31dba1a48806fa79d3572',
|
||||
'app/libs/x86_64/libhev-socks5-tunnel.so': 'c61a54f38f61feb73b465d2245fe6e4746c2efba7e9024de8de025ce3fc9206e',
|
||||
}
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
with Path(path).open('x', encoding='utf-8', newline='\n') as stream:
|
||||
json.dump(value, stream, indent=2, ensure_ascii=False)
|
||||
stream.write('\n')
|
||||
|
||||
|
||||
|
||||
def verify_junit_evidence(job, candidate):
|
||||
"""Bind reported counts to this build's XML, not a previous candidate's totals."""
|
||||
tests = json.loads((job / 'evidence/tests.json').read_text(encoding='utf-8'))
|
||||
if tests['ExitCode'] != 0 or tests['Offline'] is not True or tests['Published'] is not False:
|
||||
raise RuntimeError('Unsuccessful or unexpected unit-test build contract')
|
||||
if tests['BuildInputsSha256'].lower() != candidate['BuildInputsSha256'].lower():
|
||||
raise RuntimeError('JUnit build input manifest differs')
|
||||
reports = job / 'project/app/build/test-results/testPlaystoreReleaseUnitTest'
|
||||
suites = []
|
||||
for path in sorted(reports.glob('TEST-*.xml')):
|
||||
suite = ET.parse(path).getroot()
|
||||
if suite.tag != 'testsuite':
|
||||
raise RuntimeError('Unexpected JUnit report root: ' + path.name)
|
||||
row = {
|
||||
'Name': suite.attrib['name'],
|
||||
'Tests': int(suite.attrib['tests']),
|
||||
'Failures': int(suite.attrib['failures']),
|
||||
'Errors': int(suite.attrib['errors']),
|
||||
'Skipped': int(suite.attrib['skipped']),
|
||||
'TestCases': len(suite.findall('testcase')),
|
||||
'ReportName': path.name,
|
||||
'ReportSha256': digest(path).upper(),
|
||||
}
|
||||
if not row['Name'] or row['Tests'] < 1 or row['Tests'] != row['TestCases']:
|
||||
raise RuntimeError('JUnit suite count differs from actual test cases: ' + path.name)
|
||||
if any(row[name] != 0 for name in ('Failures', 'Errors', 'Skipped')):
|
||||
raise RuntimeError('JUnit suite has failures, errors or skipped cases: ' + path.name)
|
||||
suites.append(row)
|
||||
if tests['Suites'] != suites:
|
||||
raise RuntimeError('JUnit evidence changed since candidate signing')
|
||||
by_name = {row['Name']: row for row in suites}
|
||||
if len(by_name) != len(suites):
|
||||
raise RuntimeError('Duplicate JUnit suite names')
|
||||
authorization = by_name.get('com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest', {}).get('Tests', 0)
|
||||
startup = by_name.get('com.v2ray.ang.ucvl.UcvlVpnStartupLeaseTest', {}).get('Tests', 0)
|
||||
total = sum(row['Tests'] for row in suites)
|
||||
if total < 41 or authorization != 10 or startup < 8:
|
||||
raise RuntimeError('Required authorization or VPN startup regressions missing')
|
||||
counts = {'UnitTests': total, 'AuthorizationLifecycleJvmTests': authorization, 'StartupLeaseJvmTests': startup}
|
||||
if any(candidate[name] != value for name, value in counts.items()):
|
||||
raise RuntimeError('Candidate test counts differ from this build JUnit XML')
|
||||
return counts
|
||||
|
||||
|
||||
def main(job):
|
||||
job = Path(job).resolve()
|
||||
if not re.fullmatch(r'ucvl-android-106-[a-f0-9]{32}', job.name):
|
||||
raise RuntimeError('Unexpected candidate job')
|
||||
candidate = json.loads((job / 'evidence/candidate.json').read_text(encoding='utf-8'))
|
||||
if candidate['Version'] != VERSION or candidate['VersionCode'] != 4010006 or candidate['Published']:
|
||||
raise RuntimeError('Unexpected candidate contract')
|
||||
test_counts = verify_junit_evidence(job, candidate)
|
||||
inputs_path = job / 'evidence/build-inputs.json'
|
||||
if digest(inputs_path) != candidate['BuildInputsSha256'].lower():
|
||||
raise RuntimeError('Build input manifest changed')
|
||||
inputs = json.loads(inputs_path.read_text(encoding='utf-8'))
|
||||
public = job / 'public-source-final'
|
||||
matched = 0
|
||||
binary_inputs = []
|
||||
for row in inputs:
|
||||
name, expected = row['Path'], row['Sha256'].lower()
|
||||
if digest(job / 'project' / name) != expected or digest(REPO / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('Build/source drift: ' + name)
|
||||
if name in LOCKED_BINARY_INPUTS:
|
||||
if expected != LOCKED_BINARY_INPUTS[name]:
|
||||
raise RuntimeError('Dependency differs from public restoration lock: ' + name)
|
||||
binary_inputs.append({'path': name, 'sha256': expected})
|
||||
else:
|
||||
if digest(public / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('GPL snapshot does not match compiled input: ' + name)
|
||||
matched += 1
|
||||
if len(binary_inputs) != len(LOCKED_BINARY_INPUTS):
|
||||
raise RuntimeError('Missing locked binary dependencies')
|
||||
|
||||
inventory = []
|
||||
forbidden = {'.jks', '.keystore', '.p12', '.pfx', '.pem', '.apk', '.aar', '.so', '.idsig', '.log'}
|
||||
for path in sorted(public.rglob('*')):
|
||||
if not path.is_file():
|
||||
continue
|
||||
name = path.relative_to(public).as_posix()
|
||||
if path.is_symlink() or name.casefold().startswith('zero3-helper/') or any(part.casefold() in {'.git', '.tools', 'build', 'releases', '.gradle'} for part in path.relative_to(public).parts):
|
||||
raise RuntimeError('Private/generated directory exported: ' + name)
|
||||
if path.suffix.casefold() in forbidden or path.name in {'signing.properties', 'local.properties'}:
|
||||
raise RuntimeError('Private/binary build input exported: ' + name)
|
||||
if re.search(rb'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----', path.read_bytes()):
|
||||
raise RuntimeError('Private key marker exported: ' + name)
|
||||
inventory.append({'path': name, 'bytes': path.stat().st_size, 'sha256': digest(path)})
|
||||
required = ['LICENSE', 'README.md', 'README-UPSTREAM.md', 'SOURCE-PROVENANCE.json', 'Restore-Dependencies.py',
|
||||
'V2rayNG/app/src/main/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuard.kt',
|
||||
'V2rayNG/app/src/test/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuardTest.kt',
|
||||
'V2rayNG/app/src/main/java/com/v2ray/ang/ucvl/UcvlVpnStartupLease.kt',
|
||||
'V2rayNG/app/src/test/java/com/v2ray/ang/ucvl/UcvlVpnStartupLeaseTest.kt']
|
||||
if any(not (public / name).is_file() for name in required):
|
||||
raise RuntimeError('GPL source snapshot incomplete')
|
||||
output = REPO / '.tools/candidates' / ('android-1.0.6-20261016-' + job.name.rsplit('-', 1)[1][:8] + '-final')
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
packages = []
|
||||
for package in candidate['Packages']:
|
||||
signed = job / 'artifacts' / package['Name']
|
||||
if digest(signed) != package['Sha256'].lower():
|
||||
raise RuntimeError('Signed APK changed')
|
||||
unsigned = job / 'project/app/build/outputs/apk/playstore/release' / package['Name']
|
||||
with zipfile.ZipFile(unsigned) as before, zipfile.ZipFile(signed) as after:
|
||||
added = set(after.namelist()) - set(before.namelist())
|
||||
if before.testzip() is not None or after.testzip() is not None or set(before.namelist()) - set(after.namelist()):
|
||||
raise RuntimeError('Signed APK removed or corrupted compiled entries')
|
||||
if added != {'META-INF/MANIFEST.MF', 'META-INF/UCVL-ZON.RSA', 'META-INF/UCVL-ZON.SF'}:
|
||||
raise RuntimeError('Unexpected entries added during signing')
|
||||
for name in before.namelist():
|
||||
if before.read(name) != after.read(name):
|
||||
raise RuntimeError('APK entry modified after build: ' + name)
|
||||
dex = {name: hashlib.sha256(after.read(name)).hexdigest() for name in after.namelist() if re.fullmatch(r'classes\d*\.dex', name)}
|
||||
shutil.copy2(signed, output / signed.name)
|
||||
packages.append({**package, 'DexSha256': dex, 'AllUnsignedZipEntriesPreserved': True, 'AddedSigningMetadata': sorted(added)})
|
||||
|
||||
save(output / 'android-1.0.6-source-inventory.json', inventory)
|
||||
source_archive = output / 'UCVL-Zonghengjia-1.0.6-source.zip'
|
||||
with zipfile.ZipFile(source_archive, 'x', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
||||
for row in inventory:
|
||||
archive.write(public / row['path'], 'UCVL-Zonghengjia-1.0.6-source/' + row['path'])
|
||||
with zipfile.ZipFile(source_archive) as archive:
|
||||
if archive.testzip() is not None or len(archive.namelist()) != len(inventory):
|
||||
raise RuntimeError('Source archive verification failed')
|
||||
report = {
|
||||
'Version': VERSION, 'BaseVersionCode': 10006, 'ApkVersionCode': 4010006,
|
||||
'Packages': packages, 'SourceArchive': source_archive.name, 'SourceArchiveSha256': digest(source_archive),
|
||||
'SourceInventorySha256': digest(output / 'android-1.0.6-source-inventory.json'), 'SourceFiles': len(inventory),
|
||||
'CompiledPublicSourceInputsMatched': matched, 'LockedRestorableBinaryInputs': binary_inputs,
|
||||
'BuildInputManifestSha256': digest(inputs_path), **test_counts,
|
||||
'OriginalCompanySignerMatches102And103': True, 'PrivateZero3Excluded': True,
|
||||
'PhysicalDeviceTested': False, 'AndroidServiceBroadcastTested': False, 'EmulatorStarted': False,
|
||||
'StableReleaseAccepted': False, 'Published': False,
|
||||
'RemainingGates': ['Physical Android VPN permission and data path', 'Real Service/broadcast lifecycle for replaced login',
|
||||
'Wi-Fi/mobile transitions, sleep/wake and recovery', 'Authenticated sustained business session'],
|
||||
}
|
||||
save(output / 'android-1.0.6-candidate.json', report)
|
||||
shutil.copytree(job / 'evidence', output / 'local-evidence')
|
||||
shutil.copytree(job / 'source-evidence-final', output / 'source-export-evidence')
|
||||
with (output / 'SHA256SUMS.txt').open('x', encoding='ascii', newline='\n') as stream:
|
||||
for path in sorted(output.iterdir()):
|
||||
if path.is_file() and path.name != 'SHA256SUMS.txt':
|
||||
stream.write(digest(path) + ' ' + path.name + '\n')
|
||||
print(json.dumps({'output': str(output), 'source_files': len(inventory), 'source_sha256': digest(source_archive),
|
||||
'public_compiled_inputs_matched': matched, 'packages': packages}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('job')
|
||||
main(parser.parse_args().job)
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Bind isolated APKs to their exact build inputs and reviewed GPL source. No network or devices."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
VERSION = '1.0.7'
|
||||
LOCKED_BINARY_INPUTS = {
|
||||
'app/libs/libv2ray.aar': '3d43b9344723e9c0625527de4f2bea0ee02c21180224e5ecab3384af143ca6d0',
|
||||
'app/libs/quickie-foss-1.14.0.aar': '4d90e9cb37e07b57eaa3a839be2abdc422c0ce9ac8e969720a2a71c968cd771f',
|
||||
'app/libs/Toasty-1.5.2.aar': '57866e731ebe3ef82328942cd4d96cf940b2406c9440f33857f69777027f36b5',
|
||||
'app/libs/arm64-v8a/libhev-socks5-tunnel.so': '4eb0b2353f4fb6d45f43cca39fe72197ce9df8c8f5ba5a82feac87abceb9ea7a',
|
||||
'app/libs/armeabi-v7a/libhev-socks5-tunnel.so': '816c48bab1785fcdaaf7fc2f49dc6b0733cf11e68b9379640d22d6a539f306ff',
|
||||
'app/libs/x86/libhev-socks5-tunnel.so': '6e42da45387d76630a8ffd52ea45cd5738395da39df31dba1a48806fa79d3572',
|
||||
'app/libs/x86_64/libhev-socks5-tunnel.so': 'c61a54f38f61feb73b465d2245fe6e4746c2efba7e9024de8de025ce3fc9206e',
|
||||
}
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
with Path(path).open('x', encoding='utf-8', newline='\n') as stream:
|
||||
json.dump(value, stream, indent=2, ensure_ascii=False)
|
||||
stream.write('\n')
|
||||
|
||||
|
||||
|
||||
def verify_junit_evidence(job, candidate):
|
||||
"""Bind reported counts to this build's XML, not a previous candidate's totals."""
|
||||
tests = json.loads((job / 'evidence/tests.json').read_text(encoding='utf-8'))
|
||||
if tests['ExitCode'] != 0 or tests['Offline'] is not True or tests['Published'] is not False:
|
||||
raise RuntimeError('Unsuccessful or unexpected unit-test build contract')
|
||||
if tests['BuildInputsSha256'].lower() != candidate['BuildInputsSha256'].lower():
|
||||
raise RuntimeError('JUnit build input manifest differs')
|
||||
reports = job / 'project/app/build/test-results/testPlaystoreReleaseUnitTest'
|
||||
suites = []
|
||||
for path in sorted(reports.glob('TEST-*.xml')):
|
||||
suite = ET.parse(path).getroot()
|
||||
if suite.tag != 'testsuite':
|
||||
raise RuntimeError('Unexpected JUnit report root: ' + path.name)
|
||||
row = {
|
||||
'Name': suite.attrib['name'],
|
||||
'Tests': int(suite.attrib['tests']),
|
||||
'Failures': int(suite.attrib['failures']),
|
||||
'Errors': int(suite.attrib['errors']),
|
||||
'Skipped': int(suite.attrib['skipped']),
|
||||
'TestCases': len(suite.findall('testcase')),
|
||||
'ReportName': path.name,
|
||||
'ReportSha256': digest(path).upper(),
|
||||
}
|
||||
if not row['Name'] or row['Tests'] < 1 or row['Tests'] != row['TestCases']:
|
||||
raise RuntimeError('JUnit suite count differs from actual test cases: ' + path.name)
|
||||
if any(row[name] != 0 for name in ('Failures', 'Errors', 'Skipped')):
|
||||
raise RuntimeError('JUnit suite has failures, errors or skipped cases: ' + path.name)
|
||||
suites.append(row)
|
||||
if tests['Suites'] != suites:
|
||||
raise RuntimeError('JUnit evidence changed since candidate signing')
|
||||
by_name = {row['Name']: row for row in suites}
|
||||
if len(by_name) != len(suites):
|
||||
raise RuntimeError('Duplicate JUnit suite names')
|
||||
authorization = by_name.get('com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest', {}).get('Tests', 0)
|
||||
startup = by_name.get('com.v2ray.ang.ucvl.UcvlVpnStartupLeaseTest', {}).get('Tests', 0)
|
||||
upgrade = by_name.get('com.v2ray.ang.ucvl.UcvlUpgradeReliabilityTest', {}).get('Tests', 0)
|
||||
total = sum(row['Tests'] for row in suites)
|
||||
if total < 41 or authorization != 10 or startup < 8 or upgrade != 8:
|
||||
raise RuntimeError('Required authorization or VPN startup regressions missing')
|
||||
counts = {'UnitTests': total, 'AuthorizationLifecycleJvmTests': authorization, 'StartupLeaseJvmTests': startup}
|
||||
if any(candidate[name] != value for name, value in counts.items()):
|
||||
raise RuntimeError('Candidate test counts differ from this build JUnit XML')
|
||||
return counts
|
||||
|
||||
|
||||
def main(job):
|
||||
job = Path(job).resolve()
|
||||
if not re.fullmatch(r'ucvl-android-107-[a-f0-9]{32}', job.name):
|
||||
raise RuntimeError('Unexpected candidate job')
|
||||
candidate = json.loads((job / 'evidence/candidate.json').read_text(encoding='utf-8'))
|
||||
if candidate['Version'] != VERSION or candidate['VersionCode'] != 4010007 or candidate['Published']:
|
||||
raise RuntimeError('Unexpected candidate contract')
|
||||
test_counts = verify_junit_evidence(job, candidate)
|
||||
inputs_path = job / 'evidence/build-inputs.json'
|
||||
if digest(inputs_path) != candidate['BuildInputsSha256'].lower():
|
||||
raise RuntimeError('Build input manifest changed')
|
||||
inputs = json.loads(inputs_path.read_text(encoding='utf-8'))
|
||||
public = job / 'public-source-final'
|
||||
matched = 0
|
||||
binary_inputs = []
|
||||
for row in inputs:
|
||||
name, expected = row['Path'], row['Sha256'].lower()
|
||||
if digest(job / 'project' / name) != expected or digest(REPO / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('Build/source drift: ' + name)
|
||||
if name in LOCKED_BINARY_INPUTS:
|
||||
if expected != LOCKED_BINARY_INPUTS[name]:
|
||||
raise RuntimeError('Dependency differs from public restoration lock: ' + name)
|
||||
binary_inputs.append({'path': name, 'sha256': expected})
|
||||
else:
|
||||
if digest(public / 'V2rayNG' / name) != expected:
|
||||
raise RuntimeError('GPL snapshot does not match compiled input: ' + name)
|
||||
matched += 1
|
||||
if len(binary_inputs) != len(LOCKED_BINARY_INPUTS):
|
||||
raise RuntimeError('Missing locked binary dependencies')
|
||||
|
||||
inventory = []
|
||||
forbidden = {'.jks', '.keystore', '.p12', '.pfx', '.pem', '.apk', '.aar', '.so', '.idsig', '.log'}
|
||||
for path in sorted(public.rglob('*')):
|
||||
if not path.is_file():
|
||||
continue
|
||||
name = path.relative_to(public).as_posix()
|
||||
if path.is_symlink() or name.casefold().startswith('zero3-helper/') or any(part.casefold() in {'.git', '.tools', 'build', 'releases', '.gradle'} for part in path.relative_to(public).parts):
|
||||
raise RuntimeError('Private/generated directory exported: ' + name)
|
||||
if path.suffix.casefold() in forbidden or path.name in {'signing.properties', 'local.properties'}:
|
||||
raise RuntimeError('Private/binary build input exported: ' + name)
|
||||
if re.search(rb'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----', path.read_bytes()):
|
||||
raise RuntimeError('Private key marker exported: ' + name)
|
||||
inventory.append({'path': name, 'bytes': path.stat().st_size, 'sha256': digest(path)})
|
||||
required = ['LICENSE', 'README.md', 'README-UPSTREAM.md', 'SOURCE-PROVENANCE.json', 'Restore-Dependencies.py',
|
||||
'V2rayNG/app/src/main/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuard.kt',
|
||||
'V2rayNG/app/src/test/java/com/v2ray/ang/ucvl/UcvlAuthorizationGuardTest.kt',
|
||||
'V2rayNG/app/src/main/java/com/v2ray/ang/ucvl/UcvlVpnStartupLease.kt',
|
||||
'V2rayNG/app/src/test/java/com/v2ray/ang/ucvl/UcvlVpnStartupLeaseTest.kt']
|
||||
if any(not (public / name).is_file() for name in required):
|
||||
raise RuntimeError('GPL source snapshot incomplete')
|
||||
output = REPO / '.tools/candidates' / ('android-1.0.7-20261107-' + job.name.rsplit('-', 1)[1][:8] + '-final')
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
packages = []
|
||||
for package in candidate['Packages']:
|
||||
signed = job / 'artifacts' / package['Name']
|
||||
if digest(signed) != package['Sha256'].lower():
|
||||
raise RuntimeError('Signed APK changed')
|
||||
unsigned = job / 'project/app/build/outputs/apk/playstore/release' / package['Name']
|
||||
with zipfile.ZipFile(unsigned) as before, zipfile.ZipFile(signed) as after:
|
||||
added = set(after.namelist()) - set(before.namelist())
|
||||
if before.testzip() is not None or after.testzip() is not None or set(before.namelist()) - set(after.namelist()):
|
||||
raise RuntimeError('Signed APK removed or corrupted compiled entries')
|
||||
if added != {'META-INF/MANIFEST.MF', 'META-INF/UCVL-ZON.RSA', 'META-INF/UCVL-ZON.SF'}:
|
||||
raise RuntimeError('Unexpected entries added during signing')
|
||||
for name in before.namelist():
|
||||
if before.read(name) != after.read(name):
|
||||
raise RuntimeError('APK entry modified after build: ' + name)
|
||||
dex = {name: hashlib.sha256(after.read(name)).hexdigest() for name in after.namelist() if re.fullmatch(r'classes\d*\.dex', name)}
|
||||
shutil.copy2(signed, output / signed.name)
|
||||
packages.append({**package, 'DexSha256': dex, 'AllUnsignedZipEntriesPreserved': True, 'AddedSigningMetadata': sorted(added)})
|
||||
|
||||
save(output / 'android-1.0.7-source-inventory.json', inventory)
|
||||
source_archive = output / 'UCVL-Zonghengjia-1.0.7-source.zip'
|
||||
with zipfile.ZipFile(source_archive, 'x', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
||||
for row in inventory:
|
||||
archive.write(public / row['path'], 'UCVL-Zonghengjia-1.0.7-source/' + row['path'])
|
||||
with zipfile.ZipFile(source_archive) as archive:
|
||||
if archive.testzip() is not None or len(archive.namelist()) != len(inventory):
|
||||
raise RuntimeError('Source archive verification failed')
|
||||
report = {
|
||||
'Version': VERSION, 'BaseVersionCode': 10007, 'ApkVersionCode': 4010007,
|
||||
'Packages': packages, 'SourceArchive': source_archive.name, 'SourceArchiveSha256': digest(source_archive),
|
||||
'SourceInventorySha256': digest(output / 'android-1.0.7-source-inventory.json'), 'SourceFiles': len(inventory),
|
||||
'CompiledPublicSourceInputsMatched': matched, 'LockedRestorableBinaryInputs': binary_inputs,
|
||||
'BuildInputManifestSha256': digest(inputs_path), **test_counts,
|
||||
'OriginalCompanySignerMatches102And103': True, 'PrivateZero3Excluded': True,
|
||||
'PhysicalDeviceTested': False, 'AndroidServiceBroadcastTested': False, 'EmulatorStarted': False,
|
||||
'StableReleaseAccepted': False, 'Published': False,
|
||||
'RemainingGates': ['Physical Android VPN permission and data path', 'Real Service/broadcast lifecycle for replaced login',
|
||||
'Wi-Fi/mobile transitions, sleep/wake and recovery', 'Authenticated sustained business session'],
|
||||
}
|
||||
save(output / 'android-1.0.7-candidate.json', report)
|
||||
shutil.copytree(job / 'evidence', output / 'local-evidence')
|
||||
shutil.copytree(job / 'source-evidence-final', output / 'source-export-evidence')
|
||||
with (output / 'SHA256SUMS.txt').open('x', encoding='ascii', newline='\n') as stream:
|
||||
for path in sorted(output.iterdir()):
|
||||
if path.is_file() and path.name != 'SHA256SUMS.txt':
|
||||
stream.write(digest(path) + ' ' + path.name + '\n')
|
||||
print(json.dumps({'output': str(output), 'source_files': len(inventory), 'source_sha256': digest(source_archive),
|
||||
'public_compiled_inputs_matched': matched, 'packages': packages}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('job')
|
||||
main(parser.parse_args().job)
|
||||
@@ -0,0 +1,48 @@
|
||||
param(
|
||||
[string]$Runtime = '',
|
||||
[ValidateSet('before','after','full')][string]$Phase = 'before'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
$source = Join-Path $repo 'V2rayNG'
|
||||
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
|
||||
if (-not $Runtime) { $Runtime = Join-Path $tempRoot ('ucvl-auth-20260917-' + [guid]::NewGuid().ToString('N')) }
|
||||
$Runtime = [IO.Path]::GetFullPath($Runtime)
|
||||
if (-not $Runtime.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -or (Split-Path $Runtime -Leaf) -notmatch '^ucvl-auth-20260917-[a-f0-9]{32}$') {
|
||||
throw 'Only a dedicated temporary ASCII build directory is allowed'
|
||||
}
|
||||
New-Item -ItemType Directory -Path $Runtime -Force | Out-Null
|
||||
foreach ($name in @('gradlew','gradlew.bat','gradle.properties','settings.gradle.kts','build.gradle.kts')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source $name) -Destination $Runtime -Force
|
||||
}
|
||||
Copy-Item -LiteralPath (Join-Path $source 'gradle') -Destination $Runtime -Recurse -Force
|
||||
$appTarget = Join-Path $Runtime 'app'
|
||||
New-Item -ItemType Directory -Path $appTarget -Force | Out-Null
|
||||
foreach ($name in @('src','libs','build.gradle.kts','proguard-rules.pro')) {
|
||||
Copy-Item -LiteralPath (Join-Path $source ('app/' + $name)) -Destination $appTarget -Recurse -Force
|
||||
}
|
||||
$env:JAVA_HOME = Join-Path $repo '.tools/jdk-staging/jdk-21.0.12.1+1'
|
||||
$env:ANDROID_HOME = Join-Path $repo '.tools/android-sdk'
|
||||
if (-not (Test-Path (Join-Path $env:JAVA_HOME 'bin/java.exe'))) { throw 'Expected JDK 21 is missing' }
|
||||
$log = Join-Path $repo ('acceptance/android-auth-' + $Phase + '-20260917.log')
|
||||
$started = Get-Date
|
||||
Push-Location $Runtime
|
||||
try {
|
||||
$gradleArgs = @('--offline','--no-daemon','--max-workers=2',':app:testPlaystoreReleaseUnitTest')
|
||||
if ($Phase -ne 'full') { $gradleArgs += @('--tests','com.v2ray.ang.ucvl.UcvlAuthorizationGuardTest') }
|
||||
& .\gradlew.bat @gradleArgs *> $log
|
||||
$testExit = $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
$suites = @()
|
||||
$resultDir = Join-Path $Runtime 'app/build/test-results/testPlaystoreReleaseUnitTest'
|
||||
if (Test-Path $resultDir) {
|
||||
foreach ($file in Get-ChildItem $resultDir -Filter 'TEST-*.xml' -File) {
|
||||
if ($file.LastWriteTime -lt $started) { continue }
|
||||
[xml]$xml = Get-Content -LiteralPath $file.FullName -Raw
|
||||
$suites += [ordered]@{name=$xml.testsuite.name; tests=[int]$xml.testsuite.tests; failures=[int]$xml.testsuite.failures; errors=[int]$xml.testsuite.errors; skipped=[int]$xml.testsuite.skipped}
|
||||
}
|
||||
}
|
||||
$report = [ordered]@{phase=$Phase; started_at=$started.ToString('o'); runtime=$Runtime; offline=$true; exit_code=$testExit; suites=$suites; source_copied=$true; emulator_started=$false; device_installed=$false; apk_published=$false; network_modified=$false}
|
||||
$report | ConvertTo-Json -Depth 5 | Set-Content -Encoding utf8 (Join-Path $repo ('acceptance/android-auth-' + $Phase + '-20260917.json'))
|
||||
$report | ConvertTo-Json -Depth 5
|
||||
exit $testExit
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Same-certificate upgrade test on our dedicated emulator; never a phone.
|
||||
|
||||
Seeds only a synthetic non-authenticating session. Does not alter host networking
|
||||
or request a production account. Run after building/signing the test APK.
|
||||
"""
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ADB = ROOT / ".tools/android-sdk/platform-tools/adb.exe"
|
||||
PACKAGE = "cn.toplc.zonghengjia"
|
||||
SERIAL = "emulator-5554"
|
||||
|
||||
|
||||
def adb(*args, timeout=60):
|
||||
return subprocess.run([str(ADB), "-s", SERIAL, *map(str, args)], capture_output=True,
|
||||
text=True, encoding="utf-8", errors="replace", timeout=timeout,
|
||||
check=True, creationflags=subprocess.CREATE_NO_WINDOW).stdout
|
||||
|
||||
|
||||
def instrument(method):
|
||||
result = adb("shell", "am", "instrument", "-w", "-r", "-e", "oldVersion", "1.0.2",
|
||||
"-e", "newVersion", "1.0.3", "-e", "class",
|
||||
"com.v2ray.ang.ucvl.UpgradeSmokeTest#" + method,
|
||||
PACKAGE + ".test/androidx.test.runner.AndroidJUnitRunner", timeout=90)
|
||||
if "OK (1 test)" not in result:
|
||||
raise RuntimeError("Instrumentation failed: " + result[-3000:])
|
||||
|
||||
|
||||
def main():
|
||||
assert adb("shell", "getprop", "ro.kernel.qemu").strip() == "1", "Dedicated emulator only"
|
||||
assert "ucvl_acceptance" in adb("emu", "avd", "name"), "Unexpected emulator image"
|
||||
assert adb("shell", "getprop", "sys.boot_completed").strip() == "1", "Emulator has not booted"
|
||||
old = ROOT / "releases/UCVL-Zonghengjia-1.0.2-android-universal.apk"
|
||||
new = ROOT / "releases/UCVL-Zonghengjia-1.0.3-android-universal.apk"
|
||||
test = ROOT / "releases/app-playstore-release-androidTest-1.0.3.apk"
|
||||
assert all(path.is_file() for path in [old, new, test])
|
||||
evidence = ROOT / "acceptance/upgrade-1.0.3.json"
|
||||
report = {"timestamp": datetime.datetime.now().astimezone().isoformat(), "serial": SERIAL,
|
||||
"old_version": "1.0.2", "new_version": "1.0.3", "passed": False,
|
||||
"physical_device_tested": False, "host_network_modified": False,
|
||||
"authenticated_vpn_connection_tested": False, "steps": []}
|
||||
try:
|
||||
adb("shell", "am", "force-stop", PACKAGE)
|
||||
assert "Success" in adb("install", "-r", old)
|
||||
assert "Success" in adb("install", "-r", test)
|
||||
instrument("seedUpgrade")
|
||||
report["steps"].append("seed_synthetic_session_on_1.0.2")
|
||||
assert "Success" in adb("install", "-r", new)
|
||||
instrument("verifyUpgrade")
|
||||
report["steps"].append("cover_upgrade_preserves_encrypted_session_login_and_device_id")
|
||||
instrument("loginVisibleAndEmptyFormIsSafe")
|
||||
report["steps"].append("login_visible_empty_submission_safe_fixture_cleared")
|
||||
report["apk_sha256"] = hashlib.sha256(new.read_bytes()).hexdigest()
|
||||
report["passed"] = True
|
||||
finally:
|
||||
adb("shell", "am", "force-stop", PACKAGE)
|
||||
evidence.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user