Release Android 1.0.9 single-node client

This commit is contained in:
UCVL Software Automation
2026-11-30 09:09:47 +08:00
parent 9c122a8913
commit 277284ea03
27 changed files with 1569 additions and 202 deletions
+7 -5
View File
@@ -1,6 +1,8 @@
# 纵横家 Android 客户端 # 纵横家 Android 客户端
版本 `1.0.8`;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。发布状态以公司安装包仓库的同版正式 Release 为准。 版本 `1.0.9`;包名 `cn.toplc.zonghengjia`。这是公司 Android 客户端的 GPL-3.0 衍生源码,不包含服务器端、账号、节点凭据或公司签名私钥。发布状态以公司安装包仓库的同版正式 Release 为准。
1.0.9 采用单节点产品逻辑:客户端固定请求 VPN004,并严格使用青岛公网入口 `47.104.134.190:11084`;不再展示或选择节点、地区、Tailscale 和调度方式。代理模式仅保留“AI 智能代理”和“全局代理”,稳定连接期间可直接切换;切换前先下载并校验新配置,失败时恢复并验证原模式,回滚失败则安全停止。主界面删除服务器流量和历史累计趋势,只保留本期/本次数值与本机代理速度趋势。登录、注册和服务域名统一为 `vpn.ucvl.cn`。
1.0.8 启动 Android VPN 后,先通过已授权的代理出口完成 HTTPS 验证,再显示已连接。第一个检查站点失败时改用独立站点。验证中可取消,刷新账号信息时可断开。连接验证与普通应用流量分别使用各自的路由规则。Android 继续使用平台为手机分配的代理入口和系统 VPN。 1.0.8 启动 Android VPN 后,先通过已授权的代理出口完成 HTTPS 验证,再显示已连接。第一个检查站点失败时改用独立站点。验证中可取消,刷新账号信息时可断开。连接验证与普通应用流量分别使用各自的路由规则。Android 继续使用平台为手机分配的代理入口和系统 VPN。
@@ -21,19 +23,19 @@
## 已实现 ## 已实现
- 公司账号登录、浏览器注册、设备授权、个人信息、套餐/额度/有效期。 - 公司账号登录、浏览器注册、设备授权、个人信息、套餐/额度/有效期。
- 由平台自动分配节点,客户端只显示实际工作节点,不提供节点选择。 - 固定使用 VPN004 的青岛公网入口,拒绝旧节点、Tailscale/CGNAT 地址、错误端口和未授权模式。
- 完整保留平台下发的路由规则,支持智能/全局代理;使用 Android VpnService + HEV 隧道接管其他应用。 - 完整保留平台下发的路由规则,支持运行中切换智能/全局代理;使用 Android VpnService + HEV 隧道接管其他应用。
- 仅统计 proxy 出站的速度/流量;速度使用 KB/s 或更大单位,直连不计入代理统计。 - 仅统计 proxy 出站的速度/流量;速度使用 KB/s 或更大单位,直连不计入代理统计。
- Android Keystore 加密会话、同一证书覆盖升级保留配置。 - Android Keystore 加密会话、同一证书覆盖升级保留配置。
- VPN 后台每 60 秒检查授权,401/403 时断开并清除会话;临时网络错误不误当账号撤销。 - VPN 后台每 60 秒检查授权,401/403 时断开并清除会话;临时网络错误不误当账号撤销。
- 退出等待服务停止,TLS 清理在后台线程执行;系统 VPN 关闭后由 Android 恢复原网络。 - 退出等待服务停止,TLS 清理在后台线程执行;系统 VPN 关闭后由 Android 恢复原网络。
- 兼容后台 `config_contract=2`,连接时把节点地址切换到统一 NPM 公网网关,同时保留每个节点的端口和 Reality SNI;旧后台仍按原配置工作。 - 只接受固定公网网关、VPN004 与 11084 端口的后台配置,同时保留 Reality SNI 和授权参数。
## 验收边界 ## 验收边界
`acceptance/` 保存实际测试记录,不把编译成功当作手机实测。原生内核三节点 × 两模式 HTTPS、系统 VPN 独立 UID、退出/后台回收、同证书覆盖升级测试已通过。独立源码副本重新下载依赖并从头构建,通过 26 项单测;生成的 APK 解包内容与候选构建逐项相同。没有 Android 实体手机测试,尚未宣称与 Windows 全功能等价。 `acceptance/` 保存实际测试记录,不把编译成功当作手机实测。原生内核三节点 × 两模式 HTTPS、系统 VPN 独立 UID、退出/后台回收、同证书覆盖升级测试已通过。独立源码副本重新下载依赖并从头构建,通过 26 项单测;生成的 APK 解包内容与候选构建逐项相同。没有 Android 实体手机测试,尚未宣称与 Windows 全功能等价。
当前没有实现 Android 未知目标失败的全量学习闭环、持续故障自动换节点和应用内静默下载安装。公司已确认的规则会随连接配置下发。1.0.7没有手机实测:真实 Service/广播、网络切换、休眠恢复和持续会话仍需独立验收,离线回归不替代这些检查。旧1.0.0版本没有本版启动更新提示时,可从公司正式发布页下载同证书 APK 直接覆盖安装。 当前没有实现 Android 未知目标失败的全量学习闭环和应用内静默下载安装。公司已确认的规则会随连接配置下发。真实 Service/广播、网络切换、休眠恢复和持续会话仍需独立验收,离线回归不替代这些检查。旧版本可从公司正式发布页下载同证书 APK 直接覆盖安装。
## 从源码构建 ## 从源码构建
+11
View File
@@ -0,0 +1,11 @@
# 纵横家 Android 1.0.9
- 固定使用 VPN004,经青岛公网入口 `47.104.134.190:11084` 连接。
- 移除 Tailscale、节点位置、节点调度和服务器出入口流量显示。
- 代理模式仅保留 AI 智能代理与全局代理。
- 支持连接期间切换代理模式,并在失败时自动恢复原模式。
- 严格拒绝旧节点、私网/CGNAT 入口、错误端口和不匹配模式。
- 保留本机代理速度趋势与本期/本次累计数值,删除历史累计趋势图。
- 平台与注册链接统一为 `vpn.ucvl.cn`。
覆盖升级会保留账号和本机配置;Android 系统仍会要求本人确认安装。
@@ -30,7 +30,7 @@ public class ProbeActivity extends Activity {
report.put("uid", android.os.Process.myUid()); report.put("uid", android.os.Process.myUid());
report.put("explicit_proxy", false); report.put("explicit_proxy", false);
String[] urls = {"https://www.google.com/generate_204", "https://api.openai.com/v1/models", String[] urls = {"https://www.google.com/generate_204", "https://api.openai.com/v1/models",
"https://chatgpt.com/backend-api/codex/models", "https://vpn.toplc.cn/"}; "https://chatgpt.com/backend-api/codex/models", "https://vpn.ucvl.cn/"};
JSONArray results = new JSONArray(); JSONArray results = new JSONArray();
int[] expected = {204, 401, 401, 200}; int[] expected = {204, 401, 401, 200};
for (int i = 0; i < urls.length; i++) { for (int i = 0; i < urls.length; i++) {
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "cn.toplc.zonghengjia" applicationId = "cn.toplc.zonghengjia"
minSdk = 24 minSdk = 24
targetSdk = 37 targetSdk = 37
versionCode = 10008 versionCode = 10009
versionName = "1.0.8" versionName = "1.0.9"
multiDexEnabled = true multiDexEnabled = true
val abiFilterList = (properties["ABI_FILTERS"] as? String)?.split(';') val abiFilterList = (properties["ABI_FILTERS"] as? String)?.split(';')
@@ -6,7 +6,10 @@ import android.widget.EditText
import android.widget.TextView import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.app.InstrumentationRegistry
import com.v2ray.ang.AppConfig
import com.v2ray.ang.R import com.v2ray.ang.R
import com.v2ray.ang.core.CoreServiceManager
import com.v2ray.ang.fmt.CustomFmt
import com.v2ray.ang.handler.MmkvManager import com.v2ray.ang.handler.MmkvManager
import org.junit.Assert.* import org.junit.Assert.*
import org.junit.Test import org.junit.Test
@@ -17,6 +20,8 @@ import java.util.concurrent.TimeUnit
/** Run only in the dedicated disposable Android acceptance emulator. No production accounts. */ /** Run only in the dedicated disposable Android acceptance emulator. No production accounts. */
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
class UpgradeSmokeTest { class UpgradeSmokeTest {
private val legacyGuid = "ucvl-upgrade-legacy-guid"
private fun requireEmulator() { private fun requireEmulator() {
val descriptor = InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("getprop ro.kernel.qemu") val descriptor = InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("getprop ro.kernel.qemu")
val value = android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).bufferedReader().use { it.readText().trim() } val value = android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).bufferedReader().use { it.readText().trim() }
@@ -25,26 +30,65 @@ class UpgradeSmokeTest {
@Test fun seedUpgrade() { @Test fun seedUpgrade() {
requireEmulator() requireEmulator()
val context = InstrumentationRegistry.getInstrumentation().targetContext val context = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals(InstrumentationRegistry.getArguments().getString("oldVersion") ?: "1.0.2", assertEquals(InstrumentationRegistry.getArguments().getString("oldVersion") ?: "1.0.8",
context.packageManager.getPackageInfo(context.packageName, 0).versionName) context.packageManager.getPackageInfo(context.packageName, 0).versionName)
UcvlSecureStore.saveToken("ucvl-upgrade-fixture-not-a-real-token") UcvlSecureStore.saveToken("ucvl-upgrade-fixture-not-a-real-token")
UcvlSecureStore.saveLastLogin("ucvl-upgrade-fixture") UcvlSecureStore.saveLastLogin("ucvl-upgrade-fixture")
MmkvManager.encodeSettings("ucvl_test_expected_device_id", UcvlSecureStore.deviceId()) MmkvManager.encodeSettings("ucvl_test_expected_device_id", UcvlSecureStore.deviceId())
val legacyRaw = """{"remarks":"legacy-upgrade-fixture","outbounds":[{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"100.67.30.7","port":11084,"users":[{"id":"11111111-2222-3333-4444-555555555555"}]}]},"streamSettings":{"security":"reality","network":"tcp","realitySettings":{"password":"legacy","serverName":"example.com"}}}]}"""
assertEquals(legacyGuid, MmkvManager.encodeServerConfig(legacyGuid, CustomFmt.parse(legacyRaw)))
MmkvManager.setSelectServer(legacyGuid)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, legacyGuid)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_CONTRACT, "")
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_ROUTE_MODE, "")
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_ACTIVE_RECORD, "")
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, false)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, true)
MmkvManager.encodeServerRaw(legacyGuid, legacyRaw)
assertEquals("ucvl-upgrade-fixture-not-a-real-token", UcvlSecureStore.loadToken()) assertEquals("ucvl-upgrade-fixture-not-a-real-token", UcvlSecureStore.loadToken())
} }
@Test fun verifyUpgrade() { @Test fun verifyUpgrade() {
requireEmulator() requireEmulator()
val context = InstrumentationRegistry.getInstrumentation().targetContext val context = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals(InstrumentationRegistry.getArguments().getString("newVersion") ?: "1.0.3", val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
context.packageManager.getPackageInfo(context.packageName, 0).versionName) assertEquals(InstrumentationRegistry.getArguments().getString("newVersion") ?: "1.0.9",
packageInfo.versionName)
assertEquals(
InstrumentationRegistry.getArguments().getString("newVersionCode")?.toLongOrNull() ?: 4_010_009L,
packageInfo.longVersionCode,
)
assertEquals("ucvl-upgrade-fixture", UcvlSecureStore.lastLogin()) assertEquals("ucvl-upgrade-fixture", UcvlSecureStore.lastLogin())
assertEquals(MmkvManager.decodeSettingsString("ucvl_test_expected_device_id"), UcvlSecureStore.deviceId()) assertEquals(MmkvManager.decodeSettingsString("ucvl_test_expected_device_id"), UcvlSecureStore.deviceId())
assertEquals("ucvl-upgrade-fixture-not-a-real-token", UcvlSecureStore.loadToken()) assertEquals("ucvl-upgrade-fixture-not-a-real-token", UcvlSecureStore.loadToken())
assertEquals(legacyGuid, MmkvManager.getSelectServer())
assertNotNull(MmkvManager.decodeServerConfig(legacyGuid))
assertEquals("", MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_CONTRACT))
assertEquals("", MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_ACTIVE_RECORD))
assertThrows(IllegalArgumentException::class.java) {
UcvlManagedConfigRecord.parse(MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_ACTIVE_RECORD))
}
assertThrows(IllegalArgumentException::class.java) {
UcvlSingleNodePolicy.validateInstalled(
MmkvManager.decodeServerRaw(legacyGuid).orEmpty(),
MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_CONTRACT),
MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_ROUTE_MODE),
)
}
UcvlSecureStore.clearToken() UcvlSecureStore.clearToken()
UcvlSecureStore.saveLastLogin("") UcvlSecureStore.saveLastLogin("")
} }
@Test fun legacyManagedConfigCannotStartFromToggle() {
requireEmulator()
val context = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals(legacyGuid, MmkvManager.getSelectServer())
assertNotNull(MmkvManager.decodeServerConfig(legacyGuid))
assertTrue(MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_FULLY_STOPPED))
assertFalse(CoreServiceManager.startVServiceFromToggle(context))
assertFalse(MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING))
}
@Test fun loginVisibleAndEmptyFormIsSafe() { @Test fun loginVisibleAndEmptyFormIsSafe() {
requireEmulator() requireEmulator()
UcvlSecureStore.clearToken() UcvlSecureStore.clearToken()
@@ -41,7 +41,10 @@ class VpnLifecycleTest {
val connectedDeadline = System.currentTimeMillis() + 45000 val connectedDeadline = System.currentTimeMillis() + 45000
while (text(R.id.statusTitle) != "已安全连接" && System.currentTimeMillis() < connectedDeadline) Thread.sleep(100) while (text(R.id.statusTitle) != "已安全连接" && System.currentTimeMillis() < connectedDeadline) Thread.sleep(100)
assertEquals("已安全连接", text(R.id.statusTitle)) assertEquals("已安全连接", text(R.id.statusTitle))
assertTrue(text(R.id.currentNode).contains("平台自动调度")) assertEquals(fixture.get("mode").asString, UcvlSingleNodePolicy.modes[
activity.findViewById<Spinner>(R.id.routeSpinner).selectedItemPosition
].id)
assertTrue("Connected users may switch proxy mode", activity.findViewById<Spinner>(R.id.routeSpinner).isEnabled)
// Finishing instrumentation force-stops the target package, including its VPN daemon. // Finishing instrumentation force-stops the target package, including its VPN daemon.
// Keep it alive while the host starts the separate-UID probe application. // Keep it alive while the host starts the separate-UID probe application.
File(ctx.filesDir, "vpn-acceptance-ready.json").writeText("{\"connected\":true}") File(ctx.filesDir, "vpn-acceptance-ready.json").writeText("{\"connected\":true}")
@@ -163,8 +163,17 @@ object AppConfig {
const val MSG_STATE_START_FAILURE = 32 const val MSG_STATE_START_FAILURE = 32
const val MSG_STATE_VERIFYING = 33 const val MSG_STATE_VERIFYING = 33
const val PREF_UCVL_MANAGED_PROFILE = "ucvl_managed_profile" const val PREF_UCVL_MANAGED_PROFILE = "ucvl_managed_profile"
const val PREF_UCVL_MANAGED_CONTRACT = "ucvl_managed_contract"
const val PREF_UCVL_MANAGED_ROUTE_MODE = "ucvl_managed_route_mode"
const val PREF_UCVL_ACTIVE_RECORD = "ucvl_active_record"
const val PREF_UCVL_PENDING_ROLLBACK = "ucvl_pending_rollback"
const val PREF_UCVL_DESIRED_RUNNING = "ucvl_desired_running"
const val PREF_UCVL_FULLY_STOPPED = "ucvl_fully_stopped"
const val PREF_UCVL_START_ACK = "ucvl_start_ack"
const val PREF_UCVL_STOP_ACK = "ucvl_stop_ack"
const val MSG_STATE_STOP = 4 const val MSG_STATE_STOP = 4
const val MSG_STATE_STOP_SUCCESS = 41 const val MSG_STATE_STOP_SUCCESS = 41
const val MSG_STATE_STOP_FAILURE = 42
const val MSG_STATE_RESTART = 5 const val MSG_STATE_RESTART = 5
const val MSG_MEASURE_DELAY = 6 const val MSG_MEASURE_DELAY = 6
const val MSG_MEASURE_DELAY_SUCCESS = 61 const val MSG_MEASURE_DELAY_SUCCESS = 61
@@ -30,6 +30,7 @@ import com.v2ray.ang.service.IDialerService
import com.v2ray.ang.util.LogUtil import com.v2ray.ang.util.LogUtil
import com.v2ray.ang.util.MessageUtil import com.v2ray.ang.util.MessageUtil
import com.v2ray.ang.util.Utils import com.v2ray.ang.util.Utils
import com.v2ray.ang.ucvl.UcvlManagedConfigRecord
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -107,8 +108,10 @@ object CoreServiceManager {
* @param context The context from which the service is stopped. * @param context The context from which the service is stopped.
*/ */
fun stopVService(context: Context) { fun stopVService(context: Context) {
//context.toast(R.string.toast_services_stop) MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, false)
MessageUtil.sendMsg2Service(context, AppConfig.MSG_STATE_STOP, "") MessageUtil.sendMsg2Service(context, AppConfig.MSG_STATE_STOP, "")
context.stopService(Intent(context.applicationContext, CoreVpnService::class.java))
context.stopService(Intent(context.applicationContext, CoreProxyOnlyService::class.java))
} }
/** /**
@@ -140,6 +143,9 @@ object CoreServiceManager {
LogUtil.w(AppConfig.TAG, "StartCore-Manager: Core already running") LogUtil.w(AppConfig.TAG, "StartCore-Manager: Core already running")
return return
} }
check(MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_FULLY_STOPPED)) {
"上一连接仍在停止,请稍候再连接。"
}
val guid = MmkvManager.getSelectServer() val guid = MmkvManager.getSelectServer()
?: run { ?: run {
@@ -147,6 +153,10 @@ object CoreServiceManager {
error(context.getString(R.string.app_tile_first_use)) error(context.getString(R.string.app_tile_first_use))
} }
// Reject stale/partially migrated managed state before decoding any
// legacy profile. This keeps every non-UI entry point fail-closed.
validateManagedSelection(guid)
val config = MmkvManager.decodeServerConfig(guid) val config = MmkvManager.decodeServerConfig(guid)
?: run { ?: run {
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to decode server config") LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to decode server config")
@@ -183,11 +193,17 @@ object CoreServiceManager {
} }
try { try {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, true)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, false)
ContextCompat.startForegroundService(context, intent) ContextCompat.startForegroundService(context, intent)
} catch (e: SecurityException) { } catch (e: SecurityException) {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, false)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, true)
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Missing permission to start foreground service", e) LogUtil.e(AppConfig.TAG, "StartCore-Manager: Missing permission to start foreground service", e)
throw IllegalStateException(e.message ?: e.javaClass.simpleName, e) throw IllegalStateException(e.message ?: e.javaClass.simpleName, e)
} catch (e: RuntimeException) { } catch (e: RuntimeException) {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, false)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
e.javaClass.name == "android.app.ForegroundServiceStartNotAllowedException" e.javaClass.name == "android.app.ForegroundServiceStartNotAllowedException"
) { ) {
@@ -225,7 +241,6 @@ object CoreServiceManager {
val message = e.message?.takeUnless { it.isBlank() } ?: e.javaClass.simpleName val message = e.message?.takeUnless { it.isBlank() } ?: e.javaClass.simpleName
LogUtil.e(AppConfig.TAG, "StartCore-Manager: $message", e) LogUtil.e(AppConfig.TAG, "StartCore-Manager: $message", e)
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, message) MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, message)
if (serviceControl?.get() === control) stopCoreLoop()
return false return false
} }
} }
@@ -239,6 +254,10 @@ object CoreServiceManager {
@Throws(Exception::class) @Throws(Exception::class)
private fun doStartCoreLoop(service: Service, vpnInterface: ParcelFileDescriptor?, control: ServiceControl, epoch: Long) { private fun doStartCoreLoop(service: Service, vpnInterface: ParcelFileDescriptor?, control: ServiceControl, epoch: Long) {
val guid = MmkvManager.getSelectServer() ?: error("No server selected") val guid = MmkvManager.getSelectServer() ?: error("No server selected")
check(MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING)) {
"VPN startup was cancelled"
}
validateManagedSelection(guid)
val config = MmkvManager.decodeServerConfig(guid) ?: error("Failed to decode server config") val config = MmkvManager.decodeServerConfig(guid) ?: error("Failed to decode server config")
LogUtil.i(AppConfig.TAG, "StartCore-Manager: Starting core loop for ${config.remarks}") LogUtil.i(AppConfig.TAG, "StartCore-Manager: Starting core loop for ${config.remarks}")
@@ -295,7 +314,7 @@ object CoreServiceManager {
requireSession(control, epoch) requireSession(control, epoch)
val generation = coreGeneration.get() val generation = coreGeneration.get()
if (service is CoreVpnService && guid == MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE)) { if (service is CoreVpnService) {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_VERIFYING, "") MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_VERIFYING, "")
service.verifyEgress(epoch) { ready -> service.verifyEgress(epoch) { ready ->
if (ready) { if (ready) {
@@ -315,6 +334,7 @@ object CoreServiceManager {
if (serviceControl?.get() !== control || coreGeneration.get() != generation || !coreController.isRunning) return false if (serviceControl?.get() !== control || coreGeneration.get() != generation || !coreController.isRunning) return false
val reported = control.reportIfSessionValid(epoch) { val reported = control.reportIfSessionValid(epoch) {
verifiedGeneration.set(generation) verifiedGeneration.set(generation)
incrementAck(AppConfig.PREF_UCVL_START_ACK)
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "") MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
} }
if (reported && isRunning()) NotificationManager.startSpeedNotification() if (reported && isRunning()) NotificationManager.startSpeedNotification()
@@ -326,22 +346,25 @@ object CoreServiceManager {
* Unregisters broadcast receivers, stops notifications, and shuts down plugins. * Unregisters broadcast receivers, stops notifications, and shuts down plugins.
* @return True if the core was stopped successfully, false otherwise. * @return True if the core was stopped successfully, false otherwise.
*/ */
fun stopCoreLoop(): Boolean { fun stopCoreLoop(onStopped: ((Boolean) -> Unit)? = null): Boolean {
val service = getService() ?: return false val service = getService() ?: return false
val generation = coreGeneration.get() val generation = coreGeneration.get()
// Always schedule stop, even when revoke preceded native startup. The // Always schedule stop, even when revoke preceded native startup. The
// serialized generation check also prevents an old stop killing a new core. // serialized generation check also prevents an old stop killing a new core.
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
var fullyStopped = false
synchronized(coreLifecycleLock) { synchronized(coreLifecycleLock) {
if (coreGeneration.get() == generation) { if (coreGeneration.get() == generation) {
try { try {
coreController.stopLoop() coreController.stopLoop()
fullyStopped = !coreController.isRunning
} catch (e: Exception) { } catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to stop V2Ray loop", e) LogUtil.e(AppConfig.TAG, "StartCore-Manager: Failed to stop V2Ray loop", e)
} }
} }
} }
onStopped?.invoke(fullyStopped)
} }
// Close existing browser dialer // Close existing browser dialer
@@ -351,7 +374,6 @@ object CoreServiceManager {
browserDialer = null browserDialer = null
} }
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_STOP_SUCCESS, "")
NotificationManager.cancelNotification() NotificationManager.cancelNotification()
try { try {
@@ -363,6 +385,29 @@ object CoreServiceManager {
return true return true
} }
fun reportFullyStopped(service: Service) {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, true)
incrementAck(AppConfig.PREF_UCVL_STOP_ACK)
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_STOP_SUCCESS, "")
}
fun reportStopFailure(service: Service) {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, false)
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_STOP_FAILURE, "VPN 核心未能完全停止,请勿重复连接。")
}
private fun incrementAck(key: String) {
val current = MmkvManager.decodeSettingsLong(key, 0L)
MmkvManager.encodeSettings(key, if (current == Long.MAX_VALUE) 1L else current + 1L)
}
private fun validateManagedSelection(guid: String) {
val record = UcvlManagedConfigRecord.parse(
MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_ACTIVE_RECORD),
)
record.verify(guid, MmkvManager.decodeServerRaw(guid).orEmpty())
}
/** /**
* Queries and resets all outbound traffic counters in one core call. * Queries and resets all outbound traffic counters in one core call.
* Go side format: tag,direction,value;tag,direction,value; * Go side format: tag,direction,value;tag,direction,value;
@@ -8,6 +8,7 @@ import com.v2ray.ang.AppConfig
import com.v2ray.ang.contracts.ServiceControl import com.v2ray.ang.contracts.ServiceControl
import com.v2ray.ang.core.CoreServiceManager import com.v2ray.ang.core.CoreServiceManager
import com.v2ray.ang.handler.SettingsManager import com.v2ray.ang.handler.SettingsManager
import com.v2ray.ang.handler.MmkvManager
import com.v2ray.ang.util.LogUtil import com.v2ray.ang.util.LogUtil
import com.v2ray.ang.util.MyContextWrapper import com.v2ray.ang.util.MyContextWrapper
import java.lang.ref.SoftReference import java.lang.ref.SoftReference
@@ -31,7 +32,11 @@ class CoreProxyOnlyService : Service(), ServiceControl {
*/ */
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
LogUtil.i(AppConfig.TAG, "StartCore-Proxy: Service command received") LogUtil.i(AppConfig.TAG, "StartCore-Proxy: Service command received")
CoreServiceManager.startCoreLoop(null) if (!MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING) ||
!CoreServiceManager.startCoreLoop(null)
) {
stopSelf()
}
return START_STICKY return START_STICKY
} }
@@ -40,7 +45,12 @@ class CoreProxyOnlyService : Service(), ServiceControl {
*/ */
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
CoreServiceManager.stopCoreLoop() if (!CoreServiceManager.stopCoreLoop { stopped ->
if (stopped) CoreServiceManager.reportFullyStopped(this)
else CoreServiceManager.reportStopFailure(this)
}) {
CoreServiceManager.reportStopFailure(this)
}
} }
/** /**
@@ -62,6 +72,7 @@ class CoreProxyOnlyService : Service(), ServiceControl {
* Stops the service. * Stops the service.
*/ */
override fun stopService() { override fun stopService() {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, false)
stopSelf() stopSelf()
} }
@@ -55,6 +55,10 @@ class CoreVpnService : VpnService(), ServiceControl {
private val authorizationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val authorizationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var authorizationJob: Job? = null private var authorizationJob: Job? = null
private var egressJob: Job? = null private var egressJob: Job? = null
@Volatile private var stopInProgress = false
@Volatile private var nativeStopConfirmed = false
@Volatile private var serviceDestroyed = false
@Volatile private var stopOutcomeReported = false
/**destroy /**destroy
* Unfortunately registerDefaultNetworkCallback is going to return our VPN interface: https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e * Unfortunately registerDefaultNetworkCallback is going to return our VPN interface: https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e
@@ -120,6 +124,8 @@ class CoreVpnService : VpnService(), ServiceControl {
stopAllServiceOnMain(false) stopAllServiceOnMain(false)
authorizationScope.cancel() authorizationScope.cancel()
super.onDestroy() super.onDestroy()
serviceDestroyed = true
reportStopOutcomeIfReady()
LogUtil.i(AppConfig.TAG, "StartCore-VPN: Service destroyed") LogUtil.i(AppConfig.TAG, "StartCore-VPN: Service destroyed")
NotificationManager.cancelNotification() NotificationManager.cancelNotification()
@@ -131,6 +137,11 @@ class CoreVpnService : VpnService(), ServiceControl {
stopSelf() stopSelf()
return START_NOT_STICKY return START_NOT_STICKY
} }
if (!MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING)) {
stopSelf()
return START_NOT_STICKY
}
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, false)
val token = UcvlSecureStore.loadToken() val token = UcvlSecureStore.loadToken()
if (token.isNullOrBlank()) { if (token.isNullOrBlank()) {
stopSelf() stopSelf()
@@ -447,6 +458,11 @@ class CoreVpnService : VpnService(), ServiceControl {
} }
private fun stopAllServiceOnMain(isForced: Boolean) { private fun stopAllServiceOnMain(isForced: Boolean) {
if (stopInProgress) return
stopInProgress = true
if (isForced) {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, false)
}
egressJob?.cancel() egressJob?.cancel()
egressJob = null egressJob = null
authorizationJob?.cancel() authorizationJob?.cancel()
@@ -467,8 +483,6 @@ class CoreVpnService : VpnService(), ServiceControl {
tun2SocksService?.stopTun2Socks() tun2SocksService?.stopTun2Socks()
tun2SocksService = null tun2SocksService = null
CoreServiceManager.stopCoreLoop()
if (isForced) { if (isForced) {
//stopSelf has to be called ahead of mInterface.close(). otherwise v2ray core cannot be stooped //stopSelf has to be called ahead of mInterface.close(). otherwise v2ray core cannot be stooped
//It's strage but true. //It's strage but true.
@@ -485,6 +499,28 @@ class CoreVpnService : VpnService(), ServiceControl {
} catch (e: Exception) { } catch (e: Exception) {
LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface", e) LogUtil.e(AppConfig.TAG, "StartCore-VPN: Failed to close interface", e)
} }
if (!CoreServiceManager.stopCoreLoop { stopped ->
mainHandler.post {
if (stopped) {
nativeStopConfirmed = true
reportStopOutcomeIfReady()
} else if (!stopOutcomeReported) {
stopOutcomeReported = true
CoreServiceManager.reportStopFailure(this)
}
}
}) {
if (!stopOutcomeReported) {
stopOutcomeReported = true
CoreServiceManager.reportStopFailure(this)
}
}
}
private fun reportStopOutcomeIfReady() {
if (!serviceDestroyed || !nativeStopConfirmed || stopOutcomeReported) return
stopOutcomeReported = true
CoreServiceManager.reportFullyStopped(this)
} }
} }
@@ -119,6 +119,6 @@ class UcvlApiClient : Closeable {
private val cleanupExecutor = Executors.newSingleThreadExecutor { work -> private val cleanupExecutor = Executors.newSingleThreadExecutor { work ->
Thread(work, "UCVL-HTTP-cleanup").apply { isDaemon = true } Thread(work, "UCVL-HTTP-cleanup").apply { isDaemon = true }
} }
const val BASE_ADDRESS = "https://vpn.toplc.cn/" const val BASE_ADDRESS = "https://vpn.ucvl.cn/"
} }
} }
@@ -14,6 +14,7 @@ import android.os.Bundle
import android.view.View import android.view.View
import android.view.WindowManager import android.view.WindowManager
import android.view.inputmethod.EditorInfo import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.ArrayAdapter import android.widget.ArrayAdapter
import android.widget.Button import android.widget.Button
import android.widget.EditText import android.widget.EditText
@@ -53,7 +54,17 @@ class UcvlMainActivity : AppCompatActivity() {
private val mainViewModel: MainViewModel by viewModels() private val mainViewModel: MainViewModel by viewModels()
private var profile: UcvlProfile? = null private var profile: UcvlProfile? = null
private var busy = false private var busy = false
private var pendingStart = false private var pendingStart: Boolean
get() = mainViewModel.vpnPermissionPending.value == true
set(value) { mainViewModel.vpnPermissionPending.value = value }
private var connectionInFlight: Boolean
get() = mainViewModel.connectionInFlight.value == true
set(value) { mainViewModel.connectionInFlight.value = value }
private var switchingMode: Boolean
get() = mainViewModel.modeSwitchInFlight.value == true
set(value) { mainViewModel.modeSwitchInFlight.value = value }
private var suppressModeSelection = false
private var activeRouteMode = "smart"
private lateinit var loginPanel: View private lateinit var loginPanel: View
private lateinit var dashboardPanel: View private lateinit var dashboardPanel: View
@@ -66,11 +77,9 @@ class UcvlMainActivity : AppCompatActivity() {
private lateinit var statusDot: TextView private lateinit var statusDot: TextView
private lateinit var statusTitle: TextView private lateinit var statusTitle: TextView
private lateinit var statusDetail: TextView private lateinit var statusDetail: TextView
private lateinit var currentNode: TextView
private lateinit var proxySpeed: TextView private lateinit var proxySpeed: TextView
private lateinit var proxyTotal: TextView private lateinit var proxyTotal: TextView
private lateinit var speedChart: UcvlTrafficChart private lateinit var speedChart: UcvlTrafficChart
private lateinit var usageChart: UcvlTrafficChart
private val speedPoints = ArrayDeque<Pair<Long, Long>>() private val speedPoints = ArrayDeque<Pair<Long, Long>>()
private lateinit var routeSpinner: Spinner private lateinit var routeSpinner: Spinner
private lateinit var connectButton: Button private lateinit var connectButton: Button
@@ -86,6 +95,7 @@ class UcvlMainActivity : AppCompatActivity() {
startCore() startCore()
} else { } else {
pendingStart = false pendingStart = false
connectionInFlight = false
setConnectionState(false, "未连接", "需要允许系统 VPN 连接请求") setConnectionState(false, "未连接", "需要允许系统 VPN 连接请求")
availableUpdate?.let { showUpdateOffer(it, automatic = true) } availableUpdate?.let { showUpdateOffer(it, automatic = true) }
} }
@@ -139,6 +149,7 @@ class UcvlMainActivity : AppCompatActivity() {
WindowCompat.getInsetsController(window, root).isAppearanceLightNavigationBars = true WindowCompat.getInsetsController(window, root).isAppearanceLightNavigationBars = true
bindViews() bindViews()
setupActions() setupActions()
recoverInterruptedModeSwitchIfSafe()
setupCoreState() setupCoreState()
ViewCompat.requestApplyInsets(root) ViewCompat.requestApplyInsets(root)
ContextCompat.registerReceiver(this, trafficReceiver, IntentFilter(UcvlTraffic.ACTION).apply { ContextCompat.registerReceiver(this, trafficReceiver, IntentFilter(UcvlTraffic.ACTION).apply {
@@ -178,11 +189,9 @@ class UcvlMainActivity : AppCompatActivity() {
statusDot = findViewById(R.id.statusDot) statusDot = findViewById(R.id.statusDot)
statusTitle = findViewById(R.id.statusTitle) statusTitle = findViewById(R.id.statusTitle)
statusDetail = findViewById(R.id.statusDetail) statusDetail = findViewById(R.id.statusDetail)
currentNode = findViewById(R.id.currentNode)
proxySpeed = findViewById(R.id.proxySpeed) proxySpeed = findViewById(R.id.proxySpeed)
proxyTotal = findViewById(R.id.proxyTotal) proxyTotal = findViewById(R.id.proxyTotal)
speedChart = findViewById(R.id.speedChart) speedChart = findViewById(R.id.speedChart)
usageChart = findViewById(R.id.usageChart)
routeSpinner = findViewById(R.id.routeSpinner) routeSpinner = findViewById(R.id.routeSpinner)
connectButton = findViewById(R.id.connectButton) connectButton = findViewById(R.id.connectButton)
refreshButton = findViewById(R.id.refreshButton) refreshButton = findViewById(R.id.refreshButton)
@@ -200,7 +209,7 @@ class UcvlMainActivity : AppCompatActivity() {
else showUpdateOffer(offer, automatic = false) else showUpdateOffer(offer, automatic = false)
} }
findViewById<View>(R.id.registerButton).setOnClickListener { findViewById<View>(R.id.registerButton).setOnClickListener {
openWeb("https://vpn.toplc.cn/register/") openWeb("https://vpn.ucvl.cn/register/")
} }
findViewById<View>(R.id.openSourceButton).setOnClickListener { findViewById<View>(R.id.openSourceButton).setOnClickListener {
MaterialAlertDialogBuilder(this).setTitle("纵横家 Android ${BuildConfig.VERSION_NAME}") MaterialAlertDialogBuilder(this).setTitle("纵横家 Android ${BuildConfig.VERSION_NAME}")
@@ -222,6 +231,19 @@ class UcvlMainActivity : AppCompatActivity() {
} }
} }
connectButton.setOnClickListener { toggleConnection() } connectButton.setOnClickListener { toggleConnection() }
routeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (suppressModeSelection) return
val route = routeSpinner.getItemAtPosition(position) as? UcvlRouteMode ?: return
if (mainViewModel.isRunning.value == true && route.id != activeRouteMode) {
switchRouteMode(route)
} else if (mainViewModel.isRunning.value == false) {
MmkvManager.encodeSettings(LAST_ROUTE_KEY, route.id)
}
}
}
refreshButton.setOnClickListener { refreshButton.setOnClickListener {
UcvlSecureStore.loadToken()?.let { refreshProfile(it, initial = false) } UcvlSecureStore.loadToken()?.let { refreshProfile(it, initial = false) }
} }
@@ -246,10 +268,29 @@ class UcvlMainActivity : AppCompatActivity() {
private fun setupCoreState() { private fun setupCoreState() {
mainViewModel.isRunning.observe(this) { running -> mainViewModel.isRunning.observe(this) { running ->
applyRunningState(running == true) if (running == true) {
connectionInFlight = false
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_PENDING_ROLLBACK, "")
activeRouteMode = runCatching {
UcvlManagedConfigRecord.parse(
MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_ACTIVE_RECORD),
).routeMode
}.getOrDefault("smart")
selectMode(activeRouteMode)
} else if (running == false) {
recoverInterruptedModeSwitchIfSafe()
}
if (switchingMode) updateConnectControls() else applyRunningState(running)
} }
mainViewModel.isStarting.observe(this) { mainViewModel.isStarting.observe(this) {
applyRunningState(mainViewModel.isRunning.value == true) if (it != true && mainViewModel.isRunning.value == false && !pendingStart && !switchingMode) {
connectionInFlight = false
}
if (switchingMode) updateConnectControls() else applyRunningState(mainViewModel.isRunning.value)
}
mainViewModel.modeSwitchInFlight.observe(this) {
if (it == true) updateConnectControls()
else applyRunningState(mainViewModel.isRunning.value)
} }
mainViewModel.updateTestResultAction.observe(this) { result -> mainViewModel.updateTestResultAction.observe(this) { result ->
if (!result.isNullOrBlank() && mainViewModel.isRunning.value == true) { if (!result.isNullOrBlank() && mainViewModel.isRunning.value == true) {
@@ -257,6 +298,12 @@ class UcvlMainActivity : AppCompatActivity() {
} }
} }
mainViewModel.startListenBroadcast() mainViewModel.startListenBroadcast()
if (connectionInFlight && !pendingStart && mainViewModel.isStarting.value != true &&
!MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING)
) {
mainViewModel.connectionOperation++
connectionInFlight = false
}
mainViewModel.initAssets(assets) mainViewModel.initAssets(assets)
} }
@@ -314,22 +361,48 @@ class UcvlMainActivity : AppCompatActivity() {
} }
} }
private data class ManagedConfig(val raw: String, val routeMode: String)
private data class ManagedSnapshot(val record: UcvlManagedConfigRecord, val raw: String) {
val guid: String get() = record.guid
val routeMode: String get() = record.routeMode
}
private fun toggleConnection() { private fun toggleConnection() {
if (switchingMode) return
if (mainViewModel.isRunning.value == null) {
setConnectionState(false, "正在确认连接状态", "请稍候,系统正在与 VPN 服务同步")
return
}
if (connectionInFlight) {
mainViewModel.connectionOperation++
pendingStart = false
setConnectionState(false, "正在取消", "系统将恢复原网络")
lifecycleScope.launch {
setBusy(true, "正在确认 VPN 已完整停止…")
val stopped = stopCoreAndWait()
connectionInFlight = false
mainViewModel.isStarting.value = false
if (stopped) {
mainViewModel.isRunning.value = false
setConnectionState(false, "未连接", "已取消并恢复原网络")
} else {
mainViewModel.isRunning.value = null
setConnectionState(false, "取消状态未知", "请勿重复连接,关闭应用后重新打开")
}
setBusy(false)
}
return
}
if (mainViewModel.isRunning.value == true || mainViewModel.isStarting.value == true) { if (mainViewModel.isRunning.value == true || mainViewModel.isStarting.value == true) {
CoreServiceManager.stopVService(this) CoreServiceManager.stopVService(applicationContext)
setConnectionState(false, "正在断开", "系统将自动恢复原网络") setConnectionState(false, "正在断开", "系统将自动恢复原网络")
return return
} }
if (busy) return if (busy) return
val currentProfile = profile ?: return if (profile == null) return
val route = currentProfile.routeModes.getOrNull(routeSpinner.selectedItemPosition) val route = routeSpinner.selectedItem as? UcvlRouteMode
if (currentProfile.nodes.isEmpty() || route == null) { if (route == null) {
setConnectionState(false, "未连接", "暂无可用线路,请刷新或联系管理员") setConnectionState(false, "未连接", "请选择代理模式")
return
}
if (route.id == "direct") {
CoreServiceManager.stopVService(this)
setConnectionState(false, "本地直连", "当前不经过 VPN 节点")
return return
} }
val token = UcvlSecureStore.loadToken() val token = UcvlSecureStore.loadToken()
@@ -337,44 +410,228 @@ class UcvlMainActivity : AppCompatActivity() {
showLogin("登录已失效,请重新登录。") showLogin("登录已失效,请重新登录。")
return return
} }
connectionInFlight = true
val operation = ++mainViewModel.connectionOperation
lifecycleScope.launch { lifecycleScope.launch {
setBusy(true, "正在获取线路授权…") setBusy(true, "正在获取线路授权…")
setConnectionState(false, "正在连接", "平台正在自动选择节点 · ${route.name}") setConnectionState(false, "正在连接", "正在启用${route.name}")
try { try {
val response = api.config(token, "auto", route.id) val candidate = prepareManagedConfig(token, route)
if (operation != mainViewModel.connectionOperation || !connectionInFlight) return@launch
installManagedConfig(candidate)
if (operation != mainViewModel.connectionOperation || !connectionInFlight) return@launch
MmkvManager.encodeSettings(LAST_ROUTE_KEY, route.id)
activeRouteMode = route.id
requestVpnAndStart()
} catch (exception: Exception) {
if (operation != mainViewModel.connectionOperation) return@launch
pendingStart = false
connectionInFlight = false
setConnectionState(false, "连接失败", friendlyError(exception))
} finally {
if (operation == mainViewModel.connectionOperation) setBusy(false)
}
}
}
private suspend fun prepareManagedConfig(token: String, route: UcvlRouteMode): ManagedConfig {
val response = api.config(token, UcvlSingleNodePolicy.NODE_SLUG, route.id)
UcvlSingleNodePolicy.validate(response, route.id)
return withContext(Dispatchers.IO) {
SettingsManager.initAssets(this@UcvlMainActivity, assets)
val port = SettingsManager.getSocksPort().coerceIn(1024, 65534)
val raw = UcvlConfigBridge.buildRuntime(
response.config,
"纵横家",
port,
port + 1,
SettingsManager.getSocksUsername(),
SettingsManager.getSocksPassword(),
UcvlSingleNodePolicy.GATEWAY_IPV4,
).toString()
ManagedConfig(raw, route.id)
}
}
private suspend fun installManagedConfig(candidate: ManagedConfig): String =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
SettingsManager.initAssets(this@UcvlMainActivity, assets) SettingsManager.initAssets(this@UcvlMainActivity, assets)
MmkvManager.encodeSettings(AppConfig.PREF_MODE, AppConfig.VPN) MmkvManager.encodeSettings(AppConfig.PREF_MODE, AppConfig.VPN)
MmkvManager.encodeSettings(AppConfig.PREF_USE_HEV_TUNNEL, true) MmkvManager.encodeSettings(AppConfig.PREF_USE_HEV_TUNNEL, true)
// A custom raw config must use the same fixed port in both Android processes.
val port = SettingsManager.getSocksPort().coerceIn(1024, 65534) val port = SettingsManager.getSocksPort().coerceIn(1024, 65534)
MmkvManager.encodeSettings(AppConfig.PREF_DYNAMIC_SOCKS_PORT, false) MmkvManager.encodeSettings(AppConfig.PREF_DYNAMIC_SOCKS_PORT, false)
MmkvManager.encodeSettings(AppConfig.PREF_SOCKS_PORT, port.toString()) MmkvManager.encodeSettings(AppConfig.PREF_SOCKS_PORT, port.toString())
MmkvManager.encodeSettings(AppConfig.PREF_SPEED_ENABLED, true) MmkvManager.encodeSettings(AppConfig.PREF_SPEED_ENABLED, true)
MmkvManager.encodeSettings(AppConfig.PREF_PER_APP_PROXY, false) MmkvManager.encodeSettings(AppConfig.PREF_PER_APP_PROXY, false)
MmkvManager.encodeSettings(AppConfig.PREF_APPEND_HTTP_PROXY, false) MmkvManager.encodeSettings(AppConfig.PREF_APPEND_HTTP_PROXY, false)
val raw = UcvlConfigBridge.buildRuntime(response.config, response.node.name, port, port + 1, // A candidate is immutable: never overwrite the active raw that rollback may need.
SettingsManager.getSocksUsername(), SettingsManager.getSocksPassword(), val selected = MmkvManager.encodeServerConfig("", CustomFmt.parse(candidate.raw))
response.gateway?.preferredAddress()).toString() MmkvManager.encodeServerRaw(selected, candidate.raw)
val ownedGuid = MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_MANAGED_PROFILE).orEmpty() val record = UcvlManagedConfigRecord.create(selected, candidate.routeMode, candidate.raw)
val selected = MmkvManager.encodeServerConfig(ownedGuid, CustomFmt.parse(raw)) // If the process dies between these two writes, the daemon sees a GUID/record
MmkvManager.encodeServerRaw(selected, raw) // mismatch and fails closed. The final active-record write is the commit point.
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, selected)
MmkvManager.setSelectServer(selected) MmkvManager.setSelectServer(selected)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_ACTIVE_RECORD, record.encode())
// Compatibility keys are informational only; the daemon trusts ACTIVE_RECORD.
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, selected)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_CONTRACT, UcvlSingleNodePolicy.INSTALLED_CONTRACT)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_ROUTE_MODE, candidate.routeMode)
selected
} }
MmkvManager.encodeSettings(LAST_NODE_KEY, response.node.slug)
MmkvManager.encodeSettings(LAST_NODE_NAME_KEY, response.node.name) private suspend fun captureManagedSnapshot(): ManagedSnapshot? = withContext(Dispatchers.IO) {
val record = runCatching {
UcvlManagedConfigRecord.parse(MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_ACTIVE_RECORD))
}.getOrNull() ?: return@withContext null
val raw = MmkvManager.decodeServerRaw(record.guid).orEmpty()
if (raw.isBlank()) return@withContext null
record.verify(MmkvManager.getSelectServer().orEmpty(), raw)
ManagedSnapshot(record, raw)
}
private suspend fun restoreManagedSnapshot(snapshot: ManagedSnapshot) = withContext(Dispatchers.IO) {
snapshot.record.verify(snapshot.guid, snapshot.raw)
MmkvManager.setSelectServer(snapshot.guid)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_ACTIVE_RECORD, snapshot.record.encode())
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, snapshot.guid)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_CONTRACT, snapshot.record.contract)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_ROUTE_MODE, snapshot.routeMode)
}
private fun recoverInterruptedModeSwitchIfSafe(): Boolean {
if (MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING) ||
!MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_FULLY_STOPPED)
) return false
val encoded = MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_PENDING_ROLLBACK)
?.takeIf { it.isNotBlank() } ?: return false
return runCatching {
val record = UcvlManagedConfigRecord.parse(encoded)
val raw = MmkvManager.decodeServerRaw(record.guid).orEmpty()
record.verify(record.guid, raw)
MmkvManager.setSelectServer(record.guid)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_ACTIVE_RECORD, record.encode())
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_PROFILE, record.guid)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_CONTRACT, record.contract)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_MANAGED_ROUTE_MODE, record.routeMode)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_PENDING_ROLLBACK, "")
true
}.getOrDefault(false)
}
private fun switchRouteMode(route: UcvlRouteMode) {
if (busy || switchingMode || route.id == activeRouteMode) return
val token = UcvlSecureStore.loadToken()
if (token.isNullOrBlank()) {
showLogin("登录已失效,请重新登录。")
return
}
lifecycleScope.launch {
val previousMode = activeRouteMode
switchingMode = true
setBusy(true, "正在切换到${route.name}…")
try {
// Fetch and validate before touching the working connection.
val candidate = prepareManagedConfig(token, route)
val snapshot = captureManagedSnapshot()
?: throw IllegalStateException("当前连接缺少可恢复配置。")
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_PENDING_ROLLBACK, snapshot.record.encode())
val transaction = UcvlModeSwitchTransaction(
object : UcvlModeSwitchTransaction.Steps<ManagedSnapshot, ManagedConfig> {
override suspend fun stop(): Boolean = stopCoreAndWait()
override suspend fun install(candidate: ManagedConfig) {
installManagedConfig(candidate)
}
override suspend fun startAndVerify(): Boolean = startCoreAndWait()
override suspend fun restore(snapshot: ManagedSnapshot) {
restoreManagedSnapshot(snapshot)
}
override suspend fun safeStop(): Boolean = stopCoreAndWait()
},
)
when (transaction.execute(snapshot, candidate)) {
UcvlModeSwitchResult.Switched -> {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_PENDING_ROLLBACK, "")
activeRouteMode = route.id
MmkvManager.encodeSettings(LAST_ROUTE_KEY, route.id) MmkvManager.encodeSettings(LAST_ROUTE_KEY, route.id)
currentNode.text = "${response.node.name} · 平台自动调度" setConnectionState(true, "已安全连接", "已切换为${route.name}")
requestVpnAndStart() }
UcvlModeSwitchResult.StopFailed -> {
mainViewModel.isRunning.value = null
selectMode(previousMode)
setConnectionState(false, "停止确认超时", "当前状态未知,请勿重复连接")
}
UcvlModeSwitchResult.RolledBack -> {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_PENDING_ROLLBACK, "")
activeRouteMode = previousMode
MmkvManager.encodeSettings(LAST_ROUTE_KEY, previousMode)
selectMode(previousMode)
setConnectionState(true, "已恢复安全连接", "新模式不可用,已恢复原代理模式")
}
UcvlModeSwitchResult.RollbackFailed -> {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_PENDING_ROLLBACK, "")
activeRouteMode = previousMode
selectMode(previousMode)
setConnectionState(false, "切换失败", "连接已安全停止,请重新连接")
}
UcvlModeSwitchResult.RecoveryStopFailed -> {
mainViewModel.isRunning.value = null
activeRouteMode = previousMode
selectMode(previousMode)
setConnectionState(false, "连接状态未知", "恢复停止未确认,请关闭应用后重新打开")
}
}
} catch (cancelled: kotlinx.coroutines.CancellationException) {
throw cancelled
} catch (exception: Exception) { } catch (exception: Exception) {
pendingStart = false selectMode(previousMode)
setConnectionState(false, "连接失败", friendlyError(exception)) val connected = mainViewModel.isRunning.value == true
setConnectionState(
connected,
if (connected) "已安全连接" else "切换失败",
"未切换模式:${friendlyError(exception)}",
)
} finally { } finally {
switchingMode = false
setBusy(false) setBusy(false)
when (mainViewModel.isRunning.value) {
false -> setConnectionState(false, "未连接", "连接状态未通过验证,请重新连接")
null -> setConnectionState(false, "连接状态未知", "请勿重复连接,关闭应用后重新打开")
true -> Unit
} }
} }
} }
}
private suspend fun stopCoreAndWait(): Boolean {
val alreadyStopped = MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_FULLY_STOPPED)
val before = MmkvManager.decodeSettingsLong(AppConfig.PREF_UCVL_STOP_ACK, 0L)
CoreServiceManager.stopVService(applicationContext)
if (alreadyStopped) return true
repeat(300) {
if (MmkvManager.decodeSettingsLong(AppConfig.PREF_UCVL_STOP_ACK, 0L) != before &&
MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_FULLY_STOPPED)
) return true
delay(100)
}
return false
}
private suspend fun startCoreAndWait(): Boolean {
val before = MmkvManager.decodeSettingsLong(AppConfig.PREF_UCVL_START_ACK, 0L)
CoreServiceManager.startVService(applicationContext)
repeat(300) {
if (MmkvManager.decodeSettingsLong(AppConfig.PREF_UCVL_START_ACK, 0L) != before) return true
delay(100)
}
return false
}
private fun selectMode(mode: String) {
val index = UcvlSingleNodePolicy.modes.indexOfFirst { it.id == mode }.coerceAtLeast(0)
suppressModeSelection = true
routeSpinner.setSelection(index, false)
suppressModeSelection = false
}
private fun requestVpnAndStart() { private fun requestVpnAndStart() {
requestNotificationPermissionIfNeeded() requestNotificationPermissionIfNeeded()
@@ -389,8 +646,10 @@ class UcvlMainActivity : AppCompatActivity() {
private fun startCore() { private fun startCore() {
pendingStart = false pendingStart = false
connectionInFlight = true
mainViewModel.isStarting.value = true
setConnectionState(false, "正在建立安全连接", "正在启动 Android 系统 VPN") setConnectionState(false, "正在建立安全连接", "正在启动 Android 系统 VPN")
CoreServiceManager.startVService(this) CoreServiceManager.startVService(applicationContext)
} }
private fun requestNotificationPermissionIfNeeded() { private fun requestNotificationPermissionIfNeeded() {
@@ -442,10 +701,23 @@ class UcvlMainActivity : AppCompatActivity() {
val identity = if (value.identityType == "employee") "内部员工" else "外部联系人" val identity = if (value.identityType == "employee") "内部员工" else "外部联系人"
accountText.text = "${value.email} · $identity" accountText.text = "${value.email} · $identity"
routeSpinner.adapter = ArrayAdapter(this, R.layout.ucvl_spinner_item, value.routeModes) suppressModeSelection = true
val lastRoute = MmkvManager.decodeSettingsString(LAST_ROUTE_KEY, "smart").orEmpty() routeSpinner.adapter = ArrayAdapter(this, R.layout.ucvl_spinner_item, UcvlSingleNodePolicy.modes)
value.routeModes.indexOfFirst { it.id == lastRoute }.takeIf { it >= 0 }?.let(routeSpinner::setSelection) val desiredMode = UcvlSingleNodePolicy.mode(
usageChart.setPoints(value.usageHistory.orEmpty().map { it.uploadBytes to it.downloadBytes }) MmkvManager.decodeSettingsString(LAST_ROUTE_KEY, "smart"),
).id
activeRouteMode = runCatching {
UcvlManagedConfigRecord.parse(
MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_ACTIVE_RECORD),
).routeMode
}.getOrDefault("smart")
selectMode(
when (mainViewModel.isRunning.value) {
true, null -> activeRouteMode
false -> desiredMode
},
)
suppressModeSelection = false
val subscription = value.subscription val subscription = value.subscription
usageText.text = if (subscription.trafficLimitBytes > 0) { usageText.text = if (subscription.trafficLimitBytes > 0) {
@@ -458,39 +730,37 @@ class UcvlMainActivity : AppCompatActivity() {
} else 0 } else 0
val expiry = subscription.expiresAt?.take(10)?.let { " · 到期 $it" } ?: " · 长期有效" val expiry = subscription.expiresAt?.take(10)?.let { " · 到期 $it" } ?: " · 长期有效"
planText.text = "套餐:${subscription.plan} · 设备上限 ${subscription.deviceLimit} 台$expiry" planText.text = "套餐:${subscription.plan} · 设备上限 ${subscription.deviceLimit} 台$expiry"
if (value.nodes.isEmpty()) { applyRunningState(mainViewModel.isRunning.value)
setConnectionState(false, "暂无线上的线路", "请联系管理员检查节点状态")
} else {
applyRunningState(mainViewModel.isRunning.value == true)
}
} }
private fun applyRunningState(running: Boolean) { private fun applyRunningState(running: Boolean?) {
if (running) { if (running == true) {
val nodeName = MmkvManager.decodeSettingsString(LAST_NODE_NAME_KEY).orEmpty().ifBlank { "已分配节点" } val route = UcvlSingleNodePolicy.mode(activeRouteMode)
val route = profile?.routeModes?.getOrNull(routeSpinner.selectedItemPosition) setConnectionState(true, "已安全连接", route.name)
currentNode.text = "$nodeName · 平台自动调度" } else if (running == null) {
setConnectionState(true, "已安全连接", listOfNotNull(nodeName, route?.name).joinToString(" · ")) setConnectionState(false, "正在确认连接状态", "同步完成前不会覆盖或启动线路")
} else if (mainViewModel.isStarting.value == true) { } else if (mainViewModel.isStarting.value == true) {
setConnectionState(false, "正在验证连接", "通过 VPN 检查 HTTPS 是否可用") setConnectionState(false, "正在验证连接", "通过 VPN 检查 HTTPS 是否可用")
} else if (statusTitle.text != "连接失败" && statusTitle.text != "本地直连") { } else if (statusTitle.text != "连接失败") {
currentNode.text = "连接后显示实际工作节点" proxySpeed.text = "↑ 0.0 KB/s ↓ 0.0 KB/s"
proxySpeed.text = "↑ 0 B/s ↓ 0 B/s" setConnectionState(false, "未连接", "选择代理模式后点击连接")
setConnectionState(false, "未连接", "点击连接,由平台策略自动选择节点")
} }
updateConnectControls() updateConnectControls()
} }
private fun updateConnectControls() { private fun updateConnectControls() {
val running = mainViewModel.isRunning.value == true val running = mainViewModel.isRunning.value == true
val stateKnown = mainViewModel.isRunning.value != null
val verifying = mainViewModel.isStarting.value == true val verifying = mainViewModel.isStarting.value == true
connectButton.text = when { connectButton.text = when {
switchingMode -> "切换中…"
connectionInFlight -> "取消"
running -> "断开" running -> "断开"
verifying -> "取消" verifying -> "取消"
else -> "连接" else -> "连接"
} }
connectButton.isEnabled = running || verifying || (!busy && profile?.nodes?.isNotEmpty() == true) connectButton.isEnabled = stateKnown && !busy && (connectionInFlight || running || verifying || profile != null)
routeSpinner.isEnabled = !busy && !running && !verifying routeSpinner.isEnabled = stateKnown && !busy && !connectionInFlight && !verifying && !switchingMode && profile != null
} }
private fun setConnectionState(connected: Boolean, title: String, detail: String) { private fun setConnectionState(connected: Boolean, title: String, detail: String) {
@@ -586,8 +856,6 @@ class UcvlMainActivity : AppCompatActivity() {
companion object { companion object {
private const val SOURCE_URL = "https://pro.ucvl.cn/admin/ucvl-zonghengjia-android" 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 LAST_ROUTE_KEY = "ucvl_last_route" private const val LAST_ROUTE_KEY = "ucvl_last_route"
} }
} }
@@ -0,0 +1,57 @@
package com.v2ray.ang.ucvl
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import java.security.MessageDigest
data class UcvlManagedConfigRecord(
val guid: String,
val routeMode: String,
val contract: String,
val rawSha256: String,
) {
fun encode(): String = JsonObject().apply {
addProperty("guid", guid)
addProperty("route_mode", routeMode)
addProperty("contract", contract)
addProperty("raw_sha256", rawSha256)
}.toString()
fun verify(selectedGuid: String, raw: String) {
require(guid.isNotBlank() && guid == selectedGuid) { "受管线路选择不一致,请重新连接。" }
require(contract == UcvlSingleNodePolicy.INSTALLED_CONTRACT) { "受管线路版本已失效,请重新连接。" }
require(UcvlSingleNodePolicy.modes.any { it.id == routeMode }) { "受管代理模式无效,请重新连接。" }
require(rawSha256 == sha256(raw)) { "受管线路完整性校验失败,请重新连接。" }
UcvlSingleNodePolicy.validateInstalled(raw, contract, routeMode)
}
companion object {
fun create(guid: String, routeMode: String, raw: String): UcvlManagedConfigRecord {
require(guid.isNotBlank() && raw.isNotBlank())
return UcvlManagedConfigRecord(
guid = guid,
routeMode = routeMode,
contract = UcvlSingleNodePolicy.INSTALLED_CONTRACT,
rawSha256 = sha256(raw),
)
}
fun parse(encoded: String?): UcvlManagedConfigRecord {
val value = runCatching { JsonParser.parseString(encoded.orEmpty()).asJsonObject }
.getOrElse { throw IllegalArgumentException("受管线路记录损坏,请重新连接。") }
fun required(name: String): String = value.get(name)?.takeUnless { it.isJsonNull }?.asString
?.takeIf { it.isNotBlank() }
?: throw IllegalArgumentException("受管线路记录缺少 $name,请重新连接。")
return UcvlManagedConfigRecord(
guid = required("guid"),
routeMode = required("route_mode"),
contract = required("contract"),
rawSha256 = required("raw_sha256"),
)
}
private fun sha256(value: String): String = MessageDigest.getInstance("SHA-256")
.digest(value.toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it) }
}
}
@@ -0,0 +1,56 @@
package com.v2ray.ang.ucvl
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
sealed interface UcvlModeSwitchResult {
data object Switched : UcvlModeSwitchResult
data object StopFailed : UcvlModeSwitchResult
data object RolledBack : UcvlModeSwitchResult
data object RollbackFailed : UcvlModeSwitchResult
data object RecoveryStopFailed : UcvlModeSwitchResult
}
class UcvlModeSwitchTransaction<S, C>(private val steps: Steps<S, C>) {
interface Steps<S, C> {
suspend fun stop(): Boolean
suspend fun install(candidate: C)
suspend fun startAndVerify(): Boolean
suspend fun restore(snapshot: S)
suspend fun safeStop(): Boolean
}
suspend fun execute(snapshot: S, candidate: C): UcvlModeSwitchResult =
withContext(NonCancellable) {
try {
if (!steps.stop()) return@withContext UcvlModeSwitchResult.StopFailed
steps.install(candidate)
if (steps.startAndVerify()) UcvlModeSwitchResult.Switched else rollback(snapshot)
} catch (cancelled: CancellationException) {
rollback(snapshot)
throw cancelled
} catch (_: Exception) {
rollback(snapshot)
}
}
private suspend fun rollback(snapshot: S): UcvlModeSwitchResult {
return try {
if (!steps.safeStop()) return UcvlModeSwitchResult.RecoveryStopFailed
steps.restore(snapshot)
if (steps.startAndVerify()) {
UcvlModeSwitchResult.RolledBack
} else {
if (steps.safeStop()) UcvlModeSwitchResult.RollbackFailed
else UcvlModeSwitchResult.RecoveryStopFailed
}
} catch (cancelled: CancellationException) {
withContext(NonCancellable) { steps.safeStop() }
throw cancelled
} catch (_: Exception) {
if (steps.safeStop()) UcvlModeSwitchResult.RollbackFailed
else UcvlModeSwitchResult.RecoveryStopFailed
}
}
}
@@ -0,0 +1,13 @@
package com.v2ray.ang.ucvl
/** Pure policy used before the UI is allowed to mutate or restart a VPN session. */
object UcvlServiceStateReconciler {
fun initial(desiredRunning: Boolean, fullyStopped: Boolean): Boolean? =
if (!desiredRunning && fullyStopped) false else null
fun afterNotRunning(desiredRunning: Boolean, fullyStopped: Boolean): Boolean? =
initial(desiredRunning, fullyStopped)
fun afterQueryTimeout(coreServiceAlive: Boolean): Boolean? =
if (coreServiceAlive) null else false
}
@@ -0,0 +1,128 @@
package com.v2ray.ang.ucvl
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.google.gson.JsonElement
object UcvlSingleNodePolicy {
const val NODE_SLUG = "racknerd-newyork-004"
const val GATEWAY_IPV4 = "47.104.134.190"
const val PROXY_PORT = 11084
const val INSTALLED_CONTRACT = "android-1.0.9-single-node-v1"
val modes: List<UcvlRouteMode> = listOf(
UcvlRouteMode("smart", "AI 智能代理"),
UcvlRouteMode("global", "全局代理"),
)
fun mode(id: String?): UcvlRouteMode = modes.firstOrNull { it.id == id } ?: modes.first()
fun validate(response: UcvlConfigResponse, requestedMode: String) {
require(modes.any { it.id == requestedMode }) { "不支持的代理模式。" }
require(response.node.slug == NODE_SLUG) { "平台返回了非授权节点。" }
require(response.routeMode == requestedMode) { "平台返回的代理模式不一致。" }
require(response.gateway?.preferredAddress() == GATEWAY_IPV4) { "平台公网入口不一致。" }
val endpoint = response.config.validateOutboundGraph(requestedMode)
require(endpoint.get("port")?.asInt == PROXY_PORT) { "平台代理端口不一致。" }
}
fun validateInstalled(raw: String, contract: String?, routeMode: String?) {
require(contract == INSTALLED_CONTRACT) { "旧版线路已失效,请打开纵横家重新连接。" }
require(modes.any { it.id == routeMode }) { "代理模式未通过校验,请重新连接。" }
val config = runCatching { JsonParser.parseString(raw).asJsonObject }
.getOrElse { throw IllegalArgumentException("本机线路配置损坏,请重新连接。") }
val endpoint = config.validateOutboundGraph(routeMode!!)
require(endpoint.string("address") == GATEWAY_IPV4) { "本机线路入口已失效,请重新连接。" }
require(endpoint.get("port")?.asInt == PROXY_PORT) { "本机线路端口已失效,请重新连接。" }
}
private fun JsonObject.validateOutboundGraph(routeMode: String): JsonObject {
val outbounds = getAsJsonArray("outbounds")?.map { it.asJsonObject }.orEmpty()
require(outbounds.isNotEmpty()) { "线路配置没有出站信息。" }
val tags = outbounds.map { it.string("tag") }
require(tags.none { it.isBlank() } && tags.distinct().size == tags.size) { "线路出站标识无效。" }
val proxies = outbounds.filter { it.string("tag") == "proxy" && it.string("protocol") == "vless" }
val proxy = proxies.singleOrNull()
?: throw IllegalArgumentException("线路配置不是 VLESS。")
require(outbounds.first() === proxy) { "平台代理必须是默认出站。" }
outbounds.forEach { outbound ->
val expectedProtocol = when (outbound.string("tag")) {
"proxy" -> "vless"
"direct" -> "freedom"
"block" -> "blackhole"
"ucvl-dns-out" -> "dns"
else -> throw IllegalArgumentException("线路包含未授权的出站。")
}
require(outbound.string("protocol") == expectedProtocol) { "线路出站协议不受支持。" }
require(!outbound.containsKeyRecursively("proxySettings") &&
!outbound.containsKeyRecursively("dialerProxy")) {
"线路包含未授权的链式代理。"
}
if (outbound !== proxy) {
require(!outbound.has("streamSettings")) { "辅助出站不能建立远程连接。" }
}
}
require(tags.containsAll(listOf("direct", "block"))) { "线路缺少安全辅助出站。" }
val direct = outbounds.single { it.string("tag") == "direct" }
require(direct.getAsJsonObject("settings")?.entrySet()?.none { it.key == "redirect" } != false) {
"直连出站包含未授权重定向。"
}
val stream = proxy.getAsJsonObject("streamSettings")
?: throw IllegalArgumentException("线路传输配置为空。")
require(stream.string("security") == "reality" && stream.string("network") == "tcp") {
"线路传输协议不受支持。"
}
val reality = stream.getAsJsonObject("realitySettings")
?: throw IllegalArgumentException("Reality 配置为空。")
require(reality.string("serverName").isNotBlank()) { "Reality SNI 为空。" }
require(reality.string("password").isNotBlank() || reality.string("publicKey").isNotBlank()) {
"Reality 公钥为空。"
}
val endpoints = proxy.getAsJsonObject("settings")?.getAsJsonArray("vnext")
val endpoint = endpoints?.singleOrNull()?.asJsonObject
?: throw IllegalArgumentException("线路服务器信息为空。")
val routing = getAsJsonObject("routing") ?: throw IllegalArgumentException("线路缺少路由策略。")
require(routing.getAsJsonArray("balancers")?.size() in listOf(null, 0)) { "线路包含未授权负载均衡器。" }
val rules = routing.getAsJsonArray("rules")?.map { it.asJsonObject }
?: throw IllegalArgumentException("线路路由策略为空。")
val allowedTags = tags.toSet()
rules.forEach { rule ->
require(!rule.has("balancerTag")) { "路由规则包含未授权负载均衡器。" }
require(rule.string("outboundTag") in allowedTags) { "路由规则引用了未授权出站。" }
}
if (routeMode == "global") {
rules.filter { it.string("outboundTag") == "direct" }.forEach { rule ->
val ips = rule.getAsJsonArray("ip")?.map { it.asString }.orEmpty()
require(ips == listOf("geoip:private") && !rule.has("domain") && !rule.has("network")) {
"全局代理包含非私网直连规则。"
}
}
} else {
val directCatchAll = rules.indexOfFirst { rule ->
rule.string("outboundTag") == "direct" &&
rule.string("network").split(',').map { it.trim() }.containsAll(listOf("tcp", "udp")) &&
!rule.has("domain") && !rule.has("ip") && !rule.has("inboundTag")
}
require(directCatchAll >= 0) { "智能代理缺少默认直连规则。" }
require(directCatchAll == rules.lastIndex) { "智能代理默认直连规则必须位于末尾。" }
require(rules.take(directCatchAll).any { rule ->
rule.string("outboundTag") == "proxy" &&
!rule.has("inboundTag") &&
(rule.getAsJsonArray("domain")?.size()?.let { it > 0 } == true ||
rule.getAsJsonArray("ip")?.size()?.let { it > 0 } == true)
}) { "智能代理缺少业务代理规则。" }
}
return endpoint
}
private fun JsonElement.containsKeyRecursively(name: String): Boolean = when {
isJsonObject -> asJsonObject.entrySet().any { it.key == name || it.value.containsKeyRecursively(name) }
isJsonArray -> asJsonArray.any { it.containsKeyRecursively(name) }
else -> false
}
private fun JsonObject.string(name: String): String =
get(name)?.takeUnless { it.isJsonNull }?.asString.orEmpty()
}
@@ -109,7 +109,7 @@ class MainActivity : HelperBaseActivity(), NavigationView.OnNavigationItemSelect
private fun setupViewModel() { private fun setupViewModel() {
mainViewModel.updateTestResultAction.observe(this) { setTestState(it) } mainViewModel.updateTestResultAction.observe(this) { setTestState(it) }
mainViewModel.isRunning.observe(this) { isRunning -> mainViewModel.isRunning.observe(this) { isRunning ->
applyRunningState(false, isRunning) applyRunningState(false, isRunning == true)
} }
mainViewModel.startListenBroadcast() mainViewModel.startListenBroadcast()
mainViewModel.initAssets(assets) mainViewModel.initAssets(assets)
@@ -1,6 +1,7 @@
package com.v2ray.ang.viewmodel package com.v2ray.ang.viewmodel
import android.app.Application import android.app.Application
import android.app.ActivityManager
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
@@ -26,6 +27,9 @@ import com.v2ray.ang.handler.AngConfigManager
import com.v2ray.ang.handler.MmkvManager import com.v2ray.ang.handler.MmkvManager
import com.v2ray.ang.handler.SettingsManager import com.v2ray.ang.handler.SettingsManager
import com.v2ray.ang.handler.SpeedtestManager import com.v2ray.ang.handler.SpeedtestManager
import com.v2ray.ang.service.CoreProxyOnlyService
import com.v2ray.ang.service.CoreVpnService
import com.v2ray.ang.ucvl.UcvlServiceStateReconciler
import com.v2ray.ang.util.LogUtil import com.v2ray.ang.util.LogUtil
import com.v2ray.ang.util.MessageUtil import com.v2ray.ang.util.MessageUtil
import com.v2ray.ang.util.Utils import com.v2ray.ang.util.Utils
@@ -33,6 +37,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.util.Collections import java.util.Collections
@@ -43,28 +48,75 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
var subscriptionId: String = MmkvManager.decodeSettingsString(AppConfig.CACHE_SUBSCRIPTION_ID, "").orEmpty() var subscriptionId: String = MmkvManager.decodeSettingsString(AppConfig.CACHE_SUBSCRIPTION_ID, "").orEmpty()
var keywordFilter = "" var keywordFilter = ""
val serversCache = mutableListOf<ServersCache>() val serversCache = mutableListOf<ServersCache>()
val isRunning by lazy { MutableLiveData<Boolean>() } val isRunning by lazy { MutableLiveData<Boolean?>(null) }
val isStarting by lazy { MutableLiveData(false) } val isStarting by lazy { MutableLiveData(false) }
val connectionInFlight by lazy { MutableLiveData(false) }
val vpnPermissionPending by lazy { MutableLiveData(false) }
val modeSwitchInFlight by lazy { MutableLiveData(false) }
var connectionOperation: Long = 0L
val updateListAction by lazy { MutableLiveData<Int>() } val updateListAction by lazy { MutableLiveData<Int>() }
val updateTestResultAction by lazy { MutableLiveData<String>() } val updateTestResultAction by lazy { MutableLiveData<String>() }
private val tcpingTestScope by lazy { CoroutineScope(Dispatchers.IO) } private val tcpingTestScope by lazy { CoroutineScope(Dispatchers.IO) }
private var listeningForServiceState = false
private var serviceStateQueryGeneration = 0L
/** /**
* Refer to the official documentation for [registerReceiver](https://developer.android.com/reference/androidx/core/content/ContextCompat#registerReceiver(android.content.Context,android.content.BroadcastReceiver,android.content.IntentFilter,int): * Refer to the official documentation for [registerReceiver](https://developer.android.com/reference/androidx/core/content/ContextCompat#registerReceiver(android.content.Context,android.content.BroadcastReceiver,android.content.IntentFilter,int):
* `registerReceiver(Context, BroadcastReceiver, IntentFilter, int)`. * `registerReceiver(Context, BroadcastReceiver, IntentFilter, int)`.
*/ */
fun startListenBroadcast() { fun startListenBroadcast() {
isRunning.value = false val desired = MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING)
val hasActiveRecord = !MmkvManager.decodeSettingsString(AppConfig.PREF_UCVL_ACTIVE_RECORD).isNullOrBlank()
if (!desired && !hasActiveRecord) {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, true)
}
val fullyStopped = MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_FULLY_STOPPED)
isRunning.value = UcvlServiceStateReconciler.initial(desired, fullyStopped)
if (!listeningForServiceState) {
val mFilter = IntentFilter(AppConfig.BROADCAST_ACTION_ACTIVITY) val mFilter = IntentFilter(AppConfig.BROADCAST_ACTION_ACTIVITY)
ContextCompat.registerReceiver(getApplication(), mMsgReceiver, mFilter, Utils.receiverFlags()) ContextCompat.registerReceiver(getApplication(), mMsgReceiver, mFilter, Utils.receiverFlags())
listeningForServiceState = true
}
val queryGeneration = ++serviceStateQueryGeneration
MessageUtil.sendMsg2Service(getApplication(), AppConfig.MSG_REGISTER_CLIENT, "")
if (isRunning.value == null) {
viewModelScope.launch {
repeat(3) {
delay(2_500)
if (queryGeneration != serviceStateQueryGeneration || isRunning.value != null) return@launch
val reconciled = UcvlServiceStateReconciler.afterQueryTimeout(isCoreServiceAlive())
if (reconciled == false) {
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_DESIRED_RUNNING, false)
MmkvManager.encodeSettings(AppConfig.PREF_UCVL_FULLY_STOPPED, true)
isStarting.value = false
isRunning.value = false
return@launch
}
// The service exists but has not answered. Stay fail-closed and retry.
MessageUtil.sendMsg2Service(getApplication(), AppConfig.MSG_REGISTER_CLIENT, "") MessageUtil.sendMsg2Service(getApplication(), AppConfig.MSG_REGISTER_CLIENT, "")
} }
}
}
}
@Suppress("DEPRECATION")
private fun isCoreServiceAlive(): Boolean = runCatching {
val manager = getApplication<AngApplication>().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val serviceNames = setOf(CoreVpnService::class.java.name, CoreProxyOnlyService::class.java.name)
manager.getRunningServices(Int.MAX_VALUE).any {
it.service.packageName == getApplication<AngApplication>().packageName &&
it.service.className in serviceNames
}
}.getOrDefault(true)
/** /**
* Called when the ViewModel is cleared. * Called when the ViewModel is cleared.
*/ */
override fun onCleared() { override fun onCleared() {
if (listeningForServiceState) {
getApplication<AngApplication>().unregisterReceiver(mMsgReceiver) getApplication<AngApplication>().unregisterReceiver(mMsgReceiver)
listeningForServiceState = false
}
tcpingTestScope.coroutineContext[Job]?.cancelChildren() tcpingTestScope.coroutineContext[Job]?.cancelChildren()
SpeedtestManager.closeAllTcpSockets() SpeedtestManager.closeAllTcpSockets()
LogUtil.i(AppConfig.TAG, "Main ViewModel is cleared") LogUtil.i(AppConfig.TAG, "Main ViewModel is cleared")
@@ -455,15 +507,30 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
private val mMsgReceiver = object : BroadcastReceiver() { private val mMsgReceiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { override fun onReceive(ctx: Context?, intent: Intent?) {
when (intent?.getIntExtra("key", 0)) { val key = intent?.getIntExtra("key", 0)
if (key in setOf(
AppConfig.MSG_STATE_RUNNING,
AppConfig.MSG_STATE_NOT_RUNNING,
AppConfig.MSG_STATE_VERIFYING,
AppConfig.MSG_STATE_START_SUCCESS,
AppConfig.MSG_STATE_START_FAILURE,
AppConfig.MSG_STATE_STOP_SUCCESS,
AppConfig.MSG_STATE_STOP_FAILURE,
)
) {
serviceStateQueryGeneration++
}
when (key) {
AppConfig.MSG_STATE_RUNNING -> { AppConfig.MSG_STATE_RUNNING -> {
isRunning.value = true isRunning.value = true
isStarting.value = false isStarting.value = false
} }
AppConfig.MSG_STATE_NOT_RUNNING -> { AppConfig.MSG_STATE_NOT_RUNNING -> {
isRunning.value = false val desired = MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_DESIRED_RUNNING)
isStarting.value = false val fullyStopped = MmkvManager.decodeSettingsBool(AppConfig.PREF_UCVL_FULLY_STOPPED)
isRunning.value = UcvlServiceStateReconciler.afterNotRunning(desired, fullyStopped)
isStarting.value = isRunning.value != false
} }
AppConfig.MSG_STATE_VERIFYING -> { AppConfig.MSG_STATE_VERIFYING -> {
@@ -483,8 +550,10 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
} else { } else {
getApplication<AngApplication>().toastError(R.string.toast_services_failure) getApplication<AngApplication>().toastError(R.string.toast_services_failure)
} }
isRunning.value = false // A failed startup still owns a VpnService/TUN teardown. Do not
isStarting.value = false // re-enable connect until STOP_SUCCESS proves the old session exited.
isRunning.value = null
isStarting.value = true
} }
AppConfig.MSG_STATE_STOP_SUCCESS -> { AppConfig.MSG_STATE_STOP_SUCCESS -> {
@@ -492,6 +561,13 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
isStarting.value = false isStarting.value = false
} }
AppConfig.MSG_STATE_STOP_FAILURE -> {
val errorMessage = intent.getStringExtra("content") ?: "VPN 核心未能完全停止。"
getApplication<AngApplication>().toastError(errorMessage)
isRunning.value = null
isStarting.value = false
}
AppConfig.MSG_MEASURE_DELAY_SUCCESS -> { AppConfig.MSG_MEASURE_DELAY_SUCCESS -> {
updateTestResultAction.value = intent.getStringExtra("content") updateTestResultAction.value = intent.getStringExtra("content")
} }
@@ -251,7 +251,7 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="3dp" android:layout_marginTop="3dp"
android:text="点击连接,由平台自动选择节点" android:text="选择代理模式后点击连接"
android:textColor="@color/ucvl_muted" android:textColor="@color/ucvl_muted"
android:textSize="13sp" /> android:textSize="13sp" />
</LinearLayout> </LinearLayout>
@@ -277,22 +277,6 @@
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="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:text="代理模式"
android:textColor="@color/ucvl_text" android:textColor="@color/ucvl_text"
android:textStyle="bold" /> android:textStyle="bold" />
@@ -379,12 +363,6 @@
<TextView android:id="@+id/proxyTotal" android:layout_width="match_parent" <TextView android:id="@+id/proxyTotal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="本次代理 0 B · 仅统计 proxy 出站" android:layout_height="wrap_content" android:text="本次代理 0 B · 仅统计 proxy 出站"
android:textColor="@color/ucvl_muted" android:textSize="12sp" /> 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> </LinearLayout>
</com.google.android.material.card.MaterialCardView> </com.google.android.material.card.MaterialCardView>
@@ -441,7 +419,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="12dp" android:layout_marginTop="12dp"
android:gravity="center" android:gravity="center"
android:text="公司策略 · 代理流量统计\nvpn.toplc.cn · © 2026 UCVL" android:text="固定公网入口 · 代理流量仅在本机统计\nvpn.ucvl.cn · © 2026 UCVL"
android:textColor="@color/ucvl_muted" android:textColor="@color/ucvl_muted"
android:textSize="12sp" /> android:textSize="12sp" />
</LinearLayout> </LinearLayout>
@@ -0,0 +1,34 @@
package com.v2ray.ang.ucvl
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
class UcvlManagedConfigRecordTest {
private val raw = """{"outbounds":[{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"47.104.134.190","port":11084}]},"streamSettings":{"security":"reality","network":"tcp","realitySettings":{"password":"key","serverName":"example.com"}}},{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[{"type":"field","domain":["domain:openai.com"],"outboundTag":"proxy"},{"type":"field","network":"tcp,udp","outboundTag":"direct"}]}}"""
@Test fun roundTripsOneAtomicRecordAndVerifiesRaw() {
val created = UcvlManagedConfigRecord.create("new-guid", "smart", raw)
val decoded = UcvlManagedConfigRecord.parse(created.encode())
assertEquals(created, decoded)
decoded.verify("new-guid", raw)
}
@Test fun rejectsRawChangedAfterAtomicCommit() {
val record = UcvlManagedConfigRecord.create("new-guid", "smart", raw)
assertThrows(IllegalArgumentException::class.java) {
record.verify("new-guid", raw.replace("11084", "11083"))
}
}
@Test fun rejectsSelectedGuidThatDoesNotMatchActiveRecord() {
val record = UcvlManagedConfigRecord.create("new-guid", "smart", raw)
assertThrows(IllegalArgumentException::class.java) { record.verify("old-guid", raw) }
}
@Test fun rejectsLegacyOrPartialRecord() {
assertThrows(IllegalArgumentException::class.java) {
UcvlManagedConfigRecord.parse("""{"guid":"old-guid","route_mode":"smart"}""")
}
}
}
@@ -0,0 +1,130 @@
package com.v2ray.ang.ucvl
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.CancellationException
import org.junit.Assert.assertEquals
import org.junit.Test
class UcvlModeSwitchTransactionTest {
private class Steps(
private val stopResult: Boolean = true,
startResults: List<Boolean> = listOf(true),
private val installFailure: Boolean = false,
private val restoreFailure: Boolean = false,
private val safeStopResult: Boolean = true,
) : UcvlModeSwitchTransaction.Steps<String, String> {
val events = mutableListOf<String>()
private val starts = ArrayDeque(startResults)
override suspend fun stop(): Boolean = stopResult.also { events += "stop" }
override suspend fun install(candidate: String) {
events += "install:$candidate"
if (installFailure) error("install")
}
override suspend fun startAndVerify(): Boolean = starts.removeFirst().also { events += "start:$it" }
override suspend fun restore(snapshot: String) {
events += "restore:$snapshot"
if (restoreFailure) error("restore")
}
override suspend fun safeStop(): Boolean = safeStopResult.also { events += "safe-stop:$it" }
}
@Test fun commitsVerifiedModeSwitch() = runBlocking {
val steps = Steps()
val result = UcvlModeSwitchTransaction(steps).execute("smart-raw", "global-raw")
assertEquals(UcvlModeSwitchResult.Switched, result)
assertEquals(listOf("stop", "install:global-raw", "start:true"), steps.events)
}
@Test fun leavesRunningConnectionUntouchedWhenStopFails() = runBlocking {
val steps = Steps(stopResult = false)
val result = UcvlModeSwitchTransaction(steps).execute("smart-raw", "global-raw")
assertEquals(UcvlModeSwitchResult.StopFailed, result)
assertEquals(listOf("stop"), steps.events)
}
@Test fun restoresAndVerifiesPreviousModeWhenNewModeFails() = runBlocking {
val steps = Steps(startResults = listOf(false, true))
val result = UcvlModeSwitchTransaction(steps).execute("smart-raw", "global-raw")
assertEquals(UcvlModeSwitchResult.RolledBack, result)
assertEquals(
listOf("stop", "install:global-raw", "start:false", "safe-stop:true", "restore:smart-raw", "start:true"),
steps.events,
)
}
@Test fun safelyStopsWhenRollbackCannotBeVerified() = runBlocking {
val steps = Steps(startResults = listOf(false, false))
val result = UcvlModeSwitchTransaction(steps).execute("smart-raw", "global-raw")
assertEquals(UcvlModeSwitchResult.RollbackFailed, result)
assertEquals("safe-stop:true", steps.events.last())
}
@Test fun installationFailureAlsoRestoresPreviousMode() = runBlocking {
val steps = Steps(startResults = listOf(true), installFailure = true)
val result = UcvlModeSwitchTransaction(steps).execute("smart-raw", "global-raw")
assertEquals(UcvlModeSwitchResult.RolledBack, result)
assertEquals(
listOf("stop", "install:global-raw", "safe-stop:true", "restore:smart-raw", "start:true"),
steps.events,
)
}
@Test fun neverRestoresOverAnUnconfirmedStop() = runBlocking {
val steps = Steps(startResults = listOf(false), safeStopResult = false)
val result = UcvlModeSwitchTransaction(steps).execute("smart-raw", "global-raw")
assertEquals(UcvlModeSwitchResult.RecoveryStopFailed, result)
assertEquals(false, steps.events.any { it.startsWith("restore:") })
}
@Test fun exposesUnconfirmedFinalStopAfterRollbackRestartFails() = runBlocking {
val events = mutableListOf<String>()
var safeStops = 0
val steps = object : UcvlModeSwitchTransaction.Steps<String, String> {
override suspend fun stop() = true
override suspend fun install(candidate: String) = Unit
override suspend fun startAndVerify(): Boolean = false
override suspend fun restore(snapshot: String) = Unit
override suspend fun safeStop(): Boolean {
events += "safe-stop"
return ++safeStops == 1
}
}
val result = UcvlModeSwitchTransaction(steps).execute("smart", "global")
assertEquals(UcvlModeSwitchResult.RecoveryStopFailed, result)
assertEquals(listOf("safe-stop", "safe-stop"), events)
}
@Test fun cancellationAfterInstallPerformsNonCancellableRollback() {
val steps = object : UcvlModeSwitchTransaction.Steps<String, String> {
val events = mutableListOf<String>()
override suspend fun stop(): Boolean = true.also { events += "stop" }
override suspend fun install(candidate: String) { events += "install"; throw CancellationException() }
override suspend fun startAndVerify(): Boolean = true.also { events += "start" }
override suspend fun restore(snapshot: String) { events += "restore" }
override suspend fun safeStop(): Boolean = true.also { events += "safe-stop" }
}
org.junit.Assert.assertThrows(CancellationException::class.java) {
runBlocking { UcvlModeSwitchTransaction(steps).execute("smart", "global") }
}
assertEquals(listOf("stop", "install", "safe-stop", "restore", "start"), steps.events)
}
@Test fun cancellationDuringInitialStopStillFinishesSafeRollback() {
val steps = object : UcvlModeSwitchTransaction.Steps<String, String> {
val events = mutableListOf<String>()
override suspend fun stop(): Boolean {
events += "stop"
throw CancellationException()
}
override suspend fun install(candidate: String) { events += "install" }
override suspend fun startAndVerify(): Boolean = true.also { events += "start" }
override suspend fun restore(snapshot: String) { events += "restore" }
override suspend fun safeStop(): Boolean = true.also { events += "safe-stop" }
}
org.junit.Assert.assertThrows(CancellationException::class.java) {
runBlocking { UcvlModeSwitchTransaction(steps).execute("smart", "global") }
}
assertEquals(listOf("stop", "safe-stop", "restore", "start"), steps.events)
}
}
@@ -0,0 +1,26 @@
package com.v2ray.ang.ucvl
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class UcvlServiceStateReconcilerTest {
@Test fun confirmedStoppedStateIsImmediatelyUsable() {
assertEquals(false, UcvlServiceStateReconciler.initial(false, true))
}
@Test fun desiredOrIncompleteStopRemainsUnknown() {
assertNull(UcvlServiceStateReconciler.initial(true, false))
assertNull(UcvlServiceStateReconciler.initial(false, false))
}
@Test fun notRunningBroadcastCannotBypassStopBarrier() {
assertNull(UcvlServiceStateReconciler.afterNotRunning(false, false))
assertEquals(false, UcvlServiceStateReconciler.afterNotRunning(false, true))
}
@Test fun deadServiceAfterQueryTimeoutCanBeReconciledStopped() {
assertEquals(false, UcvlServiceStateReconciler.afterQueryTimeout(false))
assertNull(UcvlServiceStateReconciler.afterQueryTimeout(true))
}
}
@@ -0,0 +1,195 @@
package com.v2ray.ang.ucvl
import com.google.gson.JsonParser
import org.junit.Assert.assertEquals
import org.junit.Test
class UcvlSingleNodePolicyTest {
private fun response(
node: String = UcvlSingleNodePolicy.NODE_SLUG,
mode: String = "smart",
gateway: String = UcvlSingleNodePolicy.GATEWAY_IPV4,
port: Int = UcvlSingleNodePolicy.PROXY_PORT,
): UcvlConfigResponse {
val rules = if (mode == "global") {
"""[{"type":"field","ip":["geoip:private"],"outboundTag":"direct"}]"""
} else {
"""[{"type":"field","ip":["geoip:private"],"outboundTag":"direct"},{"type":"field","domain":["domain:openai.com"],"outboundTag":"proxy"},{"type":"field","network":"tcp,udp","outboundTag":"direct"}]"""
}
return UcvlConfigResponse(
configContract = 1,
gateway = UcvlGateway(host = gateway, ipv4 = gateway),
node = UcvlNode(node, "hidden", "hidden"),
routeMode = mode,
config = JsonParser.parseString(
"""{"outbounds":[{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"100.67.30.7","port":$port,"users":[{"id":"11111111-2222-3333-4444-555555555555"}]}]},"streamSettings":{"security":"reality","network":"tcp","realitySettings":{"password":"key","serverName":"example.com"}}},{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"domainStrategy":"IPIfNonMatch","rules":$rules}}"""
).asJsonObject,
)
}
@Test fun exposesOnlySmartAndGlobalModes() {
assertEquals(listOf("smart", "global"), UcvlSingleNodePolicy.modes.map { it.id })
assertEquals(listOf("AI 智能代理", "全局代理"), UcvlSingleNodePolicy.modes.map { it.name })
}
@Test fun acceptsOnlyTheFixedPublicVpn004Contract() {
UcvlSingleNodePolicy.validate(response(), "smart")
UcvlSingleNodePolicy.validate(response(mode = "global"), "global")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsOldOrAutomaticallyScheduledNode() {
UcvlSingleNodePolicy.validate(response(node = "auto"), "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsDirectOrMismatchedMode() {
UcvlSingleNodePolicy.validate(response(mode = "direct"), "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsTailscaleOrPrivateGateway() {
UcvlSingleNodePolicy.validate(response(gateway = "100.67.30.7"), "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsWrongPublicPort() {
UcvlSingleNodePolicy.validate(response(port = 11083), "smart")
}
@Test fun acceptsOnlyStampedInstalledSingleNodeConfig() {
val raw = response().config.deepCopy().also { config ->
config.getAsJsonArray("outbounds")[0].asJsonObject
.getAsJsonObject("settings").getAsJsonArray("vnext")[0].asJsonObject
.addProperty("address", UcvlSingleNodePolicy.GATEWAY_IPV4)
}.toString()
UcvlSingleNodePolicy.validateInstalled(
raw,
UcvlSingleNodePolicy.INSTALLED_CONTRACT,
"smart",
)
}
@Test(expected = IllegalArgumentException::class)
fun rejectsPre109InstalledConfigWithoutContractStamp() {
UcvlSingleNodePolicy.validateInstalled(response().config.toString(), null, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsInstalledTailscaleAddressEvenWithNewStamp() {
UcvlSingleNodePolicy.validateInstalled(
response().config.toString(),
UcvlSingleNodePolicy.INSTALLED_CONTRACT,
"smart",
)
}
@Test(expected = IllegalArgumentException::class)
fun rejectsUnsupportedInstalledMode() {
val raw = response().config.deepCopy().also { config ->
config.getAsJsonArray("outbounds")[0].asJsonObject
.getAsJsonObject("settings").getAsJsonArray("vnext")[0].asJsonObject
.addProperty("address", UcvlSingleNodePolicy.GATEWAY_IPV4)
}.toString()
UcvlSingleNodePolicy.validateInstalled(
raw,
UcvlSingleNodePolicy.INSTALLED_CONTRACT,
"direct",
)
}
@Test(expected = IllegalArgumentException::class)
fun rejectsAdditionalRemoteOutbound() {
val value = response()
value.config.getAsJsonArray("outbounds").add(JsonParser.parseString(
"""{"tag":"legacy","protocol":"vless","settings":{"vnext":[{"address":"8.216.53.107","port":10803}]}}"""
))
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsMultipleProxyEndpoints() {
val value = response()
val vnext = value.config.getAsJsonArray("outbounds")[0].asJsonObject
.getAsJsonObject("settings").getAsJsonArray("vnext")
vnext.add(vnext[0].deepCopy())
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsGlobalResponseThatActuallyRoutesAllTrafficDirect() {
val value = response(mode = "global")
value.config.getAsJsonObject("routing").getAsJsonArray("rules").add(
JsonParser.parseString("""{"type":"field","network":"tcp,udp","outboundTag":"direct"}"""),
)
UcvlSingleNodePolicy.validate(value, "global")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsSmartResponseWithoutDefaultDirectRule() {
val value = response()
value.config.getAsJsonObject("routing").add("rules", JsonParser.parseString(
"""[{"type":"field","ip":["geoip:private"],"outboundTag":"direct"}]""",
))
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsSmartResponseWithoutAnyBusinessProxyRule() {
val value = response()
value.config.getAsJsonObject("routing").add("rules", JsonParser.parseString(
"""[{"type":"field","ip":["geoip:private"],"outboundTag":"direct"},{"type":"field","network":"tcp,udp","outboundTag":"direct"}]""",
))
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsSmartResponseWithRulesAfterDefaultDirectCatchAll() {
val value = response()
val rules = value.config.getAsJsonObject("routing").getAsJsonArray("rules")
rules.add(JsonParser.parseString(
"""{"type":"field","domain":["domain:example.com"],"outboundTag":"proxy"}""",
))
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsHiddenDialerProxy() {
val value = response()
value.config.getAsJsonArray("outbounds")[0].asJsonObject
.getAsJsonObject("streamSettings").add(
"sockopt",
JsonParser.parseString("""{"dialerProxy":"legacy"}"""),
)
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsFreedomRedirect() {
val value = response()
value.config.getAsJsonArray("outbounds")[1].asJsonObject.add(
"settings",
JsonParser.parseString("""{"redirect":"8.216.53.107:10803"}"""),
)
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsBalancerRule() {
val value = response()
value.config.getAsJsonObject("routing").add(
"balancers",
JsonParser.parseString("""[{"tag":"legacy","selector":["proxy"]}]"""),
)
UcvlSingleNodePolicy.validate(value, "smart")
}
@Test(expected = IllegalArgumentException::class)
fun rejectsRuleReferencingUnknownOutbound() {
val value = response()
value.config.getAsJsonObject("routing").getAsJsonArray("rules").add(
JsonParser.parseString("""{"type":"field","network":"tcp","outboundTag":"legacy"}"""),
)
UcvlSingleNodePolicy.validate(value, "smart")
}
}
@@ -0,0 +1,10 @@
# Android 1.0.9 实施计划
1. 新增单节点策略和运行中切换事务的 JVM 失败测试。
2. 实现固定节点/公网入口/端口的严格验证,以及可回滚模式切换。
3. 精简主界面与文案,更新域名、版本和升级测试。
4. 在纯英文隔离目录运行全部 JVM 测试并构建五个 release APK。
5. 用原公司证书签名,核验包名、版本、versionCode、证书和覆盖升级。
6. 发布源码 tag 与正式 Gitea release,匿名回读全部资产。
7. 更新内部资源中心、企业动态配图,并用尚书台通知全员。
8. iOS 仅发布 1.0.5 源码候选;没有 Mac/Xcode/签名环境时不生成或宣称 IPA。
@@ -0,0 +1,36 @@
# 纵横家 Android 1.0.9 单节点设计
## 目标
Android 客户端与 Windows 0.4.0 的产品逻辑一致:只使用 VPN004,由青岛公网入口
`47.104.134.190:11084` 转发;客户端不再暴露 Tailscale、节点、地区或调度概念。
用户只选择两种代理模式:`smart`(AI 智能代理)和 `global`(全局代理)。连接后仍可切换模式。
## 安全边界
- 配置请求固定使用节点 `racknerd-newyork-004`。
- 只接受 `smart` 或 `global`,拒绝 `auto`、`direct` 和其他模式。
- 后台响应必须同时匹配固定节点、请求模式、固定公网入口和端口 11084。
- 拒绝私网、CGNAT/Tailscale、旧节点和错误端口,避免客户端被后台旧数据带回已退役链路。
- 连接成功仍以现有代理 HTTPS 出网验证为准,不能仅以进程启动为准。
## 运行中切换
切换前先取得并校验新配置,然后快照当前受管配置和模式。停止旧连接、安装新配置并重新启动;
只有现有出网验证通过才提交新模式。失败时恢复快照并重启旧模式;回滚也失败则安全停止并提示重新连接。
模式切换期间禁止重复操作,但模式选择器在稳定连接时保持可用。
## 界面
- 删除“当前工作节点”和“平台自动调度”。
- 删除近 7 天流量趋势图,保留本期/本次累计数值与本机代理速度趋势。
- 不请求、轮询或显示服务器出入口流量。
- 手机端保留滚动容器,确保小屏与软键盘下控件可达。
- 登录、注册和页脚域名统一为 `vpn.ucvl.cn`。
## 版本与发布
版本为 1.0.9,Playstore 有效 versionCode 为 4010009。正式产物包含五个 ABI APK、GPL 源码包、
元数据和 SHA256SUMS,并保持公司原签名证书连续。
+178
View File
@@ -0,0 +1,178 @@
# Local candidate only. Uses cached dependencies; never starts adb or an emulator.
param([string]$JobDirectory = '',[switch]$ResumeAfterBuild,[string]$ToolRoot = '')
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd(
[char[]]@([IO.Path]::DirectorySeparatorChar,[IO.Path]::AltDirectorySeparatorChar)
)
if ($ResumeAfterBuild -and -not $JobDirectory) { throw 'Resume requires the exact completed build directory' }
if (-not $JobDirectory) { $JobDirectory = Join-Path $tempRoot ('ucvl-android-109-' + [guid]::NewGuid().ToString('N')) }
$job = [IO.Path]::GetFullPath($JobDirectory)
if ([IO.Path]::GetDirectoryName($job) -ine $tempRoot -or [IO.Path]::GetFileName($job) -cnotmatch '^ucvl-android-109-[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' }
$buildText = Get-Content -LiteralPath (Join-Path $repo 'V2rayNG/app/build.gradle.kts') -Raw
if ($buildText -notmatch 'versionCode = 10009' -or $buildText -notmatch 'versionName = "1.0.9"') { throw 'Source version mismatch' }
$toolRootValue = if ($ToolRoot) { $ToolRoot } else { $env:UCVL_ANDROID_TOOL_ROOT }
if (-not $toolRootValue) { throw 'ToolRoot or UCVL_ANDROID_TOOL_ROOT is required' }
$toolRootPath = [IO.Path]::GetFullPath($toolRootValue)
$javaHome = Join-Path $toolRootPath '.tools/jdk-staging/jdk-21.0.12.1+1'
$androidSdk = Join-Path $toolRootPath '.tools/android-sdk'
$signingProperties = Join-Path $toolRootPath '.tools/signing/signing.properties'
$keyStore = Join-Path $toolRootPath '.tools/signing/ucvl-zonghengjia-release.jks'
foreach ($required in @($javaHome,$androidSdk,$signingProperties,$keyStore)) {
if (-not (Test-Path -LiteralPath $required)) { throw "Missing private build input: $required" }
}
$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 Get-PortableRelativePath([string]$Base,[string]$Target) {
$basePath = [IO.Path]::GetFullPath($Base).TrimEnd([char[]]@([char]'\',[char]'/')) + [IO.Path]::DirectorySeparatorChar
$baseUri = New-Object System.Uri($basePath)
$targetUri = New-Object System.Uri([IO.Path]::GetFullPath($Target))
[Uri]::UnescapeDataString($baseUri.MakeRelativeUri($targetUri).ToString()).Replace('\','/')
}
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 = [IO.File]::ReadAllText($_.FullName,[Text.Encoding]::UTF8)
[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 = $javaHome
$env:ANDROID_HOME = $androidSdk
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=(Get-PortableRelativePath $project $_.FullName);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 {
$savedErrorActionPreference = $ErrorActionPreference
try {
# Windows PowerShell 5 wraps benign native stderr (for example JVM
# warnings) as NativeCommandError. The Gradle process exit code is the
# authoritative build result and its complete output remains in evidence.
$ErrorActionPreference = 'Continue'
& ./gradlew.bat --offline --no-daemon --max-workers=2 :app:testPlaystoreReleaseUnitTest :app:assemblePlaystoreRelease :app:assemblePlaystoreReleaseAndroidTest *> (Join-Path $job 'evidence/gradle.log')
$buildExit = $LASTEXITCODE
} finally {
$ErrorActionPreference = $savedErrorActionPreference
}
} 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' })
$singleNodeSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlSingleNodePolicyTest' })
$modeSwitchSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlModeSwitchTransactionTest' })
$managedRecordSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlManagedConfigRecordTest' })
$serviceStateSuites = @($suites | Where-Object { $_.Name -ceq 'com.v2ray.ang.ucvl.UcvlServiceStateReconcilerTest' })
if ($totalUnitTests -lt 100 -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 upgrade regressions missing' }
if ($singleNodeSuites.Count -ne 1 -or $singleNodeSuites[0].Tests -lt 20 -or $modeSwitchSuites.Count -ne 1 -or $modeSwitchSuites[0].Tests -lt 9 -or $managedRecordSuites.Count -ne 1 -or $managedRecordSuites[0].Tests -ne 4 -or $serviceStateSuites.Count -ne 1 -or $serviceStateSuites[0].Tests -ne 4) {
throw 'Required single-node or live mode-switch 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)"
}
}
$java = Join-Path $env:JAVA_HOME 'bin/java.exe'
$signer = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/lib/apksigner.jar'
$signerBat = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/apksigner.bat'
$zipAlign = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/zipalign.exe'
$aapt = Join-Path $env:ANDROID_HOME 'build-tools/37.0.0/aapt.exe'
$expectedCertificate = '0f1a09870d6ee1e73b62138f99463e7066f4228ce28b7f16ff0aeccca59ea14f'
$previousPackage = Join-Path $toolRootPath 'releases/UCVL-Zonghengjia-1.0.8-android-universal.apk'
$oldVerification = (& $java -jar $signer verify --verbose --print-certs $previousPackage 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0 -or $oldVerification -notmatch $expectedCertificate) { throw 'Old 1.0.8 signing identity differs' }
$signing = @{}
Get-Content -LiteralPath $signingProperties | ForEach-Object {
$parts = $_ -split '=',2
if ($parts.Length -eq 2) { $signing[$parts[0].Trim()] = $parts[1].Trim() }
}
$env:UCVL_ANDROID_STORE_PASS = $signing['storePassword']
$env:UCVL_ANDROID_KEY_PASS = $signing['keyPassword']
try {
foreach ($unsigned in Get-ChildItem -LiteralPath (Join-Path $project 'app/build/outputs/apk/playstore/release') -Filter 'UCVL-Zonghengjia-1.0.9-android-*.apk' -File) {
$aligned = Join-Path $job ('.aligned-' + $unsigned.Name)
$signed = Join-Path $job ('artifacts/' + $unsigned.Name)
& $zipAlign -f -p 4 $unsigned.FullName $aligned
if ($LASTEXITCODE -ne 0) { throw "APK alignment failed: $($unsigned.Name)" }
& $signerBat sign --ks $keyStore --ks-key-alias $signing['keyAlias'] --ks-pass env:UCVL_ANDROID_STORE_PASS --key-pass env:UCVL_ANDROID_KEY_PASS --out $signed $aligned
if ($LASTEXITCODE -ne 0) { throw "APK signing failed: $($unsigned.Name)" }
Remove-Item -LiteralPath $aligned -Force
}
$unsignedTest = Get-ChildItem -LiteralPath (Join-Path $project 'app/build/outputs/apk/androidTest/playstore/release') -Filter '*androidTest*.apk' -File
if (@($unsignedTest).Count -ne 1) { throw 'Expected exactly one Android instrumentation APK' }
$alignedTest = Join-Path $job '.aligned-app-playstore-release-androidTest-1.0.9.apk'
$signedTest = Join-Path $job 'artifacts/app-playstore-release-androidTest-1.0.9.apk'
& $zipAlign -f -p 4 $unsignedTest.FullName $alignedTest
if ($LASTEXITCODE -ne 0) { throw 'Android instrumentation APK alignment failed' }
& $signerBat sign --ks $keyStore --ks-key-alias $signing['keyAlias'] --ks-pass env:UCVL_ANDROID_STORE_PASS --key-pass env:UCVL_ANDROID_KEY_PASS --out $signedTest $alignedTest
if ($LASTEXITCODE -ne 0) { throw 'Android instrumentation APK signing failed' }
Remove-Item -LiteralPath $alignedTest -Force
} finally {
Remove-Item Env:UCVL_ANDROID_STORE_PASS,Env:UCVL_ANDROID_KEY_PASS -ErrorAction SilentlyContinue
$signing.Clear()
}
$packages = @(foreach ($file in Get-ChildItem -LiteralPath (Join-Path $job 'artifacts') -Filter 'UCVL-Zonghengjia-1.0.9-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)" }
$badging = (& $aapt dump badging $file.FullName 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0 -or $badging -notmatch "package: name='cn.toplc.zonghengjia' versionCode='4010009' versionName='1.0.9'") { throw "Candidate manifest mismatch: $($file.Name)" }
[ordered]@{Name=$file.Name;Bytes=$file.Length;Sha256=(Get-FileHash -LiteralPath $file.FullName).Hash;Version='1.0.9';VersionCode=4010009;SignerSha256=$expectedCertificate;V2=$true;V3=$true}
})
if ($packages.Count -ne 5) { throw 'Expected all five ABI/universal packages' }
$testApk = Get-Item -LiteralPath (Join-Path $job 'artifacts/app-playstore-release-androidTest-1.0.9.apk')
$testVerification = (& $java -jar $signer verify --verbose --print-certs $testApk.FullName 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0 -or $testVerification -notmatch $expectedCertificate) { throw 'Android instrumentation APK signature mismatch' }
Save-Json 'candidate.json' ([ordered]@{Version='1.0.9';VersionCode=4010009;BaseVersionCode=10009;JobDirectory=$job;BuiltAt=[DateTimeOffset]::Now.ToString('O');Packages=$packages;AndroidTest=[ordered]@{Name=$testApk.Name;Bytes=$testApk.Length;Sha256=(Get-FileHash -LiteralPath $testApk.FullName).Hash;SignerSha256=$expectedCertificate};BuildInputsSha256=$inputsHash;UnitTests=$totalUnitTests;AuthorizationLifecycleJvmTests=$authorizationUnitTests;StartupLeaseJvmTests=$startupLeaseUnitTests;SingleNodeJvmTests=[int]$singleNodeSuites[0].Tests;ModeSwitchJvmTests=[int]$modeSwitchSuites[0].Tests;ManagedConfigRecordJvmTests=[int]$managedRecordSuites[0].Tests;ServiceStateJvmTests=[int]$serviceStateSuites[0].Tests;SameSignerAs=@('1.0.8');PhysicalDeviceTested=$false;AndroidServiceBroadcastTested=$false;StableReleaseAccepted=$false;Published=$false})
Write-Output "CANDIDATE_JOB=$job"
Write-Output 'CANDIDATE_BUILD_SIGN_VERIFY_PASSED'
+47 -26
View File
@@ -4,60 +4,81 @@ Seeds only a synthetic non-authenticating session. Does not alter host networkin
or request a production account. Run after building/signing the test APK. or request a production account. Run after building/signing the test APK.
""" """
import datetime import datetime
import argparse
import hashlib import hashlib
import json import json
import os
from pathlib import Path from pathlib import Path
import subprocess import subprocess
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
ADB = ROOT / ".tools/android-sdk/platform-tools/adb.exe"
PACKAGE = "cn.toplc.zonghengjia" PACKAGE = "cn.toplc.zonghengjia"
SERIAL = "emulator-5554"
def adb(*args, timeout=60): def adb(adb_path, serial, *args, timeout=60):
return subprocess.run([str(ADB), "-s", SERIAL, *map(str, args)], capture_output=True, return subprocess.run([str(adb_path), "-s", serial, *map(str, args)], capture_output=True,
text=True, encoding="utf-8", errors="replace", timeout=timeout, text=True, encoding="utf-8", errors="replace", timeout=timeout,
check=True, creationflags=subprocess.CREATE_NO_WINDOW).stdout check=True, creationflags=subprocess.CREATE_NO_WINDOW).stdout
def instrument(method): def instrument(adb_path, serial, method, old_version, new_version, new_version_code):
result = adb("shell", "am", "instrument", "-w", "-r", "-e", "oldVersion", "1.0.2", result = adb(adb_path, serial, "shell", "am", "instrument", "-w", "-r",
"-e", "newVersion", "1.0.3", "-e", "class", "-e", "oldVersion", old_version,
"-e", "newVersion", new_version,
"-e", "newVersionCode", str(new_version_code), "-e", "class",
"com.v2ray.ang.ucvl.UpgradeSmokeTest#" + method, "com.v2ray.ang.ucvl.UpgradeSmokeTest#" + method,
PACKAGE + ".test/androidx.test.runner.AndroidJUnitRunner", timeout=90) PACKAGE + ".test/androidx.test.runner.AndroidJUnitRunner", timeout=90)
if "OK (1 test)" not in result: if "OK (1 test)" not in result:
raise RuntimeError("Instrumentation failed: " + result[-3000:]) raise RuntimeError("Instrumentation failed: " + result[-3000:])
def parse_args():
tool_root = Path(os.environ.get("UCVL_ANDROID_TOOL_ROOT", ROOT))
parser = argparse.ArgumentParser(description="Verify the 1.0.8 to 1.0.9 signed cover upgrade on the dedicated emulator")
parser.add_argument("--adb", type=Path, default=tool_root / ".tools/android-sdk/platform-tools/adb.exe")
parser.add_argument("--serial", default="emulator-5554")
parser.add_argument("--old-version", default="1.0.8")
parser.add_argument("--new-version", default="1.0.9")
parser.add_argument("--new-version-code", type=int, default=4_010_009)
parser.add_argument("--old-apk", type=Path, default=ROOT / "releases/UCVL-Zonghengjia-1.0.8-android-universal.apk")
parser.add_argument("--new-apk", type=Path, default=ROOT / "releases/UCVL-Zonghengjia-1.0.9-android-universal.apk")
parser.add_argument("--test-apk", type=Path, default=ROOT / "releases/app-playstore-release-androidTest-1.0.9.apk")
parser.add_argument("--evidence", type=Path, default=ROOT / "acceptance/upgrade-1.0.9.json")
return parser.parse_args()
def main(): def main():
assert adb("shell", "getprop", "ro.kernel.qemu").strip() == "1", "Dedicated emulator only" args = parse_args()
assert "ucvl_acceptance" in adb("emu", "avd", "name"), "Unexpected emulator image" assert args.adb.is_file(), f"adb not found: {args.adb}"
assert adb("shell", "getprop", "sys.boot_completed").strip() == "1", "Emulator has not booted" assert adb(args.adb, args.serial, "shell", "getprop", "ro.kernel.qemu").strip() == "1", "Dedicated emulator only"
old = ROOT / "releases/UCVL-Zonghengjia-1.0.2-android-universal.apk" assert "ucvl_acceptance" in adb(args.adb, args.serial, "emu", "avd", "name"), "Unexpected emulator image"
new = ROOT / "releases/UCVL-Zonghengjia-1.0.3-android-universal.apk" assert adb(args.adb, args.serial, "shell", "getprop", "sys.boot_completed").strip() == "1", "Emulator has not booted"
test = ROOT / "releases/app-playstore-release-androidTest-1.0.3.apk" old, new, test = args.old_apk.resolve(), args.new_apk.resolve(), args.test_apk.resolve()
assert all(path.is_file() for path in [old, new, test]) assert all(path.is_file() for path in [old, new, test])
evidence = ROOT / "acceptance/upgrade-1.0.3.json" evidence = args.evidence.resolve()
report = {"timestamp": datetime.datetime.now().astimezone().isoformat(), "serial": SERIAL, evidence.parent.mkdir(parents=True, exist_ok=True)
"old_version": "1.0.2", "new_version": "1.0.3", "passed": False, report = {"timestamp": datetime.datetime.now().astimezone().isoformat(), "serial": args.serial,
"old_version": args.old_version, "new_version": args.new_version,
"new_version_code": args.new_version_code, "passed": False,
"physical_device_tested": False, "host_network_modified": False, "physical_device_tested": False, "host_network_modified": False,
"authenticated_vpn_connection_tested": False, "steps": []} "authenticated_vpn_connection_tested": False, "steps": []}
try: try:
adb("shell", "am", "force-stop", PACKAGE) adb(args.adb, args.serial, "shell", "am", "force-stop", PACKAGE)
assert "Success" in adb("install", "-r", old) assert "Success" in adb(args.adb, args.serial, "install", "-r", old)
assert "Success" in adb("install", "-r", test) assert "Success" in adb(args.adb, args.serial, "install", "-r", test)
instrument("seedUpgrade") instrument(args.adb, args.serial, "seedUpgrade", args.old_version, args.new_version, args.new_version_code)
report["steps"].append("seed_synthetic_session_on_1.0.2") report["steps"].append(f"seed_synthetic_session_and_legacy_managed_config_on_{args.old_version}")
assert "Success" in adb("install", "-r", new) assert "Success" in adb(args.adb, args.serial, "install", "-r", new)
instrument("verifyUpgrade") instrument(args.adb, args.serial, "verifyUpgrade", args.old_version, args.new_version, args.new_version_code)
report["steps"].append("cover_upgrade_preserves_encrypted_session_login_and_device_id") report["steps"].append("cover_upgrade_preserves_encrypted_session_and_rejects_legacy_managed_config")
instrument("loginVisibleAndEmptyFormIsSafe") instrument(args.adb, args.serial, "legacyManagedConfigCannotStartFromToggle", args.old_version, args.new_version, args.new_version_code)
report["steps"].append("legacy_managed_config_rejected_by_real_toggle_entry_point")
instrument(args.adb, args.serial, "loginVisibleAndEmptyFormIsSafe", args.old_version, args.new_version, args.new_version_code)
report["steps"].append("login_visible_empty_submission_safe_fixture_cleared") report["steps"].append("login_visible_empty_submission_safe_fixture_cleared")
report["apk_sha256"] = hashlib.sha256(new.read_bytes()).hexdigest() report["apk_sha256"] = hashlib.sha256(new.read_bytes()).hexdigest()
report["passed"] = True report["passed"] = True
finally: finally:
adb("shell", "am", "force-stop", PACKAGE) adb(args.adb, args.serial, "shell", "am", "force-stop", PACKAGE)
evidence.write_text(json.dumps(report, indent=2), encoding="utf-8") evidence.write_text(json.dumps(report, indent=2), encoding="utf-8")
print(json.dumps(report)) print(json.dumps(report))