Выпуск WDTT Plus v12

This commit is contained in:
Ivan4537 committed 2026-07-29 15:26:22 +03:00
1 parent b3aad32990
commit cd441e604e
108 files changed
+22337 -2201

No files matched your search

@@ -0,0 +1,216 @@
package com.wdtt.plus
enum class AccessLifecycleSeverity {
NORMAL,
WARNING,
ERROR;
companion object {
fun parse(value: String, allowConnect: Boolean): AccessLifecycleSeverity =
when (value.trim().lowercase()) {
"normal", "info" -> NORMAL
"warning", "warn" -> WARNING
"error", "danger" -> ERROR
else -> if (allowConnect) NORMAL else ERROR
}
}
}
/**
* Opaque provider-neutral capability attached to a remotely managed profile.
*
* Android does not interpret the provider policy behind this capability. It
* submits the protected key to the exact HTTPS service URL, then applies only
* the generic connection decision and optional document/action returned by it.
*/
data class RemoteAccessCapability(
val available: Boolean,
val key: String = "",
val url: String = "",
val binding: String = "",
val initialStatus: AccessLifecycleStatus? = null,
val cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable,
val exchange: RemoteProfileExchange = RemoteProfileExchange.Unavailable,
) {
companion object {
val Unavailable = RemoteAccessCapability(available = false)
}
}
/**
* Provider-neutral exchange attached to one remotely managed profile.
*
* Tokens are opaque and device-bound. Android can submit the profile's normal
* auxiliary values or invoke the remotely presented action, but it does not
* know why the provider stores them or how the returned update is produced.
*/
data class RemoteProfileExchange(
val submitAvailable: Boolean,
val submitToken: String = "",
val actionAvailable: Boolean = false,
val actionToken: String = "",
val label: String = "",
val message: String = "",
) {
companion object {
val Unavailable = RemoteProfileExchange(submitAvailable = false)
}
}
/**
* A provider-neutral action cached with a remotely managed profile.
*
* Android treats [payload] as an opaque clipboard value and opens [target]
* exactly as supplied. Presentation is also remote-provided, so the APK does
* not know which external channel fulfills the action.
*/
data class CachedRemoteAction(
val available: Boolean,
val payload: String = "",
val target: RemoteLaunchTarget = RemoteLaunchTarget(primaryUrl = ""),
val title: String = "",
val message: String = "",
val label: String = "",
val clipboardLabel: String = "",
val copiedMessage: String = "",
val failedMessage: String = "",
val helpTitle: String = "",
val helpIntro: String = "",
val helpSteps: String = "",
) {
companion object {
val Unavailable = CachedRemoteAction(available = false)
}
}
data class AccessProfileUpdate(
val revision: Long,
val link: RemoteDocumentLink,
)
data class AccessLifecycleStatus(
val allowConnect: Boolean,
val actionAvailable: Boolean,
val actionLabel: String = "",
val actionMessage: String = "",
val title: String = "",
val message: String = "",
val detailLabel: String = "",
val detailValue: String = "",
val actionIcon: String = "",
val severity: AccessLifecycleSeverity = AccessLifecycleSeverity.NORMAL,
val checkedAtMillis: Long = System.currentTimeMillis(),
val profileRevision: Long = 0,
val profileUpdate: AccessProfileUpdate? = null,
val cachedAction: CachedRemoteAction = CachedRemoteAction.Unavailable,
val exchange: RemoteProfileExchange? = null,
)
data class StoredAccessLifecycle(
val managed: Boolean,
val capability: RemoteAccessCapability,
val status: AccessLifecycleStatus?,
val appliedProfileRevision: Long,
val lastAttemptAtMillis: Long,
)
data class AccessLifecycleUiState(
val managed: Boolean,
val allowConnect: Boolean,
val actionAvailable: Boolean,
val actionLabel: String,
val actionMessage: String,
val title: String,
val message: String,
val detailLabel: String = "",
val detailValue: String = "",
val actionIcon: String = "",
val severity: AccessLifecycleSeverity,
val checkedAtMillis: Long,
) {
companion object {
val Unmanaged = AccessLifecycleUiState(
managed = false,
allowConnect = true,
actionAvailable = false,
actionLabel = "",
actionMessage = "",
title = "",
message = "",
detailLabel = "",
detailValue = "",
actionIcon = "",
severity = AccessLifecycleSeverity.NORMAL,
checkedAtMillis = 0,
)
}
}
internal fun accessLifecycleDismissalSignature(
lifecycle: AccessLifecycleUiState,
): String {
if (!lifecycle.managed) return ""
return listOf(
lifecycle.allowConnect,
lifecycle.actionAvailable,
lifecycle.title,
lifecycle.message,
lifecycle.detailLabel,
lifecycle.detailValue,
).joinToString("|")
}
internal fun StoredAccessLifecycle.toUiState(): AccessLifecycleUiState {
val current = status
return AccessLifecycleUiState(
managed = managed,
allowConnect = current?.allowConnect ?: true,
actionAvailable = current?.actionAvailable == true,
actionLabel = current?.actionLabel.orEmpty(),
actionMessage = current?.actionMessage.orEmpty(),
title = current?.title.orEmpty(),
message = current?.message.orEmpty(),
detailLabel = current?.detailLabel.orEmpty(),
detailValue = current?.detailValue.orEmpty(),
actionIcon = current?.actionIcon.orEmpty(),
severity = current?.severity ?: AccessLifecycleSeverity.NORMAL,
checkedAtMillis = current?.checkedAtMillis ?: 0,
)
}
internal sealed interface AccessStartDecision {
data object Allowed : AccessStartDecision
data class Denied(val status: AccessLifecycleStatus) : AccessStartDecision
}
internal fun accessStartDecision(
lifecycle: StoredAccessLifecycle,
): AccessStartDecision {
val status = lifecycle.status
val pendingProfileUpdate = status?.profileUpdate
?.revision
?.let { it > lifecycle.appliedProfileRevision } == true
return if (
!lifecycle.capability.available ||
status == null ||
(status.allowConnect && !pendingProfileUpdate)
) {
AccessStartDecision.Allowed
} else {
AccessStartDecision.Denied(
if (pendingProfileUpdate) {
status.copy(
allowConnect = false,
title = "Нужно обновить профиль",
message = "Не удалось применить новые параметры. Повторите подключение.",
severity = AccessLifecycleSeverity.WARNING,
)
} else {
status
}
)
}
}
internal fun AccessLifecycleUiState.fallbackTitle(): String =
if (allowConnect) "Профиль доступен" else "Профиль временно недоступен"
@@ -0,0 +1,567 @@
package com.wdtt.plus
import android.content.Context
import android.os.Build
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.TimeZone
sealed interface AccessLifecycleRefreshResult {
data object Unmanaged : AccessLifecycleRefreshResult
data class Success(val status: AccessLifecycleStatus) : AccessLifecycleRefreshResult
data class Cached(val status: AccessLifecycleStatus?) : AccessLifecycleRefreshResult
data class Throttled(
val status: AccessLifecycleStatus?,
val retryAfterMillis: Long,
) : AccessLifecycleRefreshResult
data class Failed(val message: String, val cached: AccessLifecycleStatus?) :
AccessLifecycleRefreshResult
}
object AccessLifecycleCoordinator {
private const val STATUS_CACHE_TTL_MS = 10 * 60 * 1000L
private const val MIN_ATTEMPT_INTERVAL_MS = 10_000L
private val profileLocks = Array(3) { Mutex() }
private val _refreshingProfiles = MutableStateFlow<Set<Int>>(emptySet())
val refreshingProfiles: StateFlow<Set<Int>> = _refreshingProfiles.asStateFlow()
private val pendingExternalRefresh = mutableSetOf<Int>()
suspend fun refreshProfile(
context: Context,
profileIndex: Int,
force: Boolean = false,
): AccessLifecycleRefreshResult {
val appContext = context.applicationContext
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(appContext)
val before = store.accessLifecycleForProfile(profile)
if (!before.capability.available) return AccessLifecycleRefreshResult.Unmanaged
val now = System.currentTimeMillis()
if (
!force &&
before.status != null &&
now - before.status.checkedAtMillis in 0 until STATUS_CACHE_TTL_MS
) {
return AccessLifecycleRefreshResult.Cached(before.status)
}
val attemptAge = now - before.lastAttemptAtMillis
if (attemptAge in 0 until MIN_ATTEMPT_INTERVAL_MS) {
return AccessLifecycleRefreshResult.Throttled(
status = before.status,
retryAfterMillis = MIN_ATTEMPT_INTERVAL_MS - attemptAge,
)
}
return profileLocks[profile].withLock {
val current = store.accessLifecycleForProfile(profile)
val currentNow = System.currentTimeMillis()
if (!current.capability.available) return@withLock AccessLifecycleRefreshResult.Unmanaged
syncPendingProfileValues(store, profile, current.capability)
if (
!force &&
current.status != null &&
currentNow - current.status.checkedAtMillis in 0 until STATUS_CACHE_TTL_MS
) {
return@withLock AccessLifecycleRefreshResult.Cached(current.status)
}
val currentAttemptAge = currentNow - current.lastAttemptAtMillis
if (currentAttemptAge in 0 until MIN_ATTEMPT_INTERVAL_MS) {
return@withLock AccessLifecycleRefreshResult.Throttled(
status = current.status,
retryAfterMillis = MIN_ATTEMPT_INTERVAL_MS - currentAttemptAge,
)
}
store.saveAccessLifecycleAttempt(profile, currentNow)
setRefreshing(profile, true)
try {
val received = AccessLifecycleGateway.fetch(
capability = current.capability,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
profileRevision = current.appliedProfileRevision,
)
val effectiveCapability = current.capability.copy(
exchange = received.exchange ?: current.capability.exchange,
)
if (effectiveCapability != current.capability) {
store.saveRemoteAccessCapability(effectiveCapability, profile)
}
val effectiveCurrent = current.copy(capability = effectiveCapability)
// Статус доступа самодостаточен: сохраняем его даже если отдельное
// обновление параметров профиля временно не удалось скачать или применить.
if (
!store.saveAccessLifecycleStatus(
profile,
received,
expectedCapability = effectiveCapability,
)
) {
return@withLock AccessLifecycleRefreshResult.Unmanaged
}
val profileUpdated = applyProfileUpdateIfNeeded(
appContext = appContext,
store = store,
profile = profile,
current = effectiveCurrent,
status = received,
)
// Новая capability может очистить прежний статус при ротации ключа.
if (profileUpdated) {
store.saveAccessLifecycleStatus(
profile,
received,
expectedCapability = effectiveCapability,
)
}
// Состояние управляемого доступа показывается своей профильной карточкой.
// Общая ошибка подключения не должна дублировать её и переноситься на
// другой, в том числе ручной, профиль.
TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS)
if (
current.status?.allowConnect != received.allowConnect ||
current.status?.title != received.title
) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_decision",
message = received.title.ifBlank { "Состояние профиля обновлено" },
warning = received.severity != AccessLifecycleSeverity.NORMAL,
)
}
updateExternalSurfaces(appContext)
AccessLifecycleRefreshResult.Success(received)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: AccessLifecycleRequestException) {
if (!error.kind.authoritative) {
return@withLock accessRefreshFailure(profile, current, error)
}
val denied = authoritativeAccessDenialStatus(
failure = error,
cached = current.status,
)
if (
!store.saveAccessLifecycleStatus(
profile,
denied,
expectedCapability = current.capability,
)
) {
return@withLock AccessLifecycleRefreshResult.Unmanaged
}
TunnelManager.clearConnectionIssue(ConnectionIssueKind.ACCESS)
if (
current.status?.allowConnect != denied.allowConnect ||
current.status?.title != denied.title
) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_${error.code}",
message = denied.title,
warning = true,
)
}
updateExternalSurfaces(appContext)
AccessLifecycleRefreshResult.Success(denied)
} catch (error: Exception) {
accessRefreshFailure(profile, current, error)
} finally {
setRefreshing(profile, false)
}
}
}
private fun accessRefreshFailure(
profile: Int,
current: StoredAccessLifecycle,
error: Exception,
): AccessLifecycleRefreshResult.Failed {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_check_failed",
message = error.message ?: "Не удалось обновить сведения о доступе",
warning = true,
)
return AccessLifecycleRefreshResult.Failed(
message = error.message ?: "Не удалось проверить профиль.",
cached = current.status,
)
}
internal suspend fun prepareStart(
context: Context,
profileIndex: Int,
): AccessStartDecision {
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(context.applicationContext)
val current = store.accessLifecycleForProfile(profile)
if (!current.capability.available) return AccessStartDecision.Allowed
val now = System.currentTimeMillis()
val cachedDecision = accessStartDecision(current)
val fresh = current.status?.checkedAtMillis?.let {
now - it in 0 until STATUS_CACHE_TTL_MS
} == true
if (fresh && cachedDecision == AccessStartDecision.Allowed) {
return AccessStartDecision.Allowed
}
return when (val refreshed = refreshProfile(context, profile, force = true)) {
is AccessLifecycleRefreshResult.Success ->
if (refreshed.status.allowConnect) {
AccessStartDecision.Allowed
} else {
AccessStartDecision.Denied(refreshed.status)
}
is AccessLifecycleRefreshResult.Cached -> {
accessStartDecision(store.accessLifecycleForProfile(profile))
}
is AccessLifecycleRefreshResult.Throttled -> {
accessStartDecision(store.accessLifecycleForProfile(profile))
}
is AccessLifecycleRefreshResult.Failed ->
accessStartDecision(store.accessLifecycleForProfile(profile))
AccessLifecycleRefreshResult.Unmanaged -> AccessStartDecision.Allowed
}
}
suspend fun beginAction(
context: Context,
profileIndex: Int,
): RemoteLaunchTarget {
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(context.applicationContext)
val current = store.accessLifecycleForProfile(profile)
require(current.capability.available && current.status?.actionAvailable == true) {
current.status?.actionMessage?.ifBlank {
"Действие сейчас недоступно."
} ?: "Действие сейчас недоступно."
}
val target = AccessLifecycleGateway.begin(
capability = current.capability,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
profileRevision = current.appliedProfileRevision,
)
store.markAccessLifecycleActionLaunched(profile)
synchronized(pendingExternalRefresh) {
pendingExternalRefresh += profile
}
return target
}
suspend fun noteServerDenied(context: Context, profileIndex: Int) {
val appContext = context.applicationContext
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(appContext)
store.markAccessLifecycleDenied(profile)
updateExternalSurfaces(appContext)
refreshProfile(appContext, profile, force = true)
}
suspend fun refreshAllIfStale(context: Context) {
val store = SettingsStore(context.applicationContext)
store.accessLifecycleProfiles().forEach { profile ->
refreshProfile(context, profile, force = false)
}
}
suspend fun refreshAllOnForeground(
context: Context,
alreadyScheduledProfiles: Set<Int> = emptySet(),
) {
val store = SettingsStore(context.applicationContext)
accessProfilesForForegroundRefresh(
managedProfiles = store.accessLifecycleProfiles(),
alreadyScheduledProfiles = alreadyScheduledProfiles,
).forEach { profile ->
refreshAfterAttemptWindow(context, profile)
}
}
suspend fun refreshAfterSuccessfulConnect(context: Context, profileIndex: Int) {
refreshAfterAttemptWindow(context, profileIndex)
}
suspend fun refreshAfterExternalAction(
context: Context,
profileIndex: Int,
): AccessLifecycleRefreshResult =
refreshAfterAttemptWindow(context, profileIndex)
private suspend fun refreshAfterAttemptWindow(
context: Context,
profileIndex: Int,
): AccessLifecycleRefreshResult {
val first = refreshProfile(
context.applicationContext,
profileIndex,
force = true,
)
if (first !is AccessLifecycleRefreshResult.Throttled) return first
delay(first.retryAfterMillis)
return refreshProfile(
context.applicationContext,
profileIndex,
force = true,
)
}
fun takePendingExternalRefreshProfiles(): Set<Int> = synchronized(pendingExternalRefresh) {
pendingExternalRefresh.toSet().also { pendingExternalRefresh.clear() }
}
suspend fun syncProfileValues(
context: Context,
profileIndex: Int,
values: List<String>,
): Boolean {
val profile = profileIndex.coerceIn(0, 2)
val cleaned = values
.map(VkJoinLink::extractHash)
.filter(VkJoinLink::isValidHash)
.distinct()
.take(4)
val store = SettingsStore(context.applicationContext)
val current = store.accessLifecycleForProfile(profile)
val exchange = current.capability.exchange
if (
!current.capability.available ||
!exchange.submitAvailable ||
exchange.submitToken.isBlank()
) {
return false
}
store.markProfileValuesSyncPending(profile)
val updatedExchange = AccessLifecycleGateway.submitProfileValues(
capability = current.capability,
token = exchange.submitToken,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
values = cleaned,
)
store.saveRemoteAccessCapability(
current.capability.copy(exchange = updatedExchange),
profile,
)
store.clearProfileValuesSyncPending(profile)
return true
}
suspend fun restoreProfileValues(
context: Context,
profileIndex: Int,
expectedCapability: RemoteAccessCapability,
): WdttDeepLinkApplyResult {
val appContext = context.applicationContext
val profile = profileIndex.coerceIn(0, 2)
val store = SettingsStore(appContext)
return profileLocks[profile].withLock {
val current = store.accessLifecycleForProfile(profile)
require(
current.capability.available &&
expectedCapability.available &&
current.capability.key == expectedCapability.key &&
current.capability.url == expectedCapability.url &&
current.capability.binding == expectedCapability.binding
) {
"Сохранённые данные относятся к другому профилю."
}
val exchange = current.capability.exchange
require(
exchange.actionAvailable && exchange.actionToken.isNotBlank()
) {
"Действие для этого профиля больше недоступно."
}
val link = AccessLifecycleGateway.invokeProfileAction(
capability = current.capability,
token = exchange.actionToken,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
profileRevision = current.appliedProfileRevision,
)
val delivery = RemoteDocumentGateway.receive(
link = link,
device = store.getOrCreateConnectDeviceId(),
label = androidDeviceLabel(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
localBindings = store.remoteDocumentBindings(),
)
require(delivery.kind == RemoteDocumentKind.UPDATE) {
"WDTT Plus вернул неподходящее обновление профиля."
}
require(
current.capability.binding.isNotBlank() &&
delivery.binding == current.capability.binding
) {
"Обновление относится к другому профилю."
}
val applied = store.applyRemoteDocumentDelivery(
plan = WdttDeepLinkApplyPlan(
link = delivery.document,
targetProfile = profile,
requiresConfirmation = false,
storeAsLink = false,
),
delivery = delivery,
isBoundUpdate = true,
) ?: throw IllegalStateException("Не удалось применить обновление профиля.")
store.clearProfileValuesSyncPending(profile)
requestTunnelProfileRuntimeUpdate(profile)
applied
}
}
private suspend fun syncPendingProfileValues(
store: SettingsStore,
profile: Int,
capability: RemoteAccessCapability,
) {
if (!store.profileValuesSyncPending(profile)) return
val exchange = capability.exchange
if (!exchange.submitAvailable || exchange.submitToken.isBlank()) return
val values = store.tunnelProfileSnapshot(profile).vkHashes
.split(",")
.map(VkJoinLink::extractHash)
.filter(VkJoinLink::isValidHash)
.distinct()
.take(4)
runCatching {
val updatedExchange = AccessLifecycleGateway.submitProfileValues(
capability = capability,
token = exchange.submitToken,
device = store.getOrCreateConnectDeviceId(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
timezone = TimeZone.getDefault().id,
values = values,
)
store.saveRemoteAccessCapability(
capability.copy(exchange = updatedExchange),
profile,
)
}.onSuccess {
store.clearProfileValuesSyncPending(profile)
}
}
private suspend fun applyProfileUpdateIfNeeded(
appContext: Context,
store: SettingsStore,
profile: Int,
current: StoredAccessLifecycle,
status: AccessLifecycleStatus,
): Boolean {
val update = status.profileUpdate ?: return false
if (update.revision <= current.appliedProfileRevision) return false
val delivery = RemoteDocumentGateway.receive(
link = update.link,
device = store.getOrCreateConnectDeviceId(),
label = androidDeviceLabel(),
client = BuildConfig.VERSION_NAME,
system = Build.VERSION.RELEASE.orEmpty(),
localBindings = store.remoteDocumentBindings(),
)
require(delivery.kind == RemoteDocumentKind.UPDATE) {
"WDTT Plus вернул неподходящее обновление профиля."
}
val binding = store.remoteAccessBindingForProfile(profile)
require(binding.isNotBlank() && delivery.binding == binding) {
"Обновление относится к другому профилю."
}
val applied = store.applyWdttDeepLink(
plan = WdttDeepLinkApplyPlan(
link = delivery.document,
targetProfile = profile,
requiresConfirmation = false,
storeAsLink = false,
),
resetRemoteContinuation = false,
profileMaxWorkers = delivery.profileMaxWorkers,
remoteManaged = null,
preserveVkHashes = true,
)
require(applied != null) { "Не удалось применить обновление профиля." }
if (delivery.access.available) {
store.saveRemoteAccessCapability(delivery.access, profile)
}
store.saveAppliedAccessProfileRevision(profile, update.revision)
requestTunnelProfileRuntimeUpdate(profile)
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profile}_updated",
message = "Параметры профиля обновлены",
warning = false,
)
return true
}
private fun androidDeviceLabel(): String {
val values = listOf(Build.MANUFACTURER, Build.MODEL)
.map(String::trim)
.filter(String::isNotBlank)
.distinctBy(String::lowercase)
return values.joinToString(" ").ifBlank { "Android-устройство" }
}
private fun setRefreshing(profile: Int, refreshing: Boolean) {
_refreshingProfiles.value = _refreshingProfiles.value.toMutableSet().apply {
if (refreshing) add(profile) else remove(profile)
}
}
private fun updateExternalSurfaces(context: Context) {
VpnWidgetProvider.updateAllWidgets(context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
android.service.quicksettings.TileService.requestListeningState(
context,
android.content.ComponentName(context, QuickToggleTileService::class.java),
)
}
}
}
internal fun accessProfilesForForegroundRefresh(
managedProfiles: Collection<Int>,
alreadyScheduledProfiles: Set<Int>,
): List<Int> = managedProfiles
.filter { it in 0..2 && it !in alreadyScheduledProfiles }
.distinct()
.sorted()
internal fun authoritativeAccessDenialStatus(
failure: AccessLifecycleRequestException,
cached: AccessLifecycleStatus?,
checkedAtMillis: Long = System.currentTimeMillis(),
): AccessLifecycleStatus {
require(failure.kind.authoritative)
val (title, fallbackMessage) = when (failure.kind) {
AccessLifecycleFailureKind.REJECTED ->
"Профиль недоступен" to
"Поставщик отклонил использование этого профиля."
AccessLifecycleFailureKind.UNBOUND ->
"Профиль отвязан" to
"Запросите новую ссылку на профиль у поставщика."
AccessLifecycleFailureKind.UNAVAILABLE ->
"Профиль больше недоступен" to
"Проверьте профиль и привязку устройства у поставщика."
AccessLifecycleFailureKind.TEMPORARY -> error("temporary failure is not authoritative")
}
return AccessLifecycleStatus(
allowConnect = false,
actionAvailable = false,
title = title,
message = failure.message?.takeIf { it.isNotBlank() } ?: fallbackMessage,
severity = AccessLifecycleSeverity.ERROR,
checkedAtMillis = checkedAtMillis,
profileRevision = cached?.profileRevision ?: 0,
)
}
@@ -0,0 +1,384 @@
package com.wdtt.plus
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
enum class AccessLifecycleFailureKind {
REJECTED,
UNBOUND,
UNAVAILABLE,
TEMPORARY;
val authoritative: Boolean
get() = this != TEMPORARY
}
class AccessLifecycleRequestException(
val kind: AccessLifecycleFailureKind,
val code: String,
message: String,
) : IllegalStateException(message)
object AccessLifecycleGateway {
private const val MAX_RESPONSE_CHARS = 32 * 1024
suspend fun fetch(
capability: RemoteAccessCapability,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
): AccessLifecycleStatus = request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = profileRevision,
operation = "status",
).let(::parseStatus)
suspend fun begin(
capability: RemoteAccessCapability,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
): RemoteLaunchTarget = request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = profileRevision,
operation = "continue",
).let(::parseLaunchTarget)
suspend fun submitProfileValues(
capability: RemoteAccessCapability,
token: String,
device: String,
client: String,
system: String,
timezone: String,
values: List<String>,
): RemoteProfileExchange =
parseExchangeResult(
request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = 0,
action = token,
values = values,
)
)
suspend fun invokeProfileAction(
capability: RemoteAccessCapability,
token: String,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
): RemoteDocumentLink = request(
capability = capability,
device = device,
client = client,
system = system,
timezone = timezone,
profileRevision = profileRevision,
action = token,
).let(::parseActionDocument)
private suspend fun request(
capability: RemoteAccessCapability,
device: String,
client: String,
system: String,
timezone: String,
profileRevision: Long,
operation: String = "",
action: String = "",
values: List<String> = emptyList(),
): String {
require(capability.available && opaqueValue(capability.key)) {
"Управление доступом недоступно для этого профиля."
}
require(safeServiceUrl(capability.url)) {
"Не удалось проверить доступ для этого профиля."
}
require(validDevice(device)) { "Не удалось определить текущее устройство." }
require(
(
operation in setOf("status", "continue") &&
action.isBlank()
) ||
(
operation.isBlank() &&
opaqueValue(action)
)
)
require(values.size <= 16)
return withContext(Dispatchers.IO) {
val payload = JSONObject()
.put("key", capability.key.trim())
.put("device", device.trim())
.put("client", client.trim().take(64))
.put("system", system.trim().take(64))
.put("timezone", timezone.trim().take(64))
.put("profile_revision", profileRevision.coerceAtLeast(0))
.put("values", org.json.JSONArray(values))
.apply {
if (operation.isNotBlank()) put("operation", operation)
if (action.isNotBlank()) put("action", action)
}
.toString()
.toByteArray(Charsets.UTF_8)
var connection: HttpURLConnection? = null
try {
connection = URL(capability.url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.instanceFollowRedirects = false
connection.connectTimeout = 7_000
connection.readTimeout = 9_000
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val body = readBody(connection, status)
if (status !in 200..299) {
throw parseHttpFailure(
status = status,
body = body,
operation = operation,
codeHint = connection.getHeaderField("X-WDTT-Access-Code").orEmpty(),
)
}
body
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (error is IllegalStateException) throw error
throw IllegalStateException(
if (operation == "continue") {
"Не удалось открыть страницу. Проверьте интернет и повторите попытку."
} else if (action.isNotBlank()) {
"Не удалось обновить сохранённые данные профиля."
} else {
"Не удалось проверить профиль. Проверьте интернет."
}
)
} finally {
connection?.disconnect()
}
}
}
internal fun parseHttpFailure(
status: Int,
body: String,
operation: String,
codeHint: String = "",
): AccessLifecycleRequestException {
val root = runCatching { JSONObject(body) }.getOrNull()
val detail = root?.opt("detail")
val structured = detail as? JSONObject
val code = structured?.optString("code").orEmpty()
.ifBlank { root?.optString("code").orEmpty() }
.ifBlank { codeHint }
.trim()
.lowercase()
val message = (
structured?.optString("message")
?: (detail as? String)
?: ""
).trim().take(300)
val kind = when {
status == 410 || code == "expired" -> AccessLifecycleFailureKind.REJECTED
code in setOf("unbound", "device_mismatch") -> AccessLifecycleFailureKind.UNBOUND
status in setOf(401, 403, 404) ||
code in setOf("removed", "revoked", "not_found", "forbidden") ->
AccessLifecycleFailureKind.UNAVAILABLE
else -> AccessLifecycleFailureKind.TEMPORARY
}
val fallback = when {
operation == "continue" -> "Действие сейчас недоступно. Попробуйте позже."
kind == AccessLifecycleFailureKind.REJECTED ->
"Поставщик отклонил использование этого профиля."
kind == AccessLifecycleFailureKind.UNBOUND ->
"Профиль отвязан от этого устройства."
kind == AccessLifecycleFailureKind.UNAVAILABLE ->
"Профиль больше недоступен для этого устройства."
else -> "Не удалось проверить профиль."
}
return AccessLifecycleRequestException(
kind = kind,
code = code.ifBlank { "http_$status" },
message = message.ifBlank { fallback },
)
}
internal fun parseStatus(body: String): AccessLifecycleStatus {
val root = parseRoot(body)
require(root.optInt("version", 0) == 1) {
"Для проверки доступа нужна более новая версия WDTT Plus."
}
require(root.has("allow_connect")) {
"WDTT Plus вернул неполное решение по профилю."
}
val allowConnect = root.optBoolean("allow_connect", false)
val action = root.optJSONObject("action")
val actionAvailable = action?.optBoolean("available", false) == true
val actionLabel = action?.optString("label").orEmpty().trim().take(80)
val actionMessage = action?.optString("message").orEmpty().trim().take(240)
val actionIcon = action?.optString("icon").orEmpty().trim().take(32)
.takeIf { it == "update" }
.orEmpty()
val title = root.optString("title").trim().take(120)
val message = root.optString("message").trim().take(400)
val detail = root.optJSONObject("detail")
val detailLabel = detail?.optString("label").orEmpty().trim().take(80)
val detailValue = detail?.optString("value").orEmpty().trim().take(120)
val severity = AccessLifecycleSeverity.parse(
root.optString("severity"),
allowConnect,
)
val profile = root.optJSONObject("profile")
val revision = profile?.optLong("revision", 0)?.coerceAtLeast(0) ?: 0
val update = if (profile?.optBoolean("update_available", false) == true) {
val link = RemoteDocumentGateway.extractLink(profile.optString("document"))
?: throw IllegalStateException("WDTT Plus вернул повреждённое обновление профиля.")
require(revision > 0) { "WDTT Plus вернул неполное обновление профиля." }
AccessProfileUpdate(revision = revision, link = link)
} else {
null
}
val cachedAction = root.optJSONObject("cached_action")
?.let(RemoteDocumentGateway::parseCachedAction)
?: CachedRemoteAction.Unavailable
val exchange = root.optJSONObject("exchange")
?.let(RemoteDocumentGateway::parseProfileExchange)
return AccessLifecycleStatus(
allowConnect = allowConnect,
actionAvailable = actionAvailable,
actionLabel = actionLabel,
actionMessage = actionMessage,
title = title,
message = message,
detailLabel = detailLabel,
detailValue = detailValue,
actionIcon = actionIcon,
severity = severity,
profileRevision = revision,
profileUpdate = update,
cachedAction = cachedAction,
exchange = exchange,
)
}
internal fun parseLaunchTarget(body: String): RemoteLaunchTarget {
val root = parseRoot(body)
val primary = root.optString("url").trim()
val fallback = root.optString("fallback").trim()
val handler = root.optString("handler").trim()
val alternateHandlers = root.optJSONArray("alternate_handlers")?.let { source ->
if (source.length() > 7) null else {
(0 until source.length())
.map { index -> source.optString(index).trim() }
.takeIf { values ->
values.all { it.isNotBlank() && safePackageName(it) } &&
values.distinct().size == values.size
}
}
} ?: if (root.has("alternate_handlers")) null else emptyList()
require(safeExternalUrl(primary)) {
"WDTT Plus вернул повреждённый адрес продолжения."
}
require(fallback.isBlank() || safeExternalUrl(fallback)) {
"WDTT Plus вернул повреждённый резервный адрес."
}
require(handler.isBlank() || safePackageName(handler)) {
"WDTT Plus вернул повреждённый обработчик продолжения."
}
require(alternateHandlers != null) {
"WDTT Plus вернул повреждённые резервные обработчики."
}
return RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
)
}
internal fun parseActionDocument(body: String): RemoteDocumentLink {
val root = parseRoot(body)
require(root.optInt("version", 0) == 1) {
"Для действия нужна более новая версия WDTT Plus."
}
return RemoteDocumentGateway.extractLink(root.optString("document"))
?: throw IllegalStateException("WDTT Plus вернул повреждённое обновление профиля.")
}
internal fun parseExchangeResult(body: String): RemoteProfileExchange {
val root = parseRoot(body)
require(root.optInt("version", 0) == 1) {
"WDTT Plus не подтвердил обновление данных профиля."
}
val source = root.optJSONObject("exchange")
?: throw IllegalStateException("WDTT Plus вернул неполный ответ.")
return RemoteDocumentGateway.parseProfileExchange(source)
}
private fun parseRoot(body: String): JSONObject {
require(body.length <= MAX_RESPONSE_CHARS) { "Ответ WDTT Plus слишком большой." }
return runCatching { JSONObject(body) }
.getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") }
}
private fun safeServiceUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) &&
uri.rawUserInfo.isNullOrBlank() &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safeExternalUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun opaqueValue(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value)
private fun validDevice(value: String): Boolean =
Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim())
private fun readBody(connection: HttpURLConnection, status: Int): String {
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty()
}
}
+167 -23
View File
@@ -2,6 +2,8 @@ package com.wdtt.plus
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.content.FileProvider
@@ -33,8 +35,16 @@ private const val UPDATE_CHECK_TOTAL_TIMEOUT_MS = 25_000L
private const val UPDATE_CHECK_REQUEST_TIMEOUT_MS = 6_000L
private const val UPDATE_CHECK_MIN_REQUEST_TIMEOUT_MS = 1_000L
private const val UPDATE_APK_HASH_TIMEOUT_MS = 4_000L
private const val MAX_UPDATE_APK_BYTES = 200L * 1024L * 1024L
private const val MAX_UPDATE_METADATA_BYTES = 1024 * 1024
private const val MAX_UPDATE_WEB_BYTES = 512 * 1024
private const val MAX_UPDATE_REDIRECTS = 5
private const val GITHUB_API_RATE_LIMIT_FALLBACK_MS = 30L * 60L * 1000L
private val SIMPLE_VERSION_TAG_REGEX = Regex("^v?(\\d+)$", RegexOption.IGNORE_CASE)
private val TRUSTED_UPDATE_ASSET_HOSTS = setOf(
"objects.githubusercontent.com",
"release-assets.githubusercontent.com",
)
@Volatile
private var githubApiCooldownUntilMs = 0L
@@ -185,7 +195,12 @@ suspend fun resolveAppUpdateCandidate(
fun selectUpdateApkAsset(release: AppReleaseInfo): AppReleaseAsset? {
val apkAssets = release.assets
.filter { it.name.endsWith(".apk", ignoreCase = true) && it.downloadUrl.isNotBlank() }
.filter {
it.name.endsWith(".apk", ignoreCase = true) &&
it.sha256 != null &&
it.sizeBytes in 1..MAX_UPDATE_APK_BYTES &&
isTrustedUpdateDownloadUrl(it.downloadUrl, initialRequest = true)
}
if (apkAssets.isEmpty()) return null
Build.SUPPORTED_ABIS.orEmpty().forEach { abi ->
@@ -201,6 +216,14 @@ suspend fun downloadUpdateApk(
asset: AppReleaseAsset,
onProgress: suspend (AppUpdateDownloadProgress) -> Unit = {}
): File = withContext(Dispatchers.IO) {
val expectedSha256 = asset.sha256
?: throw SecurityException("Для APK отсутствует обязательный SHA-256.")
require(asset.sizeBytes in 1..MAX_UPDATE_APK_BYTES) {
"Размер APK отсутствует или превышает безопасный лимит."
}
require(isTrustedUpdateDownloadUrl(asset.downloadUrl, initialRequest = true)) {
"Адрес APK не принадлежит официальному выпуску WDTT Plus."
}
val appContext = context.applicationContext
val updatesDir = File(appContext.cacheDir, "updates").apply { mkdirs() }
updatesDir.listFiles()?.forEach { file ->
@@ -217,28 +240,58 @@ suspend fun downloadUpdateApk(
}
try {
conn = URL(asset.downloadUrl).openConnection() as HttpURLConnection
applyNoCacheHeaders(conn)
conn.instanceFollowRedirects = true
conn.requestMethod = "GET"
conn.setRequestProperty("Accept", "application/vnd.android.package-archive,application/octet-stream,*/*")
conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}")
conn.connectTimeout = 15_000
conn.readTimeout = 30_000
val responseCode = conn.responseCode
var currentUrl = URL(asset.downloadUrl)
var responseCode = 0
for (redirect in 0..MAX_UPDATE_REDIRECTS) {
val currentConnection = currentUrl.openConnection() as HttpURLConnection
conn = currentConnection
applyNoCacheHeaders(currentConnection)
currentConnection.instanceFollowRedirects = false
currentConnection.requestMethod = "GET"
currentConnection.setRequestProperty(
"Accept",
"application/vnd.android.package-archive,application/octet-stream",
)
currentConnection.setRequestProperty(
"User-Agent",
"WDTTAndroid/${BuildConfig.VERSION_NAME}",
)
currentConnection.connectTimeout = 15_000
currentConnection.readTimeout = 30_000
responseCode = currentConnection.responseCode
if (responseCode !in 300..399) break
val location = currentConnection.getHeaderField("Location")
?.takeIf { it.isNotBlank() }
?: throw IOException("GitHub вернул перенаправление без адреса.")
if (redirect >= MAX_UPDATE_REDIRECTS) {
throw IOException("GitHub вернул слишком много перенаправлений.")
}
val nextUrl = URL(currentUrl, location)
require(isTrustedUpdateDownloadUrl(nextUrl.toString(), initialRequest = false)) {
"GitHub перенаправил загрузку на недоверенный адрес."
}
currentConnection.disconnect()
conn = null
currentUrl = nextUrl
}
val activeConnection = conn ?: throw IOException("Не удалось открыть загрузку APK.")
if (responseCode !in 200..299) {
throw IOException("GitHub вернул HTTP $responseCode при скачивании APK")
}
val total = asset.sizeBytes.takeIf { it > 0L }
?: conn.contentLengthLong.takeIf { it > 0L }
?: 0L
val responseLength = activeConnection.contentLengthLong
if (responseLength > MAX_UPDATE_APK_BYTES) {
throw IOException("APK превышает безопасный лимит размера.")
}
if (responseLength > 0L && responseLength != asset.sizeBytes) {
throw IOException("Размер APK не совпал с данными выпуска.")
}
val total = asset.sizeBytes
var downloaded = 0L
var lastEmitAt = 0L
emit(0L, total)
conn.inputStream.use { input ->
activeConnection.inputStream.use { input ->
outputFile.outputStream().use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
@@ -246,6 +299,9 @@ suspend fun downloadUpdateApk(
if (read < 0) break
output.write(buffer, 0, read)
downloaded += read
if (downloaded > MAX_UPDATE_APK_BYTES || downloaded > asset.sizeBytes) {
throw IOException("APK превышает заявленный размер.")
}
val now = System.currentTimeMillis()
if (now - lastEmitAt >= 250L || downloaded == total) {
lastEmitAt = now
@@ -260,13 +316,12 @@ suspend fun downloadUpdateApk(
throw IOException("Размер APK не совпал с GitHub asset")
}
asset.sha256?.let { expected ->
val actual = outputFile.sha256Hex()
if (!actual.equals(expected, ignoreCase = true)) {
outputFile.delete()
throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest")
}
val actual = outputFile.sha256Hex()
if (!actual.equals(expectedSha256, ignoreCase = true)) {
outputFile.delete()
throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest")
}
validateUpdatePackage(appContext, outputFile)
emit(outputFile.length(), total.takeIf { it > 0L } ?: outputFile.length())
outputFile
@@ -285,6 +340,7 @@ fun canRequestApkInstall(context: Context): Boolean {
fun installUpdateApk(context: Context, apkFile: File) {
val appContext = context.applicationContext
validateUpdatePackage(appContext, apkFile)
val uri = FileProvider.getUriForFile(appContext, "${appContext.packageName}.files", apkFile)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
@@ -294,6 +350,90 @@ fun installUpdateApk(context: Context, apkFile: File) {
appContext.startActivity(intent)
}
internal fun isTrustedUpdateDownloadUrl(
value: String,
initialRequest: Boolean,
): Boolean {
val uri = runCatching { java.net.URI(value) }.getOrNull() ?: return false
val host = uri.host?.lowercase(Locale.US)?.trimEnd('.') ?: return false
if (
!uri.scheme.equals("https", ignoreCase = true) ||
!uri.rawUserInfo.isNullOrBlank() ||
(uri.port != -1 && uri.port != 443) ||
!uri.rawFragment.isNullOrBlank()
) {
return false
}
if (initialRequest) {
return host == "github.com" &&
uri.path.orEmpty().startsWith(
"/Ivan4537/WDTT-Plus/releases/download/",
ignoreCase = true,
)
}
return host in TRUSTED_UPDATE_ASSET_HOSTS ||
host.endsWith(".release-assets.githubusercontent.com")
}
private fun validateUpdatePackage(context: Context, apkFile: File) {
require(apkFile.isFile && apkFile.length() in 1..MAX_UPDATE_APK_BYTES) {
"Файл обновления отсутствует или имеет недопустимый размер."
}
val packageManager = context.packageManager
val archive = packageManager.updateArchiveInfo(apkFile)
?: throw SecurityException("Не удалось проверить пакет обновления.")
val installed = packageManager.installedUpdateTargetInfo(context.packageName)
if (archive.packageName != context.packageName) {
throw SecurityException("APK предназначен для другого приложения.")
}
val archiveSigners = archive.currentSignerDigests()
val installedSigners = installed.currentSignerDigests()
if (
archiveSigners.isEmpty() ||
installedSigners.isEmpty() ||
archiveSigners != installedSigners
) {
throw SecurityException("Подпись APK не совпадает с установленным WDTT Plus.")
}
}
@Suppress("DEPRECATION")
private fun PackageManager.updateArchiveInfo(apkFile: File): PackageInfo? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
getPackageArchiveInfo(
apkFile.absolutePath,
PackageManager.PackageInfoFlags.of(
PackageManager.GET_SIGNING_CERTIFICATES.toLong(),
),
)
} else {
getPackageArchiveInfo(apkFile.absolutePath, PackageManager.GET_SIGNING_CERTIFICATES)
}
}
@Suppress("DEPRECATION")
private fun PackageManager.installedUpdateTargetInfo(packageName: String): PackageInfo {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
getPackageInfo(
packageName,
PackageManager.PackageInfoFlags.of(
PackageManager.GET_SIGNING_CERTIFICATES.toLong(),
),
)
} else {
getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES)
}
}
private fun PackageInfo.currentSignerDigests(): Set<String> {
val signers = signingInfo?.apkContentsSigners.orEmpty()
return signers.mapTo(linkedSetOf()) { signature ->
MessageDigest.getInstance("SHA-256")
.digest(signature.toByteArray())
.joinToString("") { "%02x".format(it) }
}
}
fun isNewerVersion(local: String, remote: String): Boolean {
val localParts = versionParts(local)
val remoteParts = versionParts(remote)
@@ -442,7 +582,9 @@ private fun fetchReleaseFromLatestWebRedirect(budget: UpdateCheckBudget): AppRel
}
if (responseCode in 200..299) {
val response = conn.inputStream.bufferedReader().use { it.readText() }
val response = conn.inputStream.use {
it.readUtf8TextLimited(MAX_UPDATE_WEB_BYTES)
}
val versionTag = Regex("/releases/tag/([^\"?#<]+)").find(response)?.groupValues?.getOrNull(1)
if (!versionTag.isNullOrBlank()) {
return AppReleaseInfo(versionTag, "$GITHUB_RELEASE_TAG_URL_PREFIX$versionTag", RemoteVersionSource.Release)
@@ -494,7 +636,9 @@ private fun fetchHttpText(
val responseCode = conn.responseCode
val stream = if (responseCode in 200..299) conn.inputStream else conn.errorStream
val response = stream?.bufferedReader()?.use { it.readText() }.orEmpty()
val response = stream?.use {
it.readUtf8TextLimited(MAX_UPDATE_METADATA_BYTES)
}.orEmpty()
if (responseCode in 200..299) {
if (isGitHubApi) githubApiCooldownUntilMs = 0L
@@ -0,0 +1,19 @@
package com.wdtt.plus
import java.io.ByteArrayOutputStream
import java.io.InputStream
internal fun InputStream.readUtf8TextLimited(maxBytes: Int): String {
require(maxBytes > 0) { "Лимит ответа должен быть положительным." }
val output = ByteArrayOutputStream(minOf(maxBytes, DEFAULT_BUFFER_SIZE))
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var total = 0
while (true) {
val read = read(buffer)
if (read < 0) break
total += read
require(total <= maxBytes) { "Ответ сервиса слишком большой." }
output.write(buffer, 0, read)
}
return output.toString(Charsets.UTF_8.name())
}
@@ -384,14 +384,8 @@ object CaptchaWebViewManager {
handler: android.webkit.SslErrorHandler,
error: android.net.http.SslError
) {
// Разрешаем только для доверенных доменов VK/OK
val url = error.url ?: ""
if (url.contains("vk.ru") || url.contains("vk.com") || url.contains("okcdn.ru")) {
handler.proceed()
} else {
handler.cancel()
Log.w(TAG, "SSL error rejected for: $url")
}
handler.cancel()
Log.w(TAG, "Отклонена страница с ошибкой TLS")
}
}
@@ -0,0 +1,562 @@
package com.wdtt.plus
import android.content.Context
import android.net.ConnectivityManager
import android.net.DnsResolver
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import android.os.CancellationSignal
import android.os.SystemClock
import android.telephony.TelephonyManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.io.DataInputStream
import java.io.DataOutputStream
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketTimeoutException
import java.net.URL
import java.net.UnknownHostException
import java.util.concurrent.Executor
import javax.net.ssl.HttpsURLConnection
import kotlin.coroutines.resume
data class ClientNetworkDiagnosticsReport(
val summaryLines: List<String>,
val items: List<DeviceCheckItem>
)
private data class DiagnosticNetwork(
val network: Network,
val capabilities: NetworkCapabilities,
val linkProperties: LinkProperties?,
val activeNetworkIsVpn: Boolean,
val mobileOperator: String
)
private data class NetworkProbeResult(
val label: String,
val success: Boolean,
val result: String,
val elapsedMs: Long
) {
fun display(): String = "$label: $result (${elapsedMs} мс)"
}
internal data class DnsResponseStatus(
val responseCode: Int,
val answerCount: Int,
val truncated: Boolean
)
internal data class ClientDnsPathAssessment(
val status: String,
val recommendation: String,
val severity: DeviceCheckSeverity,
val action: DeviceCheckAction?
)
private const val NETWORK_PROBE_TIMEOUT_MS = 4_500L
private const val SOCKET_TIMEOUT_MS = 3_500
private val directExecutor = Executor { command -> command.run() }
private val clientDnsServers = listOf("77.88.8.8", "77.88.8.1")
private val clientDnsRouteOrder = listOf(
"77.88.8.8 UDP",
"77.88.8.1 UDP",
"77.88.8.8 TCP",
"77.88.8.1 TCP"
)
internal const val clientDnsProbeHost = "api.vk.me"
internal val primaryVkDiagnosticHosts = linkedSetOf(
"api.vk.me",
"calls.okcdn.ru"
)
internal val reserveVkDiagnosticHosts = linkedSetOf(
"vk.ru",
"login.vk.ru",
"api.vk.ru",
"id.vk.ru",
"static.vk.ru",
"vk.com",
"id.vk.com",
"static.vk.com"
)
private val vkDnsHosts = (primaryVkDiagnosticHosts + reserveVkDiagnosticHosts).toList()
private val vkHttpsTargets = listOf(
"api.vk.me" to "https://api.vk.me/method/users.get?v=5.276",
"calls.okcdn.ru" to "https://calls.okcdn.ru/fb.do",
"vk.ru" to "https://vk.ru/",
"login.vk.ru" to "https://login.vk.ru/",
"api.vk.ru" to "https://api.vk.ru/method/users.get?v=5.275",
"id.vk.ru" to "https://id.vk.ru/",
"static.vk.ru" to "https://static.vk.ru/",
"vk.com" to "https://vk.com/",
"id.vk.com" to "https://id.vk.com/",
"static.vk.com" to "https://static.vk.com/"
)
suspend fun collectClientNetworkDiagnostics(context: Context): ClientNetworkDiagnosticsReport =
withContext(Dispatchers.IO) {
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
val diagnosticNetwork = connectivityManager?.let { selectDiagnosticNetwork(context, it) }
if (diagnosticNetwork == null) {
return@withContext ClientNetworkDiagnosticsReport(
summaryLines = listOf("Активная физическая сеть для проверки DNS/VK не найдена"),
items = listOf(
DeviceCheckItem(
title = "Сетевой путь телефона",
status = "физическая сеть не найдена",
details = "Не удалось выбрать сеть без VPN для безопасной проверки DNS и узлов VK/OK.",
recommendation = "Отключите режим полёта, включите Wi‑Fi или мобильную сеть и повторите диагностику.",
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.NetworkSettings
)
)
)
}
val networkItem = buildNetworkPathItem(diagnosticNetwork)
val (dnsResults, clientDnsResults, httpsResults) = coroutineScope {
val systemDns = async { probeSystemDns(diagnosticNetwork.network) }
val clientDns = async { probeClientDns(diagnosticNetwork.network) }
val vkHttps = async { probeVkHttps(diagnosticNetwork.network) }
Triple(systemDns.await(), clientDns.await(), vkHttps.await())
}
val primaryDnsResults = dnsResults.filter { it.label in primaryVkDiagnosticHosts }
val reserveDnsResults = dnsResults.filter { it.label in reserveVkDiagnosticHosts }
val primaryDnsOk = primaryDnsResults.count { it.success }
val clientUdp = clientDnsResults.filter { it.label.endsWith("UDP") }
val clientTcp = clientDnsResults.filter { it.label.endsWith("TCP") }
val clientUdpOk = clientUdp.count { it.success }
val clientTcpOk = clientTcp.count { it.success }
val primaryHttpsResults = httpsResults.filter { it.label in primaryVkDiagnosticHosts }
val reserveHttpsResults = httpsResults.filter { it.label in reserveVkDiagnosticHosts }
val primaryHttpsOk = primaryHttpsResults.count { it.success }
val systemPrimaryApiWorks = dnsResults.firstOrNull { it.label == clientDnsProbeHost }?.success == true
val successfulClientDnsRoutes = clientDnsResults
.filter { it.success }
.mapTo(linkedSetOf()) { it.label }
val clientDnsAssessment = assessClientDnsPath(successfulClientDnsRoutes, systemPrimaryApiWorks)
val dnsItem = DeviceCheckItem(
title = "DNS основного VKCalls на телефоне",
status = "$primaryDnsOk из ${primaryDnsResults.size} основных узлов разрешаются",
details = primaryDnsResults.joinToString(". ") { it.display() } + ". " +
"Резервные legacy- и совместимые узлы: " +
reserveDnsResults.joinToString(". ") { it.display() } + ".",
recommendation = if (primaryDnsOk == primaryDnsResults.size) "" else
"Быстрый VKCalls может быть недоступен. Проверьте системный или Private DNS и сеть оператора; приложение также попробует legacy-резерв.",
severity = if (primaryDnsOk == primaryDnsResults.size) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning,
action = if (primaryDnsOk == primaryDnsResults.size) null else DeviceCheckAction.NetworkSettings
)
val clientDnsItem = DeviceCheckItem(
title = "DNS-путь нативного клиента",
status = clientDnsAssessment.status,
details = clientDnsResults.joinToString(". ") { it.display() } +
". Нативный клиент проверяет эти прямые DNS-пути, а при их недоступности автоматически использует системный DNS Android.",
recommendation = clientDnsAssessment.recommendation,
severity = clientDnsAssessment.severity,
action = clientDnsAssessment.action
)
val httpsItem = DeviceCheckItem(
title = "Основной VKCalls HTTPS с телефона",
status = "$primaryHttpsOk из ${primaryHttpsResults.size} основных узлов отвечают",
details = primaryHttpsResults.joinToString(". ") { it.display() } + ". " +
"Резервные legacy- и совместимые узлы: " +
reserveHttpsResults.joinToString(". ") { it.display() } +
". Любой HTTP-код означает, что DNS, TCP и TLS до узла отработали; авторизация и VK-хеш не используются.",
recommendation = if (primaryHttpsOk == primaryHttpsResults.size) "" else
"Для быстрого VKCalls сеть должна пропускать api.vk.me и calls.okcdn.ru. При их недоступности приложение попробует legacy-резерв.",
severity = if (primaryHttpsOk == primaryHttpsResults.size) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning,
action = if (primaryHttpsOk == primaryHttpsResults.size) null else DeviceCheckAction.NetworkSettings
)
val recentNetworkEvents = buildRecentNetworkEventsItem()
ClientNetworkDiagnosticsReport(
summaryLines = listOf(
"Физическая сеть диагностики: ${networkPathSummary(diagnosticNetwork)}",
"DNS основного VKCalls: $primaryDnsOk/${primaryDnsResults.size}",
"DNS клиента: ${clientDnsAssessment.status}; UDP $clientUdpOk/${clientUdp.size}, TCP $clientTcpOk/${clientTcp.size}",
"HTTPS основного VKCalls: $primaryHttpsOk/${primaryHttpsResults.size}"
),
items = buildList {
add(networkItem)
add(dnsItem)
add(clientDnsItem)
add(httpsItem)
recentNetworkEvents?.let(::add)
}
)
}
internal fun assessClientDnsPath(
successfulDirectRoutes: Set<String>,
systemPrimaryApiWorks: Boolean
): ClientDnsPathAssessment {
val selectedDirectRoute = clientDnsRouteOrder.firstOrNull(successfulDirectRoutes::contains)
return when {
selectedDirectRoute == "77.88.8.8 UDP" -> ClientDnsPathAssessment(
status = "основной UDP DNS доступен",
recommendation = "",
severity = DeviceCheckSeverity.Ok,
action = null
)
selectedDirectRoute == "77.88.8.1 UDP" -> ClientDnsPathAssessment(
status = "резервный UDP DNS доступен",
recommendation = "Основной прямой DNS ограничен, но нативный клиент автоматически выберет рабочий резервный адрес.",
severity = DeviceCheckSeverity.Info,
action = null
)
selectedDirectRoute?.endsWith(" TCP") == true -> ClientDnsPathAssessment(
status = "UDP DNS недоступен, TCP отвечает",
recommendation = "Оператор ограничивает прямой UDP DNS, но нативный клиент автоматически использует рабочий TCP-путь.",
severity = DeviceCheckSeverity.Info,
action = null
)
systemPrimaryApiWorks -> ClientDnsPathAssessment(
status = "прямой DNS недоступен, используется системный DNS",
recommendation = "Это штатный автоматический fallback: менять DNS вручную не требуется.",
severity = DeviceCheckSeverity.Info,
action = null
)
else -> ClientDnsPathAssessment(
status = "DNS до VK недоступен",
recommendation = "Не ответили ни прямые DNS-пути клиента, ни системный DNS Android. Проверьте Private DNS или повторите проверку в другой сети.",
severity = DeviceCheckSeverity.Error,
action = DeviceCheckAction.NetworkSettings
)
}
}
private fun selectDiagnosticNetwork(context: Context, connectivityManager: ConnectivityManager): DiagnosticNetwork? {
val activeNetwork = runCatching { connectivityManager.activeNetwork }.getOrNull()
val activeCapabilities = activeNetwork?.let {
runCatching { connectivityManager.getNetworkCapabilities(it) }.getOrNull()
}
val activeNetworkIsVpn = activeCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
val candidates = runCatching { connectivityManager.allNetworks.toList() }.getOrDefault(emptyList())
.mapNotNull { network ->
val capabilities = runCatching { connectivityManager.getNetworkCapabilities(network) }.getOrNull()
?: return@mapNotNull null
if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) ||
!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
) {
return@mapNotNull null
}
Triple(network, capabilities, runCatching { connectivityManager.getLinkProperties(network) }.getOrNull())
}
val selected = candidates.maxByOrNull { (network, capabilities, _) ->
var score = 0
if (network == activeNetwork) score += 100
if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) score += 50
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) score += 10
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) score += 5
score
} ?: return null
return DiagnosticNetwork(
network = selected.first,
capabilities = selected.second,
linkProperties = selected.third,
activeNetworkIsVpn = activeNetworkIsVpn,
mobileOperator = mobileOperatorSummary(context, selected.second)
)
}
private fun mobileOperatorSummary(context: Context, capabilities: NetworkCapabilities): String {
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return "не применяется"
return runCatching {
val telephonyManager = context.getSystemService(TelephonyManager::class.java)
val network = telephonyManager?.networkOperatorName.orEmpty().trim()
val sim = telephonyManager?.simOperatorName.orEmpty().trim()
val names = listOf(network, sim).filter(String::isNotBlank).distinct()
buildString {
append(names.joinToString(" / ").ifBlank { "не определён" })
append(", roaming=")
append(telephonyManager?.isNetworkRoaming ?: false)
}
}.getOrDefault("недоступен")
}
private fun buildNetworkPathItem(network: DiagnosticNetwork): DeviceCheckItem {
val capabilities = network.capabilities
val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
val details = networkPathSummary(network)
return DeviceCheckItem(
title = "Сетевой путь телефона",
status = if (validated) "физическая сеть подтверждена" else "интернет не подтверждён Android",
details = details,
recommendation = if (validated) "" else
"Проверьте ограничения оператора, captive portal или доступность интернета без VPN.",
severity = if (validated) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning,
action = if (validated) null else DeviceCheckAction.NetworkSettings
)
}
private fun networkPathSummary(network: DiagnosticNetwork): String {
val capabilities = network.capabilities
val properties = network.linkProperties
val transports = buildList {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) add("мобильная")
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) add("Wi‑Fi")
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) add("Ethernet")
}.joinToString().ifBlank { "не определена" }
val hasIpv4 = properties?.linkAddresses?.any { it.address is Inet4Address } == true
val hasIpv6 = properties?.linkAddresses?.any { it.address is Inet6Address } == true
val dnsServers = properties?.dnsServers
?.joinToString { it.hostAddress.orEmpty() }
?.ifBlank { "не указаны" }
?: "недоступны"
val privateDns = if (properties?.isPrivateDnsActive == true) {
properties.privateDnsServerName?.takeIf(String::isNotBlank)?.let { "включён ($it)" } ?: "включён"
} else {
"выключен"
}
val nat64 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
properties?.nat64Prefix?.toString() ?: "нет"
} else {
"не поддерживается Android"
}
val mtu = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
properties?.mtu?.toString() ?: "недоступно"
} else {
"не поддерживается Android"
}
return "Сеть: $transports; validated=${capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)}; " +
"metered=${!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)}; " +
"активный VPN=${network.activeNetworkIsVpn}; оператор=${network.mobileOperator}; " +
"IPv4=$hasIpv4; IPv6=$hasIpv6; NAT64=$nat64; " +
"MTU=$mtu; системные DNS: $dnsServers; Private DNS: $privateDns. " +
"Локальные IP-адреса телефона в отчёт не включаются."
}
private suspend fun probeSystemDns(network: Network): List<NetworkProbeResult> = coroutineScope {
vkDnsHosts.map { host ->
async(Dispatchers.IO) {
timedProbe(host) {
val addresses = resolveWithSystemDns(network, host)
val ipv4 = addresses.count { it is Inet4Address }
val ipv6 = addresses.count { it is Inet6Address }
if (addresses.isEmpty()) error("пустой DNS-ответ")
"OK, IPv4=$ipv4, IPv6=$ipv6"
}
}
}.awaitAll()
}
private suspend fun resolveWithSystemDns(network: Network, host: String): List<InetAddress> =
withTimeout(NETWORK_PROBE_TIMEOUT_MS) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
suspendCancellableCoroutine { continuation ->
val cancellationSignal = CancellationSignal()
continuation.invokeOnCancellation { cancellationSignal.cancel() }
DnsResolver.getInstance().query(
network,
host,
DnsResolver.FLAG_EMPTY,
directExecutor,
cancellationSignal,
object : DnsResolver.Callback<List<InetAddress>> {
override fun onAnswer(answer: List<InetAddress>, rcode: Int) {
if (!continuation.isActive) return
if (rcode == 0 && answer.isNotEmpty()) continuation.resume(answer)
else continuation.resumeWith(Result.failure(UnknownHostException("DNS rcode=$rcode")))
}
override fun onError(error: DnsResolver.DnsException) {
if (continuation.isActive) continuation.resumeWith(Result.failure(error))
}
}
)
}
} else {
runInterruptible(Dispatchers.IO) { network.getAllByName(host).toList() }
}
}
private suspend fun probeClientDns(network: Network): List<NetworkProbeResult> = coroutineScope {
clientDnsServers.flatMap { server ->
listOf(
async(Dispatchers.IO) {
timedProbe("$server UDP") { directDnsQuery(network, server, useTcp = false) }
},
async(Dispatchers.IO) {
timedProbe("$server TCP") { directDnsQuery(network, server, useTcp = true) }
}
)
}.awaitAll()
}
private fun directDnsQuery(network: Network, server: String, useTcp: Boolean): String {
val queryId = (SystemClock.elapsedRealtimeNanos() and 0xffff).toInt()
val query = buildDnsQuery(clientDnsProbeHost, queryId)
val response = if (useTcp) {
Socket().use { socket ->
network.bindSocket(socket)
socket.connect(InetSocketAddress(server, 53), SOCKET_TIMEOUT_MS)
socket.soTimeout = SOCKET_TIMEOUT_MS
DataOutputStream(socket.getOutputStream()).use { output ->
output.writeShort(query.size)
output.write(query)
output.flush()
val input = DataInputStream(socket.getInputStream())
val responseLength = input.readUnsignedShort()
require(responseLength in 12..65_535) { "некорректная длина DNS-ответа" }
ByteArray(responseLength).also(input::readFully)
}
}
} else {
DatagramSocket(null).use { socket ->
network.bindSocket(socket)
socket.soTimeout = SOCKET_TIMEOUT_MS
socket.connect(InetSocketAddress(server, 53))
socket.send(DatagramPacket(query, query.size))
val buffer = ByteArray(2_048)
val packet = DatagramPacket(buffer, buffer.size)
socket.receive(packet)
packet.data.copyOfRange(packet.offset, packet.offset + packet.length)
}
}
val status = parseDnsResponse(response, queryId)
require(status.responseCode == 0) { "DNS rcode=${status.responseCode}" }
require(status.answerCount > 0) { "DNS-ответ без записей" }
return "OK, ответов=${status.answerCount}${if (status.truncated) ", truncated" else ""}"
}
internal fun buildDnsQuery(host: String, queryId: Int): ByteArray {
val labels = host.trim('.').split('.')
require(labels.isNotEmpty() && labels.all { it.isNotBlank() && it.toByteArray(Charsets.US_ASCII).size <= 63 }) {
"некорректное DNS-имя"
}
val bytes = ArrayList<Byte>(host.length + 18)
fun addShort(value: Int) {
bytes += ((value ushr 8) and 0xff).toByte()
bytes += (value and 0xff).toByte()
}
addShort(queryId)
addShort(0x0100)
addShort(1)
addShort(0)
addShort(0)
addShort(0)
labels.forEach { label ->
val encoded = label.toByteArray(Charsets.US_ASCII)
bytes += encoded.size.toByte()
encoded.forEach { bytes += it }
}
bytes += 0.toByte()
addShort(1)
addShort(1)
return bytes.toByteArray()
}
internal fun parseDnsResponse(response: ByteArray, expectedId: Int): DnsResponseStatus {
require(response.size >= 12) { "короткий DNS-ответ" }
fun unsignedShort(offset: Int): Int =
((response[offset].toInt() and 0xff) shl 8) or (response[offset + 1].toInt() and 0xff)
require(unsignedShort(0) == (expectedId and 0xffff)) { "чужой DNS-ответ" }
val flags = unsignedShort(2)
require(flags and 0x8000 != 0) { "DNS-пакет не является ответом" }
return DnsResponseStatus(
responseCode = flags and 0x000f,
answerCount = unsignedShort(6),
truncated = flags and 0x0200 != 0
)
}
private suspend fun probeVkHttps(network: Network): List<NetworkProbeResult> = coroutineScope {
vkHttpsTargets.map { (label, url) ->
async(Dispatchers.IO) {
timedProbe(label) { httpsProbe(network, url) }
}
}.awaitAll()
}
private fun httpsProbe(network: Network, target: String): String {
val connection = network.openConnection(URL(target)) as HttpsURLConnection
return try {
connection.connectTimeout = SOCKET_TIMEOUT_MS
connection.readTimeout = SOCKET_TIMEOUT_MS
connection.instanceFollowRedirects = false
connection.requestMethod = "GET"
connection.setRequestProperty("User-Agent", "WDTT-Plus-Diagnostics/${BuildConfig.VERSION_NAME}")
connection.setRequestProperty("Range", "bytes=0-0")
val responseCode = connection.responseCode
require(responseCode in 100..599) { "нет HTTP-ответа" }
"HTTP $responseCode"
} finally {
connection.disconnect()
}
}
private suspend inline fun timedProbe(label: String, crossinline block: suspend () -> String): NetworkProbeResult {
val started = SystemClock.elapsedRealtime()
return try {
val result = block()
NetworkProbeResult(label, true, result, SystemClock.elapsedRealtime() - started)
} catch (error: CancellationException) {
if (error !is TimeoutCancellationException) throw error
NetworkProbeResult(label, false, "тайм-аут", SystemClock.elapsedRealtime() - started)
} catch (_: SocketTimeoutException) {
NetworkProbeResult(label, false, "тайм-аут", SystemClock.elapsedRealtime() - started)
} catch (_: UnknownHostException) {
NetworkProbeResult(label, false, "DNS не разрешён", SystemClock.elapsedRealtime() - started)
} catch (error: Throwable) {
val reason = error.message
?.replace(Regex("[\\r\\n]+"), " ")
?.take(120)
?.takeIf(String::isNotBlank)
?: error.javaClass.simpleName
NetworkProbeResult(label, false, reason, SystemClock.elapsedRealtime() - started)
}
}
private fun buildRecentNetworkEventsItem(): DeviceCheckItem? {
val entries = TunnelManager.logs.value
.filter { entry ->
entry.severity != LogSeverity.Info ||
entry.key.startsWith("err_") ||
entry.key.startsWith("vkcalls_") ||
entry.key.startsWith("vk_provider_") ||
entry.key.startsWith("vk_credentials_") ||
entry.key.startsWith("vk_legacy_") ||
entry.key.startsWith("turn_") ||
entry.key.startsWith("worker_turn_")
}
.take(12)
if (entries.isEmpty()) return null
val details = entries.joinToString(" | ") { entry ->
val message = entry.message
.replace(Regex("(https?://[^?\\s]+)\\?[^\\s]+"), "\$1?<параметры скрыты>")
.replace(Regex("(?i)(token|password|credential|secret)=([^&\\s]+)"), "\$1=<скрыто>")
.take(220)
"${entry.key}: $message${if (entry.count > 1) " ×${entry.count}" else ""}"
}
return DeviceCheckItem(
title = "Последние сетевые события туннеля",
status = "собрано ${entries.size}",
details = details,
severity = DeviceCheckSeverity.Info
)
}
@@ -90,13 +90,11 @@ object ClientTransferCodec {
val clean = value.trim()
if (clean.isBlank()) return ""
require(clean.length <= 4096 && clean.none(Char::isISOControl)) { "Поле VK-хешей повреждено." }
val hashes = clean.split(Regex("[,\\s]+"))
.map { VkJoinLink.extractHash(it) }
.filter { it.isNotBlank() }
require(hashes.isNotEmpty() && hashes.all { it.length >= 16 } && hashes.none { it.contains('/') || it.contains('\\') }) {
val hashes = VkJoinLink.normalizeHashes(clean)
require(hashes != null) {
"VK-хеши в переносе имеют неверный формат."
}
return hashes.distinct().joinToString(",")
return hashes
}
}
@@ -17,6 +17,7 @@ object DeployManager {
val deployProgress = MutableStateFlow(0f)
val currentStep = MutableStateFlow("")
val lastResult = MutableStateFlow("") // "success", "error: ...", ""
val installedServerVersion = MutableStateFlow("")
@Volatile
var activeSession: com.jcraft.jsch.Session? = null
@@ -59,6 +60,7 @@ object DeployManager {
deployProgress.value = 0f
currentStep.value = "Инициализация..."
lastResult.value = ""
installedServerVersion.value = ""
}
fun stopDeploy(result: String = "") {
@@ -340,8 +340,8 @@ object DeviceCompatibility {
DeviceCheckItem(
title = "WebView",
status = "не найден",
details = "Автоматическая и ручная captcha через WebView могут не работать.",
recommendation = "Проверьте системный Android System WebView или браузер-провайдер WebView.",
details = "Быстрый VKCalls может работать без WebView, но автоматическая и ручная капча резервного способа будут недоступны.",
recommendation = "Обновите или включите Android System WebView либо браузер-провайдер WebView, чтобы резервное подключение могло пройти капчу.",
severity = DeviceCheckSeverity.Warning,
firstLaunchRelevant = false,
action = DeviceCheckAction.WebViewSettings
@@ -350,7 +350,7 @@ object DeviceCompatibility {
DeviceCheckItem(
title = "WebView",
status = webView.packageName,
details = "Версия: ${webView.versionName}. WebView доступен для captcha-сценариев.",
details = "Версия: ${webView.versionName}. WebView доступен для капчи резервного способа.",
severity = DeviceCheckSeverity.Ok,
firstLaunchRelevant = false
)
@@ -395,7 +395,7 @@ object DeviceCompatibility {
return DeviceCheckItem(
title = "Сеть Android",
status = "активная сеть не найдена",
details = "Приложение запустится, но для VKCalls, TURN и обновлений нужна сеть.",
details = "Приложение запустится, но для быстрого VKCalls, TURN и обновлений нужна сеть.",
recommendation = "Подключитесь к Wi‑Fi или мобильной сети.",
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.NetworkSettings
@@ -422,7 +422,7 @@ object DeviceCompatibility {
DeviceCheckItem(
title = "Сеть Android",
status = "$transports, интернет подтверждён",
details = "Активная сеть выглядит пригодной для проверки VK/TURN.",
details = "Android подтвердил общий доступ в интернет. Системный DNS, DNS-путь нативного клиента и служебные узлы VK/OK проверяются отдельными пунктами ниже.",
severity = DeviceCheckSeverity.Ok
)
}
@@ -0,0 +1,29 @@
package com.wdtt.plus
internal object DeviceIdentity {
private val validPattern = Regex("^[A-Za-z0-9_.:-]{8,128}$")
private val knownInvalidAndroidIds = setOf(
"9774d56d682e549c",
"unknown",
)
fun valid(value: String): Boolean =
value.trim().matches(validPattern) &&
value.trim().lowercase() !in knownInvalidAndroidIds
fun resolve(
existing: String?,
platformId: String?,
generatedId: String,
): String {
val stored = existing.orEmpty().trim()
if (valid(stored)) return stored
val platform = platformId.orEmpty().trim()
if (valid(platform)) return platform
val generated = generatedId.trim()
require(valid(generated)) { "Некорректный резервный идентификатор устройства." }
return generated
}
}
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,6 @@
package com.wdtt.plus
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Intent
import android.graphics.drawable.Icon
@@ -33,9 +34,19 @@ class QuickToggleTileService : TileService() {
TunnelManager.running,
TrustedWifiManager.state,
settingsStore.activeProfile,
settingsStore.profileNames
) { running, trustedWifi, activeProfile, profileNames ->
TileUiState(running, trustedWifi, activeProfile, profileNames)
TunnelManager.activeTunnelProfile,
settingsStore.profileNames,
) { running, trustedWifi, selectedProfile, activeTunnelProfile, profileNames ->
TileUiState(
running,
trustedWifi,
selectedProfile,
activeTunnelProfile,
profileNames,
AccessLifecycleUiState.Unmanaged,
)
}.combine(settingsStore.activeAccessLifecycle) { state, accessLifecycle ->
state.copy(accessLifecycle = accessLifecycle)
}.collect { uiState ->
updateTile(uiState)
}
@@ -53,39 +64,53 @@ class QuickToggleTileService : TileService() {
override fun onClick() {
super.onClick()
runCatching {
if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) {
// Если запущен — останавливаем. Состояние плитки изменится автоматически,
// когда TunnelManager остановит процессы и обновит статус running в false.
val stopIntent = Intent(this, TunnelService::class.java).apply { action = "STOP" }
startService(stopIntent)
return
}
when (
tunnelToggleAction(
running = TunnelManager.running.value,
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
vpnPermissionRequired = VpnService.prepare(this) != null,
)
) {
TunnelToggleAction.STOP -> {
// Состояние плитки изменится после фактической остановки службы.
startService(
Intent(this, TunnelService::class.java).apply { action = "STOP" }
)
}
TunnelToggleAction.REQUEST_VPN_PERMISSION -> {
Toast.makeText(
this,
"Откройте WDTT Plus и выдайте VPN-разрешение",
Toast.LENGTH_LONG
).show()
openMainActivity()
}
TunnelToggleAction.START -> scope.launch {
try {
val intent = buildTunnelStartIntentFromSettings(this@QuickToggleTileService)
if (intent == null) {
Toast.makeText(
this@QuickToggleTileService,
"Заполните настройки подключения в WDTT Plus",
Toast.LENGTH_LONG
).show()
openMainActivity()
return@launch
}
// Проверяем наличие выданного разрешения VPN перед стартом
if (VpnService.prepare(this) != null) {
Toast.makeText(this, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
openMainActivity()
return
}
// Запускаем старт туннеля в фоне
scope.launch {
try {
val intent = buildTunnelStartIntentFromSettings(this@QuickToggleTileService)
if (intent == null) {
Toast.makeText(this@QuickToggleTileService, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show()
openMainActivity()
return@launch
if (Build.VERSION.SDK_INT >= 26) {
startForegroundService(intent)
} else {
startService(intent)
}
} catch (e: Exception) {
Log.e("QuickToggleTile", "Failed to start tunnel via QS tile", e)
Toast.makeText(
this@QuickToggleTileService,
"Ошибка запуска: ${e.localizedMessage}",
Toast.LENGTH_SHORT
).show()
}
if (Build.VERSION.SDK_INT >= 26) {
startForegroundService(intent)
} else {
startService(intent)
}
} catch (e: Exception) {
Log.e("QuickToggleTile", "Failed to start tunnel via QS tile", e)
Toast.makeText(this@QuickToggleTileService, "Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT).show()
}
}
}.onFailure { e ->
@@ -102,12 +127,21 @@ class QuickToggleTileService : TileService() {
runCatching {
val running = uiState.running
val waiting = uiState.trustedWifi.waiting
val activeProfile = uiState.activeProfile
val profileNames = uiState.profileNames
val profile = activeProfile.coerceIn(0, 2)
val profile = displayedTunnelProfile(
selectedProfile = uiState.selectedProfile,
activeTunnelProfile = uiState.activeTunnelProfile,
running = running,
trustedWifiWaiting = waiting,
)
val profileLabel = vpnProfileDisplayName(profile, profileNames)
val defaultProfileLabel = vpnProfileDefaultName(profile)
val profileIsDefault = profileLabel == defaultProfileLabel
val accessBlocked =
uiState.accessLifecycle.managed &&
!uiState.accessLifecycle.allowConnect &&
!running &&
!waiting
qsTile?.apply {
label = when {
waiting -> "Ожидание"
@@ -121,6 +155,8 @@ class QuickToggleTileService : TileService() {
subtitle = when {
waiting -> uiState.trustedWifi.ssid.ifBlank { "Wi-Fi" }
running -> ""
accessBlocked -> uiState.accessLifecycle.title
.ifBlank { uiState.accessLifecycle.fallbackTitle() }
else -> "Отключено"
}
}
@@ -134,10 +170,13 @@ class QuickToggleTileService : TileService() {
private data class TileUiState(
val running: Boolean,
val trustedWifi: TrustedWifiRuntimeState,
val activeProfile: Int,
val profileNames: List<String>
val selectedProfile: Int,
val activeTunnelProfile: Int?,
val profileNames: List<String>,
val accessLifecycle: AccessLifecycleUiState,
)
@SuppressLint("StartActivityAndCollapseDeprecated")
private fun openMainActivity() {
runCatching {
val intent = Intent(this, MainActivity::class.java).apply {
@@ -0,0 +1,407 @@
package com.wdtt.plus
import android.content.Context
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.util.UUID
/**
* Provider-neutral UI action prepared by a remote service.
*
* The application does not interpret the destination or reconstruct either
* URL. It only validates the generic HTTPS boundary and opens the exact
* backend-provided target.
*/
data class RemoteUiAction(
val title: String,
val message: String,
val label: String,
val target: RemoteLaunchTarget,
val confirmationTitle: String = "",
val confirmationMessage: String = "",
val confirmationLabel: String = "",
val progressLabel: String = "",
val preparingMessage: String = "",
val stoppingMessage: String = "",
val openingMessage: String = "",
val successMessage: String = "",
val cancelledMessage: String = "",
val failureMessage: String = "",
val compactMessage: String = "",
val compactLabel: String = "",
val compactLinkText: String = "",
val compactButtonVisible: Boolean = true,
val cancelLabel: String = "",
val form: RemoteActionForm? = null,
)
data class RemoteActionFormChoice(
val label: String,
val value: String,
)
data class RemoteActionForm(
val token: String,
val submitUrl: String,
val title: String,
val message: String,
val choices: List<RemoteActionFormChoice>,
val inputLabel: String,
val inputSuffix: String,
val initialValue: String,
val minimum: Long,
val maximum: Long,
val maxCharacters: Int,
val supportingText: String,
val invalidText: String,
val submitLabel: String,
val busyLabel: String,
val failureMessage: String,
val fallbackLabel: String,
)
class RemoteActionExecutionException(message: String) : IllegalStateException(message)
data class RemoteActionCatalog(
val actions: Map<String, RemoteUiAction> = emptyMap(),
) {
fun at(placement: String): RemoteUiAction? = actions[placement]
companion object {
val Empty = RemoteActionCatalog()
}
}
object RemoteActionCatalogGateway {
private const val CACHE_TTL_MS = 10 * 60 * 1000L
private const val MAX_RESPONSE_CHARS = 32 * 1024
private val placements = setOf("tunnel", "profile", "about")
@Volatile
private var cachedAt = 0L
@Volatile
private var cachedCatalog = RemoteActionCatalog.Empty
fun hasFreshCache(): Boolean =
System.currentTimeMillis() - cachedAt in 0 until CACHE_TTL_MS
fun cached(): RemoteActionCatalog =
if (hasFreshCache()) cachedCatalog else RemoteActionCatalog.Empty
suspend fun fetch(force: Boolean = false): RemoteActionCatalog {
val now = System.currentTimeMillis()
if (!force && now - cachedAt in 0 until CACHE_TTL_MS) return cachedCatalog
return withContext(Dispatchers.IO) {
val current = System.currentTimeMillis()
if (!force && current - cachedAt in 0 until CACHE_TTL_MS) {
return@withContext cachedCatalog
}
val received = runCatching { request() }.getOrDefault(RemoteActionCatalog.Empty)
cachedCatalog = received
cachedAt = current
received
}
}
suspend fun fetchQuestionAction(): RemoteUiAction? =
withContext(Dispatchers.IO) {
runCatching { request(context = "question").at("about") }.getOrNull()
}
suspend fun execute(
form: RemoteActionForm,
requestId: String,
value: String,
): RemoteLaunchTarget = withContext(Dispatchers.IO) {
require(validOpaqueToken(form.token)) { "Действие устарело. Обновите экран." }
require(safeExternalUrl(form.submitUrl)) { "Получен небезопасный адрес действия." }
require(runCatching { UUID.fromString(requestId) }.isSuccess) {
"Не удалось подготовить действие."
}
require(value.length in 1..32) { form.invalidText }
var connection: HttpURLConnection? = null
try {
connection = URL(form.submitUrl).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.instanceFollowRedirects = false
connection.connectTimeout = 7_000
connection.readTimeout = 12_000
connection.doOutput = true
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
val payload = JSONObject()
.put("token", form.token)
.put("request_id", requestId)
.put("value", value)
.put("client", BuildConfig.VERSION_NAME)
.put("system", android.os.Build.VERSION.RELEASE.orEmpty())
.toString()
.toByteArray(Charsets.UTF_8)
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val stream = if (status in 200..299) {
connection.inputStream
} else {
connection.errorStream
}
val body = stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty()
if (status !in 200..299) {
val detail = runCatching {
JSONObject(body).optString("detail").trim().take(240)
}.getOrDefault("")
throw RemoteActionExecutionException(
detail.ifBlank { form.failureMessage }
)
}
parseExecutionTarget(body)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: RemoteActionExecutionException) {
throw error
} catch (error: Exception) {
throw RemoteActionExecutionException(form.failureMessage)
} finally {
connection?.disconnect()
}
}
private fun request(context: String? = null): RemoteActionCatalog {
var connection: HttpURLConnection? = null
return try {
val query = buildList {
if (BuildConfig.REMOTE_ACTION_PREVIEW) add("preview=1")
if (context == "question") add("context=question")
}.joinToString("&").let { if (it.isBlank()) "" else "?$it" }
connection = URL(
"https://${BuildConfig.WDTT_PLUS_DOMAIN}/api/client/actions$query"
).openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.instanceFollowRedirects = false
connection.connectTimeout = 5_000
connection.readTimeout = 6_000
connection.setRequestProperty("Accept", "application/json")
val status = connection.responseCode
if (status !in 200..299) return RemoteActionCatalog.Empty
parse(connection.inputStream.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) })
} finally {
connection?.disconnect()
}
}
internal fun parse(body: String): RemoteActionCatalog {
if (body.length > MAX_RESPONSE_CHARS) return RemoteActionCatalog.Empty
val root = runCatching { JSONObject(body) }.getOrNull()
?: return RemoteActionCatalog.Empty
if (root.optInt("version", 0) != 1) return RemoteActionCatalog.Empty
val source = root.optJSONObject("actions") ?: return RemoteActionCatalog.Empty
val actions = placements.mapNotNull { placement ->
val item = source.optJSONObject(placement) ?: return@mapNotNull null
parseAction(item)?.let { placement to it }
}.toMap()
return RemoteActionCatalog(actions)
}
private fun parseAction(item: JSONObject): RemoteUiAction? {
val title = item.optString("title").trim().take(120)
val message = item.optString("message").trim().take(400)
val label = item.optString("label").trim().take(80)
val confirmationTitle = item.optString("confirmation_title").trim().take(120)
val confirmationMessage = item.optString("confirmation_message").trim().take(1600)
val confirmationLabel = item.optString("confirmation_label").trim().take(80)
val progressLabel = item.optString("progress_label").trim().take(80)
val preparingMessage = item.optString("preparing_message").trim().take(240)
val stoppingMessage = item.optString("stopping_message").trim().take(240)
val openingMessage = item.optString("opening_message").trim().take(240)
val successMessage = item.optString("success_message").trim().take(400)
val cancelledMessage = item.optString("cancelled_message").trim().take(240)
val failureMessage = item.optString("failure_message").trim().take(240)
val compactMessage = item.optString("compact_message").trim().take(400)
val compactLabel = item.optString("compact_label").trim().take(80)
val compactLinkText = item.optString("compact_link_text").trim().take(120)
val compactButtonVisible = item.optBoolean("compact_button_visible", true)
val cancelLabel = item.optString("cancel_label").trim().take(80)
val primary = item.optString("url").trim()
val fallback = item.optString("fallback").trim()
val handler = item.optString("handler").trim()
val alternateHandlers = parseAlternateHandlers(item) ?: return null
val formSource = item.optJSONObject("form")
val form = formSource?.let(::parseForm)
if (title.isBlank() || message.isBlank() || label.isBlank()) return null
if (!safeExternalUrl(primary)) return null
if (fallback.isNotBlank() && !safeExternalUrl(fallback)) return null
if (handler.isNotBlank() && !safePackageName(handler)) return null
if (formSource != null && form == null) return null
return RemoteUiAction(
title = title,
message = message,
label = label,
confirmationTitle = confirmationTitle,
confirmationMessage = confirmationMessage,
confirmationLabel = confirmationLabel,
progressLabel = progressLabel,
preparingMessage = preparingMessage,
stoppingMessage = stoppingMessage,
openingMessage = openingMessage,
successMessage = successMessage,
cancelledMessage = cancelledMessage,
failureMessage = failureMessage,
compactMessage = compactMessage,
compactLabel = compactLabel,
compactLinkText = compactLinkText,
compactButtonVisible = compactButtonVisible,
cancelLabel = cancelLabel,
form = form,
target = RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
),
)
}
private fun parseForm(item: JSONObject): RemoteActionForm? {
val token = item.optString("token").trim()
val submitUrl = item.optString("submit_url").trim()
val title = item.optString("title").trim().take(120)
val message = item.optString("message").trim().take(600)
val inputLabel = item.optString("input_label").trim().take(80)
val inputSuffix = item.optString("input_suffix").trim().take(16)
val initialValue = item.optString("initial_value").trim().take(32)
val minimum = item.optLong("minimum", Long.MIN_VALUE)
val maximum = item.optLong("maximum", Long.MIN_VALUE)
val maxCharacters = item.optInt("max_characters", 0)
val supportingText = item.optString("supporting_text").trim().take(160)
val invalidText = item.optString("invalid_text").trim().take(160)
val submitLabel = item.optString("submit_label").trim().take(120)
val busyLabel = item.optString("busy_label").trim().take(80)
val failureMessage = item.optString("failure_message").trim().take(240)
val fallbackLabel = item.optString("fallback_label").trim().take(80)
val choicesSource = item.optJSONArray("choices") ?: return null
if (
!validOpaqueToken(token) ||
!safeExternalUrl(submitUrl) ||
title.isBlank() ||
message.isBlank() ||
inputLabel.isBlank() ||
initialValue.isBlank() ||
minimum < 0 ||
maximum < minimum ||
maximum > 1_000_000_000L ||
maxCharacters !in 1..12 ||
supportingText.isBlank() ||
invalidText.isBlank() ||
submitLabel.isBlank() ||
busyLabel.isBlank() ||
failureMessage.isBlank() ||
fallbackLabel.isBlank() ||
choicesSource.length() !in 1..8
) {
return null
}
val initialNumber = initialValue.toLongOrNull() ?: return null
if (initialNumber !in minimum..maximum) return null
val choices = (0 until choicesSource.length()).mapNotNull { index ->
val choice = choicesSource.optJSONObject(index) ?: return@mapNotNull null
val choiceLabel = choice.optString("label").trim().take(40)
val choiceValue = choice.optString("value").trim()
if (choiceLabel.isBlank() || choiceValue.length !in 1..256) {
null
} else {
RemoteActionFormChoice(choiceLabel, choiceValue)
}
}
if (choices.size != choicesSource.length()) return null
return RemoteActionForm(
token = token,
submitUrl = submitUrl,
title = title,
message = message,
choices = choices,
inputLabel = inputLabel,
inputSuffix = inputSuffix,
initialValue = initialValue,
minimum = minimum,
maximum = maximum,
maxCharacters = maxCharacters,
supportingText = supportingText,
invalidText = invalidText,
submitLabel = submitLabel,
busyLabel = busyLabel,
failureMessage = failureMessage,
fallbackLabel = fallbackLabel,
)
}
internal fun parseExecutionTarget(body: String): RemoteLaunchTarget {
if (body.length > MAX_RESPONSE_CHARS) {
throw RemoteActionExecutionException("Получен слишком большой ответ.")
}
val root = runCatching { JSONObject(body) }.getOrNull()
?: throw RemoteActionExecutionException("Получен некорректный ответ.")
if (root.optInt("version", 0) != 1) {
throw RemoteActionExecutionException("Версия ответа не поддерживается.")
}
val primary = root.optString("url").trim()
val fallback = root.optString("fallback").trim()
val handler = root.optString("handler").trim()
val alternateHandlers = parseAlternateHandlers(root)
?: throw RemoteActionExecutionException("Получены небезопасные обработчики действия.")
if (
!safeExternalUrl(primary) ||
(fallback.isNotBlank() && !safeExternalUrl(fallback)) ||
(handler.isNotBlank() && !safePackageName(handler))
) {
throw RemoteActionExecutionException("Получен небезопасный адрес действия.")
}
return RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
)
}
private fun validOpaqueToken(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9._-]+$").matches(value)
private fun safeExternalUrl(value: String): Boolean {
if (value.length !in 1..2048) return false
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun parseAlternateHandlers(item: JSONObject): List<String>? {
val handlers = item.optJSONArray("alternate_handlers") ?: return emptyList()
if (handlers.length() > 7) return null
return (0 until handlers.length())
.map { index -> handlers.optString(index).trim() }
.takeIf { values ->
values.all { it.isNotBlank() && safePackageName(it) } &&
values.distinct().size == values.size
}
}
}
object RemoteUiActionLauncher {
suspend fun open(context: Context, action: RemoteUiAction): Boolean =
withContext(Dispatchers.Main.immediate) {
runCatching {
RemoteContinuationLauncher.launch(context, action.target)
true
}.getOrDefault(false)
}
}
@@ -0,0 +1,276 @@
package com.wdtt.plus
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.browser.auth.AuthTabIntent
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.net.URLDecoder
data class RemoteLaunchTarget(
val primaryUrl: String,
val fallbackUrl: String = "",
val preferredHandler: String = "",
val alternateHandlers: List<String> = emptyList(),
val returnScheme: String = "",
) {
internal fun handlerPackages(): List<String> =
(listOf(preferredHandler) + alternateHandlers)
.filter(String::isNotBlank)
.distinct()
}
object RemoteContinuationLauncher {
suspend fun begin(capability: RemoteContinuation, device: String): RemoteLaunchTarget {
require(capability.available && opaqueValue(capability.key)) {
"Автоматическое заполнение недоступно для этого профиля."
}
require(safeServiceUrl(capability.url)) { "Автоматическое заполнение сейчас недоступно." }
require(validDevice(device)) { "Не удалось определить текущее устройство." }
return withContext(Dispatchers.IO) {
val payload = JSONObject()
.put("key", capability.key.trim())
.put("device", device.trim())
.put("return_transport", "auth_tab")
.toString()
.toByteArray(Charsets.UTF_8)
var connection: HttpURLConnection? = null
try {
connection = URL(capability.url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.connectTimeout = 10_000
connection.readTimeout = 15_000
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val body = readBody(connection, status)
if (status !in 200..299) {
val detail = runCatching { JSONObject(body).optString("detail") }.getOrDefault("")
throw IllegalStateException(
detail.ifBlank { "Не удалось продолжить действие. Откройте свежую ссылку подключения." }
)
}
val response = runCatching { JSONObject(body) }
.getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") }
val primary = response.optString("url").trim()
val fallback = response.optString("fallback").trim()
val handler = response.optString("handler").trim()
val alternateHandlers = parseAlternateHandlers(response)
val returnScheme = response.optString("return_scheme").trim()
require(safeExternalUrl(primary)) {
"WDTT Plus вернул повреждённый адрес продолжения."
}
require(fallback.isBlank() || safeExternalUrl(fallback)) {
"WDTT Plus вернул повреждённый резервный адрес."
}
require(handler.isBlank() || safePackageName(handler)) {
"WDTT Plus вернул повреждённый обработчик продолжения."
}
require(alternateHandlers != null) {
"WDTT Plus вернул повреждённые резервные обработчики."
}
require(returnScheme.isBlank() || returnScheme == AUTH_TAB_RETURN_SCHEME) {
"WDTT Plus вернул повреждённый способ возврата."
}
RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternateHandlers,
returnScheme = returnScheme,
)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (error is IllegalStateException) throw error
throw IllegalStateException(
"Не удалось связаться с WDTT Plus. Проверьте интернет и повторите попытку."
)
} finally {
connection?.disconnect()
}
}
}
fun launch(
context: Context,
target: RemoteLaunchTarget,
authTabLauncher: ActivityResultLauncher<Intent>? = null,
) {
require(safeExternalUrl(target.primaryUrl)) { "Адрес продолжения повреждён." }
val handlerPackages = target.handlerPackages()
require(handlerPackages.size <= MAX_HANDLER_PACKAGES) {
"Получено слишком много обработчиков продолжения."
}
handlerPackages.forEach { handler ->
require(safePackageName(handler)) { "Обработчик продолжения повреждён." }
try {
context.startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse(target.primaryUrl)).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
setPackage(handler)
}
)
return
} catch (_: ActivityNotFoundException) {
// The fallback preserves the remote operation when its preferred app is unavailable.
} catch (_: SecurityException) {
// Some Android builds reject explicit package launches; use the browser below.
}
}
if (target.returnScheme == AUTH_TAB_RETURN_SCHEME && authTabLauncher != null) {
AuthTabIntent.Builder()
.build()
.launch(
authTabLauncher,
Uri.parse(authTabLaunchUrl(target)),
AUTH_TAB_RETURN_SCHEME,
)
return
}
var lastFailure: Exception? = null
for (browserUrl in browserLaunchUrls(target)) {
try {
context.startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse(browserUrl)).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
}
)
return
} catch (error: ActivityNotFoundException) {
lastFailure = error
} catch (error: SecurityException) {
lastFailure = error
}
}
throw IllegalStateException(
"Не удалось открыть VK или страницу продолжения. Проверьте приложение VK и браузер.",
lastFailure,
)
}
internal fun authTabLaunchUrl(target: RemoteLaunchTarget): String =
browserLaunchUrls(target).first()
internal fun browserLaunchUrls(target: RemoteLaunchTarget): List<String> =
(
if (target.handlerPackages().isNotEmpty() && target.fallbackUrl.isNotBlank()) {
listOf(target.fallbackUrl, target.primaryUrl)
} else {
listOf(target.primaryUrl, target.fallbackUrl)
}
)
.filter { it.isNotBlank() }
.onEach {
require(safeExternalUrl(it)) { "Резервный адрес продолжения повреждён." }
}
.distinct()
internal fun callbackDocumentUri(callback: Uri?): Uri? {
val document = callbackDocumentUrl(callback?.toString().orEmpty()) ?: return null
return Uri.parse(document)
}
internal fun isCancellationCallback(callback: Uri?): Boolean =
isCancellationCallback(callback?.toString().orEmpty())
internal fun isCancellationCallback(rawCallback: String): Boolean {
val uri = runCatching { URI(rawCallback.trim()) }.getOrNull() ?: return false
return uri.scheme.equals(AUTH_TAB_RETURN_SCHEME, ignoreCase = true) &&
uri.host.equals("return", ignoreCase = true) &&
uri.port == -1 &&
uri.rawUserInfo.isNullOrBlank() &&
uri.path.orEmpty().isBlank() &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank()
}
internal fun callbackDocumentUrl(rawCallback: String): String? {
val callback = runCatching { URI(rawCallback.trim()) }.getOrNull() ?: return null
if (
!callback.scheme.equals(AUTH_TAB_RETURN_SCHEME, ignoreCase = true) ||
!callback.host.equals("return", ignoreCase = true) ||
callback.port != -1 ||
!callback.rawUserInfo.isNullOrBlank() ||
!callback.rawFragment.isNullOrBlank() ||
callback.path.orEmpty().isNotBlank()
) {
return null
}
val documents = callback.rawQuery.orEmpty()
.split('&')
.mapNotNull { item ->
val separator = item.indexOf('=')
if (separator <= 0) return@mapNotNull null
val key = URLDecoder.decode(
item.substring(0, separator),
Charsets.UTF_8.name(),
)
if (key != "document") return@mapNotNull null
URLDecoder.decode(
item.substring(separator + 1),
Charsets.UTF_8.name(),
)
}
val document = documents.singleOrNull()?.trim().orEmpty()
return RemoteDocumentGateway.extractLink(document)?.url
}
private fun safeServiceUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) &&
uri.rawUserInfo.isNullOrBlank() &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safeExternalUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun parseAlternateHandlers(source: JSONObject): List<String>? {
val handlers = source.optJSONArray("alternate_handlers") ?: return emptyList()
if (handlers.length() > MAX_HANDLER_PACKAGES - 1) return null
return (0 until handlers.length())
.map { index -> handlers.optString(index).trim() }
.takeIf { values ->
values.all { it.isNotBlank() && safePackageName(it) } &&
values.distinct().size == values.size
}
}
private fun opaqueValue(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value)
private fun validDevice(value: String): Boolean =
Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim())
private fun readBody(connection: HttpURLConnection, status: Int): String {
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_BYTES) }.orEmpty()
}
private const val AUTH_TAB_RETURN_SCHEME = "wdtt"
private const val MAX_HANDLER_PACKAGES = 8
private const val MAX_RESPONSE_BYTES = 32 * 1024
}
@@ -0,0 +1,388 @@
package com.wdtt.plus
import android.net.Uri
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.util.TimeZone
data class RemoteDocumentLink(val url: String)
data class RemoteDocumentFailureAction(
val label: String,
val target: RemoteLaunchTarget,
)
class RemoteDocumentFailure(
message: String,
val action: RemoteDocumentFailureAction? = null,
) : IllegalStateException(message)
data class RemoteContinuation(
val available: Boolean,
val key: String = "",
val url: String = "",
val expiresAt: Long = 0,
val message: String = ""
)
enum class RemoteDocumentKind {
BASE,
UPDATE
}
data class RemoteDocumentDelivery(
val document: String,
val binding: String,
val continuation: RemoteContinuation,
val access: RemoteAccessCapability,
val kind: RemoteDocumentKind,
val profileMaxWorkers: Int = 0,
val profileRevision: Long = 0,
)
internal fun RemoteDocumentDelivery.shouldPreserveLocalVkHashes(
existingProfileRedelivery: Boolean = false,
): Boolean {
val deliveredHashes = WdttDeepLink.parse(document, allowMissingHashes = true)
?.hashes
.orEmpty()
return deliveredHashes.isBlank() &&
(
kind == RemoteDocumentKind.UPDATE ||
(kind == RemoteDocumentKind.BASE && existingProfileRedelivery)
)
}
internal fun RemoteDocumentDelivery.requiresInitialContinuationWarning(
existingProfileHasVkHashes: Boolean = false,
): Boolean =
kind == RemoteDocumentKind.BASE &&
!continuation.available &&
!existingProfileHasVkHashes
object RemoteDocumentGateway {
private const val MAX_RESPONSE_CHARS = 32 * 1024
fun extractLink(uri: Uri): RemoteDocumentLink? = extractLink(uri.toString())
fun extractLink(rawUri: String): RemoteDocumentLink? {
val uri = runCatching { URI(rawUri.trim()) }.getOrNull() ?: return null
val path = uri.path.orEmpty()
val code = path.takeIf { it.startsWith("/c/") }
?.removePrefix("/c/")
?.trim()
.orEmpty()
val navigationMarkerValid = uri.rawQuery.isNullOrBlank() ||
Regex("^open=[0-9]{1,20}$").matches(uri.rawQuery)
val valid = trustedServiceUri(uri) &&
navigationMarkerValid &&
uri.rawFragment.isNullOrBlank() &&
Regex("^[A-Za-z0-9_-]{6,64}$").matches(code)
if (!valid) return null
return RemoteDocumentLink("https://${BuildConfig.WDTT_PLUS_DOMAIN}/c/$code")
}
suspend fun receive(
link: RemoteDocumentLink,
device: String,
label: String,
client: String,
system: String,
localBindings: Collection<String>? = null,
): RemoteDocumentDelivery {
require(extractLink(link.url) != null) { "Ссылка повреждена или неполна." }
require(validDevice(device)) { "Не удалось определить текущее устройство." }
return withContext(Dispatchers.IO) {
val request = JSONObject()
.put("device", device.trim())
.put("label", label.trim().take(160))
.put("client", client.trim().take(64))
.put("system", system.trim().take(64))
.put("timezone", TimeZone.getDefault().id.take(64))
if (localBindings != null) {
val bindings = localBindings
.map(String::trim)
.filter(::opaqueValue)
.distinct()
.take(6)
request.put("bindings", JSONArray(bindings))
}
val payload = request
.toString()
.toByteArray(Charsets.UTF_8)
var connection: HttpURLConnection? = null
try {
connection = URL(link.url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.connectTimeout = 10_000
connection.readTimeout = 12_000
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val body = readBody(connection, status)
if (status !in 200..299) {
val failure = parseFailure(body)
throw RemoteDocumentFailure(
failure.first.ifBlank {
"Ссылка недоступна. Получите новую ссылку подключения."
},
failure.second,
)
}
parse(body)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (error is IllegalStateException) throw error
throw IllegalStateException(
"Не удалось связаться с WDTT Plus. Проверьте интернет и попробуйте ещё раз."
)
} finally {
connection?.disconnect()
}
}
}
internal fun parse(body: String): RemoteDocumentDelivery {
require(body.length <= MAX_RESPONSE_CHARS) { "Ответ WDTT Plus слишком большой." }
val root = runCatching { JSONObject(body) }
.getOrElse { throw IllegalStateException("WDTT Plus вернул неполные данные.") }
if (root.optInt("version", 0) != 1) {
throw IllegalStateException("Для этой ссылки нужна более новая версия WDTT Plus.")
}
val kind = when (root.optString("type").trim()) {
"base" -> RemoteDocumentKind.BASE
"update" -> RemoteDocumentKind.UPDATE
else -> throw IllegalStateException("WDTT Plus вернул неподдерживаемый тип данных.")
}
val document = root.optString("document").trim()
val documentParts = WdttDeepLink.parse(document, allowMissingHashes = true)
if (documentParts == null) {
throw IllegalStateException("WDTT Plus вернул неполные данные подключения.")
}
val binding = root.optString("binding").trim().takeIf(::opaqueValue).orEmpty()
val action = root.optJSONObject("continuation")
val key = action?.optString("key").orEmpty().trim()
val url = action?.optString("url").orEmpty().trim()
val available = action?.optBoolean("available", false) == true &&
opaqueValue(key) && safeServiceUrl(url)
val accessSource = root.optJSONObject("access")
val accessKey = accessSource?.optString("key").orEmpty().trim()
val accessUrl = accessSource?.optString("url").orEmpty().trim()
val accessBinding = accessSource?.optString("binding").orEmpty().trim()
val accessAvailable = accessSource?.optBoolean("available", false) == true &&
opaqueValue(accessKey) &&
safeServiceUrl(accessUrl) &&
opaqueValue(accessBinding)
val cachedAction = accessSource
?.optJSONObject("cached_action")
?.let(::parseCachedAction)
?: CachedRemoteAction.Unavailable
val exchange = accessSource
?.optJSONObject("exchange")
?.let(::parseProfileExchange)
?: RemoteProfileExchange.Unavailable
val initialAccessStatus = if (accessAvailable) {
accessSource
?.optJSONObject("status")
?.let { nested ->
AccessLifecycleGateway.parseStatus(
JSONObject(nested.toString()).put("version", 1).toString()
)
}
} else {
null
}
when (kind) {
RemoteDocumentKind.BASE -> {
if (documentParts.hashes.isNotBlank()) {
throw IllegalStateException(
"Ссылка подключения содержит лишние данные. Получите новую ссылку."
)
}
}
RemoteDocumentKind.UPDATE -> {
if (
binding.isBlank() ||
action != null
) {
throw IllegalStateException(
"Обновление профиля неполное или относится к другому действию."
)
}
}
}
val workers = root.optJSONObject("limits")?.optInt("workers", 0)
?.takeIf {
it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
it % TUNNEL_WORKERS_PER_GROUP == 0
}
?: 0
val profileRevision = root.optLong("profile_revision", 0L).coerceAtLeast(0)
return RemoteDocumentDelivery(
document = document,
binding = binding,
continuation = RemoteContinuation(
available = available,
key = key.takeIf { available }.orEmpty(),
url = url.takeIf { available }.orEmpty(),
expiresAt = action?.optLong("expires", 0L) ?: 0L,
message = action?.optString("message").orEmpty().trim()
),
access = RemoteAccessCapability(
available = accessAvailable,
key = accessKey.takeIf { accessAvailable }.orEmpty(),
url = accessUrl.takeIf { accessAvailable }.orEmpty(),
binding = accessBinding.takeIf { accessAvailable }.orEmpty(),
initialStatus = initialAccessStatus.takeIf { accessAvailable },
cachedAction = cachedAction.takeIf { accessAvailable }
?: CachedRemoteAction.Unavailable,
exchange = exchange.takeIf { accessAvailable }
?: RemoteProfileExchange.Unavailable,
),
kind = kind,
profileMaxWorkers = workers,
profileRevision = profileRevision,
)
}
internal fun parseFailure(body: String): Pair<String, RemoteDocumentFailureAction?> {
if (body.length > MAX_RESPONSE_CHARS) return "" to null
val root = runCatching { JSONObject(body) }.getOrNull() ?: return "" to null
val detail = root.optString("detail").trim().take(600)
val source = root.optJSONObject("action") ?: return detail to null
if (!source.optBoolean("available", false)) return detail to null
val label = source.optString("label").trim().take(120)
val primary = source.optString("url").trim()
val fallback = source.optString("fallback").trim()
val handler = source.optString("handler").trim()
val alternatesSource = source.optJSONArray("alternate_handlers") ?: JSONArray()
if (alternatesSource.length() > 8) return detail to null
val alternates = buildList {
repeat(alternatesSource.length()) { index ->
val value = alternatesSource.optString(index).trim()
if (!safePackageName(value)) return detail to null
add(value)
}
}.distinct()
val valid = label.isNotBlank() &&
safeExternalUrl(primary) &&
(fallback.isBlank() || safeExternalUrl(fallback)) &&
(handler.isBlank() || safePackageName(handler))
if (!valid) return detail to null
return detail to RemoteDocumentFailureAction(
label = label,
target = RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
alternateHandlers = alternates,
),
)
}
private fun safeServiceUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return trustedServiceUri(uri) &&
uri.rawQuery.isNullOrBlank() &&
uri.rawFragment.isNullOrBlank()
}
internal fun parseCachedAction(source: JSONObject): CachedRemoteAction {
val payload = source.optString("payload").trim()
val primary = source.optString("url").trim()
val fallback = source.optString("fallback").trim()
val handler = source.optString("handler").trim()
val available = source.optBoolean("available", false) &&
opaquePayload(payload) &&
safeExternalUrl(primary) &&
(fallback.isBlank() || safeExternalUrl(fallback)) &&
(handler.isBlank() || safePackageName(handler))
if (!available) return CachedRemoteAction.Unavailable
return CachedRemoteAction(
available = true,
payload = payload,
target = RemoteLaunchTarget(
primaryUrl = primary,
fallbackUrl = fallback,
preferredHandler = handler,
),
title = source.optString("title").trim().take(120),
message = source.optString("message").trim().take(600),
label = source.optString("label").trim().take(120),
clipboardLabel = source.optString("clipboard_label").trim().take(120),
copiedMessage = source.optString("copied_message").trim().take(240),
failedMessage = source.optString("failed_message").trim().take(240),
helpTitle = source.optString("help_title").trim().take(120),
helpIntro = source.optString("help_intro").trim().take(600),
helpSteps = source.optString("help_steps").trim().take(1200),
)
}
internal fun parseProfileExchange(source: JSONObject): RemoteProfileExchange {
val submit = source.optJSONObject("submit")
val action = source.optJSONObject("action")
val submitToken = submit?.optString("token").orEmpty().trim()
val actionToken = action?.optString("token").orEmpty().trim()
val submitAvailable =
submit?.optBoolean("available", false) == true && opaqueValue(submitToken)
val label = action?.optString("label").orEmpty().trim().take(80)
val message = action?.optString("message").orEmpty().trim().take(300)
val actionAvailable =
action?.optBoolean("available", false) == true &&
opaqueValue(actionToken) &&
label.isNotBlank()
return if (submitAvailable || opaqueValue(actionToken)) {
RemoteProfileExchange(
submitAvailable = submitAvailable,
submitToken = submitToken.takeIf { submitAvailable }.orEmpty(),
actionAvailable = actionAvailable,
actionToken = actionToken.takeIf(::opaqueValue).orEmpty(),
label = label,
message = message,
)
} else {
RemoteProfileExchange.Unavailable
}
}
private fun safeExternalUrl(value: String): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
return uri.scheme.equals("https", ignoreCase = true) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
}
private fun safePackageName(value: String): Boolean =
value.length in 3..255 &&
Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$").matches(value)
private fun opaquePayload(value: String): Boolean =
value.length in 24..512 && Regex("^[A-Za-z0-9._-]+$").matches(value)
private fun trustedServiceUri(uri: URI): Boolean =
uri.scheme.equals("https", ignoreCase = true) &&
uri.host.equals(BuildConfig.WDTT_PLUS_DOMAIN, ignoreCase = true) &&
uri.rawUserInfo.isNullOrBlank() &&
(uri.port == -1 || uri.port == 443)
private fun opaqueValue(value: String): Boolean =
value.length in 24..256 && Regex("^[A-Za-z0-9_-]+$").matches(value)
private fun validDevice(value: String): Boolean =
Regex("^[A-Za-z0-9_.:-]{8,128}$").matches(value.trim())
private fun readBody(connection: HttpURLConnection, status: Int): String {
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
return stream?.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }.orEmpty()
}
}
@@ -12,6 +12,11 @@ import javax.crypto.spec.GCMParameterSpec
class SecureStringStore(context: Context) {
private val appContext = context.applicationContext
private val decryptedCache = object : LinkedHashMap<String, String>(32, 0.75f, true) {
override fun removeEldestEntry(
eldest: MutableMap.MutableEntry<String, String>?
): Boolean = size > 64
}
companion object {
private const val KEY_ALIAS = "wdtt.settings.secrets"
@@ -29,14 +34,21 @@ class SecureStringStore(context: Context) {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())
val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
return VERSION_PREFIX +
val encoded = VERSION_PREFIX +
Base64.encodeToString(cipher.iv, Base64.NO_WRAP) +
":" +
Base64.encodeToString(encrypted, Base64.NO_WRAP)
synchronized(decryptedCache) {
decryptedCache[encoded] = value
}
return encoded
}
fun decrypt(value: String?): String? {
if (value.isNullOrBlank() || !value.startsWith(VERSION_PREFIX)) return null
synchronized(decryptedCache) {
decryptedCache[value]?.let { return it }
}
val payload = value.removePrefix(VERSION_PREFIX)
val parts = payload.split(":", limit = 2)
if (parts.size != 2) return null
@@ -47,7 +59,11 @@ class SecureStringStore(context: Context) {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
cipher.doFinal(encrypted).toString(Charsets.UTF_8)
}.getOrNull()
}.getOrNull()?.also { decrypted ->
synchronized(decryptedCache) {
decryptedCache[value] = decrypted
}
}
}
private fun getOrCreateKey(): SecretKey {
@@ -21,7 +21,7 @@ data class ServerAdminProfileInfo(
val vkHashes: String = "",
val secondaryVkHash: String = "",
val profileName: String = "",
val workersPerHash: Int = 16,
val workersPerHash: Int = 18,
val protocol: String = "udp",
val listenPort: Int = 9000,
val sni: String = "",
@@ -42,6 +42,7 @@ data class ServerAdminState(
val maxPasswords: Int,
val passwordCount: Int,
val deviceCount: Int,
val ownerDeviceCount: Int,
val expiredCount: Int,
val orphanDeviceCount: Int,
val orphanDevices: List<ServerDeviceInfo>,
@@ -393,6 +394,13 @@ object ServerAdminClient {
maxPasswords = server.optInt("max_passwords", 50),
passwordCount = server.optInt("password_count", clients.size),
deviceCount = server.optInt("device_count", 0),
ownerDeviceCount = server.optInt(
"owner_device_count",
server.optJSONObject("admin_profile")
?.optJSONArray("device_ids")
?.length()
?: 0
),
expiredCount = server.optInt("expired_count", 0),
orphanDeviceCount = server.optInt("orphan_device_count", 0),
orphanDevices = buildList {
@@ -423,7 +431,7 @@ object ServerAdminClient {
vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(),
secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(),
profileName = vpnProfileRestorableName(json?.optString("profile_name", "").orEmpty()),
workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128),
workersPerHash = (json?.optInt("workers_per_hash", 18) ?: 18).coerceIn(1, 128),
protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
listenPort = listenPort,
sni = json?.optString("sni", "").orEmpty().trim(),
@@ -565,7 +573,7 @@ internal fun buildAdminProfilePatchArgs(profile: ServerAdminProfileInfo): List<S
add("--profile-name")
add(it)
}
profile.workersPerHash.coerceIn(1, 128).takeIf { it != 16 }?.let {
profile.workersPerHash.coerceIn(1, 128).takeIf { it != 18 }?.let {
add("--workers")
add(it.toString())
}
@@ -655,7 +663,8 @@ fun buildServerConnectionLink(
publicHost: String,
profileName: String = ""
): String? {
if (hashes.isBlank() || password.isBlank()) return null
if (password.isBlank()) return null
val normalizedHashes = VkJoinLink.normalizeHashes(hashes) ?: return null
val parts = ports.split(",").map { it.trim().toIntOrNull() }
if (parts.size != 3) return null
val dtls = parts[0]?.takeIf { it in 1..65535 } ?: return null
@@ -670,7 +679,7 @@ fun buildServerConnectionLink(
wgPort = wg,
localPort = local,
password = password,
hashes = hashes,
hashes = normalizedHashes,
profileName = profileName
)
)
@@ -1,7 +1,7 @@
package com.wdtt.plus
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7)
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12)
data class ServerMigrationState(
val pendingLevel: Int,
File diff suppressed because it is too large. Load diff
@@ -45,6 +45,12 @@ object WdttTransferCodec {
normalizeVpnProfileName(parts.profileName)
.takeIf { it.isNotBlank() }
?.let { values["name"] = it }
parts.maxWorkers
.takeIf {
it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
it % TUNNEL_WORKERS_PER_GROUP == 0
}
?.let { values["max_workers"] = it.toString() }
return "wdtt://connect?" + values.entries.joinToString("&") { (key, value) ->
"${encode(key)}=${encode(value)}"
}
@@ -66,6 +72,12 @@ object WdttTransferCodec {
}
.toMap()
if (values["v"] != "1") return null
val maxWorkers = values["max_workers"]?.takeIf { it.isNotBlank() }?.let { raw ->
raw.toIntOrNull()?.takeIf {
it in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
it % TUNNEL_WORKERS_PER_GROUP == 0
} ?: return null
} ?: 0
return WdttLinkParts(
host = values["host"].orEmpty(),
dtlsPort = values["dtls"]?.toIntOrNull() ?: return null,
@@ -73,7 +85,8 @@ object WdttTransferCodec {
localPort = values["local"]?.toIntOrNull() ?: return null,
password = values["password"].orEmpty(),
hashes = values["hashes"].orEmpty(),
profileName = values["name"].orEmpty()
profileName = values["name"].orEmpty(),
maxWorkers = maxWorkers
)
}
@@ -13,6 +13,7 @@ import android.provider.Settings
import androidx.core.content.ContextCompat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.util.concurrent.ConcurrentHashMap
private const val UNKNOWN_WIFI_SSID = "<unknown ssid>"
private const val BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION"
@@ -23,6 +24,50 @@ data class TrustedWifiRuntimeState(
val status: String = ""
)
internal data class TrustedWifiResumeRetryPlan(
val delayMs: Long,
val keepCpuAwake: Boolean
)
internal fun trustedWifiResumeRetryPlan(retryCount: Int): TrustedWifiResumeRetryPlan =
if (retryCount.coerceAtLeast(0) < 12) {
TrustedWifiResumeRetryPlan(delayMs = 5_000L, keepCpuAwake = true)
} else {
TrustedWifiResumeRetryPlan(delayMs = 30_000L, keepCpuAwake = false)
}
internal class TrustedWifiValidatedNetworkTracker<T : Any> {
private val validatedNetworks = ConcurrentHashMap.newKeySet<T>()
private val wifiNetworks = ConcurrentHashMap.newKeySet<T>()
@Synchronized
fun update(network: T, validated: Boolean, wifi: Boolean) {
if (validated) validatedNetworks.add(network) else validatedNetworks.remove(network)
if (wifi) wifiNetworks.add(network) else wifiNetworks.remove(network)
}
@Synchronized
fun lost(network: T) {
validatedNetworks.remove(network)
wifiNetworks.remove(network)
}
@Synchronized
fun forgetWifi() {
wifiNetworks.forEach { network -> validatedNetworks.remove(network) }
wifiNetworks.clear()
}
@Synchronized
fun hasUsableNetwork(): Boolean = validatedNetworks.isNotEmpty()
@Synchronized
fun clear() {
validatedNetworks.clear()
wifiNetworks.clear()
}
}
object TrustedWifiManager {
private val _state = MutableStateFlow(TrustedWifiRuntimeState())
val state = _state.asStateFlow()
+504 -64
View File
@@ -40,19 +40,35 @@ data class LogEntry(
val isError: Boolean get() = severity == LogSeverity.Error
}
@Stable
enum class ConnectionIssueKind {
GENERAL,
ACCESS,
}
@Stable
data class ConnectionIssue(
val title: String,
val action: String,
val isError: Boolean = true
val isError: Boolean = true,
val kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL,
)
internal val ConnectionIssue.isStandaloneUiIssue: Boolean
get() = kind != ConnectionIssueKind.ACCESS
enum class NetworkRecoveryAction {
SoftRestart,
RecreateVpn,
StopVpn
}
internal fun stableNetworkRecoveryAction(completedAttempts: Int): NetworkRecoveryAction = when {
completedAttempts <= 0 -> NetworkRecoveryAction.SoftRestart
completedAttempts == 1 -> NetworkRecoveryAction.RecreateVpn
else -> NetworkRecoveryAction.StopVpn
}
enum class TunnelStopReason(val displayText: String) {
User("отключено пользователем"),
VpnSlotTransferred("VPN-слот передан другому приложению"),
@@ -64,7 +80,14 @@ enum class TunnelStopReason(val displayText: String) {
CaptchaCancelled("проверка отменена пользователем"),
TrustedWifi("подключена доверенная сеть Wi-Fi"),
RestoreFailed("не удалось восстановить VPN"),
ServiceDestroyed("служба VPN остановлена системой")
ServiceDestroyed("служба VPN остановлена системой"),
AccessExpired("срок доступа закончился")
}
enum class TunnelTransition {
IDLE,
STARTING,
STOPPING,
}
private val stoppedStatsTrafficPairRegex = Regex(
@@ -121,6 +144,13 @@ internal fun classifyRecoverableWorkerRetry(
}
}
internal fun isExpiredAccessAuthFailure(line: String): Boolean =
line.contains("DENIED:expired", ignoreCase = true) ||
line.contains("срок действия пароля истёк", ignoreCase = true)
internal const val WRAP_HANDSHAKE_RETRY_MESSAGE =
"[WRAP] Отдельные каналы не ответили, выполняется повтор"
const val AMNEZIA_STYLE_RECOVERY = true
private const val RECOVERABLE_NETWORK_GRACE_MS = 90_000L
private const val HARD_NETWORK_GRACE_MS = 30_000L
@@ -177,6 +207,8 @@ object TunnelManager {
var isLoggingEnabled = true
val running = MutableStateFlow(false)
val transition = MutableStateFlow(TunnelTransition.IDLE)
val activeTunnelProfile = MutableStateFlow<Int?>(null)
val logs = MutableStateFlow<List<LogEntry>>(emptyList())
val unreadErrorCount = MutableStateFlow(0)
val config = MutableStateFlow<String?>(null)
@@ -192,16 +224,45 @@ object TunnelManager {
unreadErrorCount.value = 0
}
fun clearConnectionIssue() {
connectionIssue.value = null
fun noteStartRequested() {
transition.value = TunnelTransition.STARTING
}
private fun setConnectionIssue(title: String, action: String, isError: Boolean = true) {
connectionIssue.value = ConnectionIssue(title = title, action = action, isError = isError)
fun noteStopRequested() {
transition.value = TunnelTransition.STOPPING
}
fun reportConnectionIssue(title: String, action: String, isError: Boolean = true) {
setConnectionIssue(title, action, isError)
fun clearTransition() {
transition.value = TunnelTransition.IDLE
}
fun clearConnectionIssue(kind: ConnectionIssueKind? = null) {
if (kind == null || connectionIssue.value?.kind == kind) {
connectionIssue.value = null
}
}
private fun setConnectionIssue(
title: String,
action: String,
isError: Boolean = true,
kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL,
) {
connectionIssue.value = ConnectionIssue(
title = title,
action = action,
isError = isError,
kind = kind,
)
}
fun reportConnectionIssue(
title: String,
action: String,
isError: Boolean = true,
kind: ConnectionIssueKind = ConnectionIssueKind.GENERAL,
) {
setConnectionIssue(title, action, isError, kind)
}
fun isCaptchaInProgress(): Boolean =
@@ -427,12 +488,23 @@ object TunnelManager {
if (now - lastRecoveryAtMs < STABLE_RECOVERY_RETRY_MS) return null
lastRecoveryAtMs = now
val action = stableNetworkRecoveryAction(recoveryAttempts)
recoveryAttempts++
setConnectionIssue(
"Восстанавливаю транспорт",
"Сеть долго не подаёт признаков жизни. Выполняется одна мягкая попытка без пересоздания VPN."
)
return NetworkRecoveryAction.SoftRestart
when (action) {
NetworkRecoveryAction.SoftRestart -> setConnectionIssue(
"Восстанавливаю транспорт",
"Сеть долго не подаёт признаков жизни. Выполняется тихая попытка без пересоздания VPN."
)
NetworkRecoveryAction.RecreateVpn -> setConnectionIssue(
"Пересоздаю VPN",
"Тихое восстановление не помогло. Системный VPN-интерфейс будет пересоздан один раз."
)
NetworkRecoveryAction.StopVpn -> setConnectionIssue(
"VPN остановлен, чтобы вернуть интернет",
"Пересоздание VPN не восстановило связь. WDTT Plus выключит VPN, чтобы телефон не остался без интернета."
)
}
return action
}
private fun buildDeviceInfoJson(context: Context): String {
@@ -461,6 +533,7 @@ object TunnelManager {
}
private var observersInitialized = false
private var accessRefreshRequestedForProcess = false
fun initObservers(context: Context) {
if (observersInitialized) return
@@ -494,6 +567,26 @@ object TunnelManager {
updateLog("deploy_ok_$hash", message, 2, false)
}
fun noteTrustedWifiEvent(key: String, message: String, warning: Boolean = false) {
val logKey = "trusted_wifi_$key"
val text = "[ДОВЕРЕННЫЙ WI-FI] $message"
if (warning) {
updateWarningLog(logKey, text, 2)
} else {
updateLog(logKey, text, 2, false)
}
}
fun noteAccessLifecycleEvent(key: String, message: String, warning: Boolean = false) {
val logKey = "access_$key"
val text = "[ДОСТУП] $message"
if (warning) {
updateWarningLog(logKey, text, 20)
} else {
updateLog(logKey, text, 20, false)
}
}
private fun updateLog(key: String, message: String, priority: Int, isError: Boolean = false) {
if (!isLoggingEnabled) return
val severity = if (isError) LogSeverity.Error else LogSeverity.Info
@@ -546,16 +639,25 @@ object TunnelManager {
}
}
fun start(context: Context, params: TunnelParams, isSwitching: Boolean = false) {
fun start(
context: Context,
params: TunnelParams,
isSwitching: Boolean = false,
preserveLogs: Boolean = false
) {
if (!isSwitching) noteStartRequested()
scope.launch {
startStopMutex.lock()
try {
if (running.value && !isSwitching) return@launch
if (running.value && !isSwitching) {
clearTransition()
return@launch
}
val appContext = context.applicationContext // Защита от Memory Leak
if (!isSwitching) {
clearLogs()
if (!preserveLogs) clearLogs()
config.value = null
stats.value = "Ожидание данных..."
floodCount = 0
@@ -573,6 +675,7 @@ object TunnelManager {
activeHashIndex = 0
currentParams = params
lastContext = appContext
accessRefreshRequestedForProcess = false
forceRegenerateUA = false
currentCaptchaMode = params.captchaMode
currentCaptchaSolveMethod = params.captchaSolveMethod
@@ -581,6 +684,22 @@ object TunnelManager {
wgHelper = WireGuardHelper(appContext)
val targetHash = if (activeHashIndex == 0) params.vkHashes else params.secondaryVkHash
val customCredentials = CustomVkClientCredentials(
enabled = params.customVkCredentialsEnabled,
clientId = params.customVkClientId,
clientSecret = params.customVkClientSecret
)
customVkCredentialsError(customCredentials)?.let { error ->
updateLog("custom_vk_credentials_error", "Ошибка: пользовательские реквизиты VK не заполнены", 99, true)
setConnectionIssue(
"Не заполнены реквизиты VK",
"$error Откройте «Настройки → Клиент ID» или выключите пользовательский режим."
)
running.value = false
currentParams = null
return@launch
}
// Robust hash parsing: split by comma, newline, or whitespace
val hashList = targetHash
@@ -607,7 +726,10 @@ object TunnelManager {
}
val hashCount = hashList.size.coerceIn(1, 4)
val totalWorkers = params.workersPerHash.coerceIn(1, 128)
val totalWorkers = normalizeTunnelWorkerCount(
requested = params.workersPerHash,
profileMaxWorkers = params.profileMaxWorkers
)
val hashMode = if (activeHashIndex == 0) "Основной" else "Запасной"
updateLog("config_info", "[$hashMode] Хешей=$hashCount, Потоков=$totalWorkers", 1)
@@ -644,7 +766,7 @@ object TunnelManager {
// stops flag.Parse and silently drops every argument after it.
cmd.add("-vkcalls-preflight=${params.vkCallsPreflight}")
val androidId = android.provider.Settings.Secure.getString(context.contentResolver, android.provider.Settings.Secure.ANDROID_ID) ?: "unknown"
val androidId = SettingsStore(appContext).getOrCreateTunnelDeviceId()
cmd.add("-device-id")
cmd.add(androidId)
cmd.add("-device-info")
@@ -653,6 +775,15 @@ object TunnelManager {
cmd.add("-password")
cmd.add(params.connectionPassword)
if (
params.managedConfigFirstStart &&
params.profileMaxWorkers == TUNNEL_WORKERS_PER_GROUP &&
totalWorkers == TUNNEL_WORKERS_PER_GROUP
) {
cmd.add("-config-first-start=true")
cmd.add("-hash-fallback=true")
}
cmd.add("-captcha-mode")
cmd.add(params.captchaMode)
@@ -662,12 +793,20 @@ object TunnelManager {
val env = pb.environment()
env["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir
if (params.customVkCredentialsEnabled) {
env["WDTT_CUSTOM_VK_CLIENT_ID"] = params.customVkClientId
env["WDTT_CUSTOM_VK_CLIENT_SECRET"] = params.customVkClientSecret
} else {
env.remove("WDTT_CUSTOM_VK_CLIENT_ID")
env.remove("WDTT_CUSTOM_VK_CLIENT_SECRET")
}
process = pb.start()
processStartedAtMs = System.currentTimeMillis()
wrapAuthTimeoutCount = 0
resetStatsLivenessState()
running.value = true
clearTransition()
startLogReader()
startWatchdog(appContext, params)
@@ -678,7 +817,9 @@ object TunnelManager {
e.printStackTrace()
running.value = false
currentParams = null
clearTransition()
} finally {
if (!isSwitching) clearTransition()
startStopMutex.unlock()
}
}
@@ -707,6 +848,26 @@ object TunnelManager {
val msgPrefixReplaced = line.replace(Regex("^\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?\\s"), "")
val lineTrim = msgPrefixReplaced.trim()
if (lineTrim.contains("[МОЩНОСТЬ] Лимит временно занят", true)) {
updateLog(
"worker_policy_wait",
"[МОЩНОСТЬ] Свободные потоки этого профиля временно заняты; повторяем подключение автоматически",
20,
false
)
return@forEachLine
}
if (lineTrim.contains("[МОЩНОСТЬ] Сервер остановил лишний поток", true)) {
updateLog(
"worker_policy_limit",
"[МОЩНОСТЬ] Лишние потоки остановлены согласно ограничению этого доступа; подключение продолжает работать",
20,
false
)
return@forEachLine
}
val isCaptchaV2FallbackStatus = lineTrim.contains("[КАПЧА] v2", true) &&
(
lineTrim.contains("fallback продолжит", true) ||
@@ -719,7 +880,8 @@ object TunnelManager {
(
lineTrim.contains("preflight не сработал", true) ||
lineTrim.contains("временно ограничил", true) ||
lineTrim.contains("временно пропущен", true)
lineTrim.contains("временно пропущен", true) ||
lineTrim.contains("пробуем совместимый резерв", true)
)
val isError = !isCaptchaV2FallbackStatus && !isCaptchaProtocolResult && !isVkCallsFallback && (
lineTrim.contains("Ошибка", true) ||
@@ -739,7 +901,7 @@ object TunnelManager {
wrapAuthTimeoutCount = 0
updateLog(
"wrap_timeout_recovered",
"[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем",
WRAP_HANDSHAKE_RETRY_MESSAGE,
20,
false
)
@@ -747,31 +909,68 @@ object TunnelManager {
wrapAuthTimeoutCount++
updateWarningLog(
"wrap_timeout_wait",
"[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)",
WRAP_HANDSHAKE_RETRY_MESSAGE,
50
)
}
return@forEachLine
}
val accessExpired = isExpiredAccessAuthFailure(lineTrim)
val reason = when {
lineTrim.contains("неверный пароль") -> "Неверный пароль подключения"
lineTrim.contains("истёк") -> "Срок действия пароля истёк"
accessExpired -> "Срок действия пароля истёк"
lineTrim.contains("другому устройству") -> "Пароль привязан к другому устройству"
else -> "Ошибка авторизации"
}
val action = when {
lineTrim.contains("неверный пароль") ->
"Проверьте пароль в «Секретах» или вставьте актуальную wdtt:// ссылку."
lineTrim.contains("истёк") ->
"Создайте новый пароль у администратора или продлите текущий в Telegram-боте."
accessExpired ->
"Откройте профиль, чтобы проверить срок и доступные действия."
lineTrim.contains("другому устройству") ->
"Этот пароль уже закреплён за другим устройством. Отвяжите устройство в Telegram-боте или создайте новый пароль."
(
"Этот пароль уже закреплён за другим устройством. " +
"Запросите отвязку или новый профиль у поставщика."
)
else ->
"Проверьте пароль, VK-хеш и состояние сервера, затем попробуйте подключиться снова."
}
setConnectionIssue(reason, action)
handleCriticalError("\uD83D\uDD12 $reason. Воркеры остановлены.")
setConnectionIssue(
reason,
action,
kind = if (accessExpired) {
ConnectionIssueKind.ACCESS
} else {
ConnectionIssueKind.GENERAL
},
)
if (accessExpired) {
updateLog(
"access_expired",
"[ДОСТУП] Срок действия профиля закончился. Откройте вкладку «Туннель», чтобы проверить доступные действия.",
20,
true,
)
val accessContext = lastContext
val accessProfile = currentParams?.profileIndex
if (accessContext != null && accessProfile != null) {
scope.launch {
AccessLifecycleCoordinator.noteServerDenied(
accessContext,
accessProfile,
)
}
}
}
handleCriticalError(
"\uD83D\uDD12 $reason. Воркеры остановлены.",
if (accessExpired) {
TunnelStopReason.AccessExpired
} else {
TunnelStopReason.CriticalError
},
)
return@forEachLine
}
@@ -802,7 +1001,7 @@ object TunnelManager {
wrapAuthTimeoutCount = 0
updateLog(
"wrap_timeout_recovered",
"[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем",
WRAP_HANDSHAKE_RETRY_MESSAGE,
20,
false
)
@@ -810,7 +1009,7 @@ object TunnelManager {
wrapAuthTimeoutCount++
updateWarningLog(
"wrap_timeout_wait",
"[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)",
WRAP_HANDSHAKE_RETRY_MESSAGE,
50
)
}
@@ -827,7 +1026,7 @@ object TunnelManager {
val redirectUri = parts[2]
val sessionToken = parts[3]
scope.launch {
handleCaptchaSolve(requestId, requestMode, redirectUri, sessionToken)
handleCaptchaSolve(observedProcess, requestId, requestMode, redirectUri, sessionToken)
}
}
3 -> {
@@ -835,18 +1034,18 @@ object TunnelManager {
val redirectUri = parts[1]
val sessionToken = parts[2]
scope.launch {
handleCaptchaSolve("", requestMode, redirectUri, sessionToken)
handleCaptchaSolve(observedProcess, "", requestMode, redirectUri, sessionToken)
}
}
2 -> {
val redirectUri = parts[0]
val sessionToken = parts[1]
scope.launch {
handleCaptchaSolve("", "selected", redirectUri, sessionToken)
handleCaptchaSolve(observedProcess, "", "selected", redirectUri, sessionToken)
}
}
else -> {
writeCaptchaResult("", "error:invalid CAPTCHA_SOLVE format")
writeCaptchaResult(observedProcess, "", "error:invalid CAPTCHA_SOLVE format")
}
}
return@forEachLine
@@ -912,6 +1111,19 @@ object TunnelManager {
}
if (active > 0) {
if (!accessRefreshRequestedForProcess) {
accessRefreshRequestedForProcess = true
val accessContext = lastContext
val accessProfile = currentParams?.profileIndex
if (accessContext != null && accessProfile != null) {
scope.launch {
AccessLifecycleCoordinator.refreshAfterSuccessfulConnect(
accessContext,
accessProfile,
)
}
}
}
lastActiveAtMs = now
wrapAuthTimeoutCount = 0
@@ -944,8 +1156,21 @@ object TunnelManager {
val workerRetry = classifyRecoverableWorkerRetry(lineTrim, activeWorkers.value)
when {
workerRetry != null ->
workerRetry != null -> {
if (activeWorkers.value <= 0) {
when (workerRetry.first) {
"worker_turn_allocate_retry" -> noteRecoverableNetworkIssue(
"TURN/UDP не отвечает",
"VK API выдал TURN-данные, но TURN Allocate не получил ответ. WDTT Plus попробует другие TURN-пути и повторы; если ошибка повторяется, оператор может ограничивать UDP/TURN."
)
"worker_dtls_retry" -> noteRecoverableNetworkIssue(
"VPS не отвечает на DTLS",
"TURN Allocate прошёл, но рукопожатие DTLS до сервера не завершилось. Проверьте порт сервера, доступность VPS и пароль подключения."
)
}
}
updateWarningLog(workerRetry.first, workerRetry.second, 20)
}
lineTrim.contains("[ВОРКЕР #", true) &&
lineTrim.contains("Невосстановимая TURN/STUN ошибка", true) ->
updateWarningLog(
@@ -953,22 +1178,100 @@ object TunnelManager {
"[TURN] Отдельные каналы завершили попытки подключения; остальные продолжают работу",
50
)
lineTrim.contains("[DNS]", true) -> {
val text = lineTrim.substringAfter("[DNS]").trim()
when {
text.contains("Прямой DNS клиента недоступен", true) &&
text.contains("системный DNS", true) -> {
noteRecoverableNetworkIssue(
"Прямой DNS клиента недоступен",
"Оператор не ответил на прямые DNS-запросы клиента. WDTT Plus использует системный DNS устройства для этого запуска."
)
updateWarningLog(
"dns_system_fallback",
"[DNS] Прямой DNS клиента недоступен, используем системный DNS устройства",
20
)
}
text.contains("DNS до VK недоступен", true) -> {
noteRecoverableNetworkIssue(
"DNS до VK недоступен",
"Прямой DNS клиента и системный DNS устройства не ответили. Проверьте Private DNS, сеть оператора или попробуйте другую сеть."
)
updateWarningLog("dns_vk_unavailable", "[DNS] DNS до VK недоступен", 99)
}
else -> updateLog("dns_status", "[DNS] $text", 2, false)
}
}
lineTrim.contains("[VKCalls]", true) -> {
when {
lineTrim.contains("TURN credentials получены", true) ->
updateLog("vkcalls_ok", "[VKCalls] Анонимные TURN-данные получены ✓", 2, false)
updateLog("vkcalls_ok", "[VKCalls] Основной бескапчевый провайдер сработал ✓", 2, false)
lineTrim.contains("preflight не сработал", true) ||
lineTrim.contains("временно ограничил", true) ||
lineTrim.contains("временно пропущен", true) ->
updateLog("vkcalls_fallback", "[VKCalls] Анонимный вход временно недоступен — используется капча", 20, false)
updateLog("vkcalls_fallback", "[VKCalls] Основной провайдер временно недоступен — пробуем legacy-резерв", 20, false)
lineTrim.contains("пробуем совместимый резерв", true) ->
updateLog("vkcalls_api_fallback", "[VKCalls] Основной API-домен не ответил — пробуем совместимый резерв", 20, false)
lineTrim.endsWith("[VKCalls] preflight", true) ->
updateLog("vkcalls_start", "[VKCalls] Пробуем анонимный вход...", 2, false)
updateLog("vkcalls_start", "[VKCalls] Пробуем основной бескапчевый провайдер...", 2, false)
else -> {
if (isError) updateWarningLog("vkcalls_status", lineTrim, 20)
else updateLog("vkcalls_status", lineTrim, 20, false)
}
}
}
lineTrim.contains("[VK Provider]", true) -> {
when {
lineTrim.contains("TURN-данные сохранены", true) -> {
val lifetime = lineTrim.substringAfter("сохранены на", "").trim()
updateLog(
"vk_provider_cache",
"[ВК] TURN-данные сохранены${lifetime.takeIf(String::isNotBlank)?.let { " на $it" }.orEmpty()}",
2,
false
)
}
lineTrim.contains("legacy-custom", true) && lineTrim.contains("успешно", true) ->
updateLog("vk_provider_custom", "[ВК] Собственный legacy Client ID сработал ✓", 5, false)
lineTrim.contains("legacy-custom", true) && lineTrim.contains("пробуем", true) ->
updateLog("vk_provider_custom", "[ВК] Пробуем собственный legacy Client ID...", 5, false)
lineTrim.contains("legacy-custom", true) && lineTrim.contains("CAPTCHA_WAIT_REQUIRED", true) ->
updateLog("vk_provider_custom_wait", "[КАПЧА] Собственный legacy-провайдер ждёт следующую безопасную попытку", 20, false)
lineTrim.contains("legacy-custom", true) && lineTrim.contains("не сработал", true) ->
updateLog("vk_provider_custom_fallback", "[ВК] Собственный legacy Client ID не сработал — пробуем встроенный резерв", 20, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("успешно", true) ->
updateLog("vk_provider_builtin", "[ВК] Встроенный legacy Client ID сработал ✓", 5, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("пробуем", true) ->
updateLog("vk_provider_builtin", "[ВК] Пробуем встроенный legacy Client ID...", 5, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("CAPTCHA_WAIT_REQUIRED", true) ->
updateLog("vk_provider_builtin_wait", "[КАПЧА] Встроенный legacy-провайдер ждёт следующую безопасную попытку", 20, false)
lineTrim.contains("legacy-built-in", true) && lineTrim.contains("не сработал", true) ->
updateLog("vk_provider_builtin_fallback", "[ВК] Этот встроенный Client ID не сработал — пробуем следующий", 20, false)
lineTrim.contains("modern-vkcalls", true) && lineTrim.contains("успешно", true) ->
updateLog("vk_provider_modern", "[ВК] Используется современный VKCalls ✓", 2, false)
else -> updateLog("vk_provider_status", lineTrim, 20, false)
}
}
lineTrim.contains("[VK Auth]", true) -> {
when {
lineTrim.contains("Using cached credentials", true) ->
updateLog("vk_credentials_cache", "[ВК] Используются ранее полученные TURN-данные", 2, false)
lineTrim.contains("Throttling", true) ->
updateLog("vk_credentials_throttle", "[ВК] Безопасная пауза между запросами к VK", 20, false)
lineTrim.contains("Credentials cache invalidated", true) ->
updateLog("vk_credentials_refresh", "[ВК] TURN-данные устарели — получаем свежие", 5, false)
lineTrim.contains("getCallPreview failed", true) ->
updateLog("vk_preview_optional", "[ВК] Предпросмотр legacy-звонка недоступен, продолжаем получение TURN-данных", 20, false)
lineTrim.contains("Rate limit detected", true) ->
updateLog("vk_legacy_rate_limit", "[ВК] Этот legacy Client ID временно ограничен — пробуем следующий", 20, false)
lineTrim.contains("Все legacy-провайдеры", true) ->
updateLog("vk_legacy_retry", "[ВК] Legacy-провайдеры временно не ответили — выполняется безопасный повтор", 20, false)
else -> {
if (isError) updateWarningLog("vk_auth_status", lineTrim, 20)
}
}
}
lineTrim.contains("[КАПЧА] AUTO:") -> {
var text = lineTrim.substringAfter("[КАПЧА] AUTO:").trim()
text = text.replace(Regex("\\s*\\([^)]+\\)\\s*"), " ").trim()
@@ -1109,15 +1412,26 @@ object TunnelManager {
val errorKey = when {
isHardNetworkFailure(lineTrim) -> "err_hard_network"
isLocalDnsRefused(lineTrim) -> "err_local_dns_refused"
lineTrim.contains("lookup login.vk.ru", true) -> "err_vk_dns"
lineTrim.contains("lookup ", true) &&
(
lineTrim.contains("login.vk.ru", true) ||
lineTrim.contains("api.vk.ru", true) ||
lineTrim.contains("api.vk.me", true) ||
lineTrim.contains("calls.okcdn.ru", true)
) -> "err_vk_dns"
lineTrim.contains("VK HTTPS", true) -> "err_vk_https"
lineTrim.contains("connection refused") -> "err_conn_refused"
lineTrim.contains("timeout") -> "err_timeout"
lineTrim.contains("кредов") -> "err_creds"
lineTrim.contains("DTLS") -> "err_dtls"
else -> "general_error_" + lineTrim.take(15).hashCode()
}
val failedVkHost = listOf("login.vk.ru", "api.vk.ru", "api.vk.me", "calls.okcdn.ru")
.firstOrNull { lineTrim.contains(it, true) }
val errorMessage = if (errorKey == "err_vk_dns") {
"[СЕТЬ] DNS до VK недоступен: login.vk.ru"
"[СЕТЬ] DNS до VK недоступен: ${failedVkHost ?: "VK/OK"}"
} else if (errorKey == "err_vk_https") {
"[VK] HTTPS до VK/OK не отвечает"
} else {
lineTrim
}
@@ -1138,6 +1452,11 @@ object TunnelManager {
"DNS до VK недоступен",
"WDTT Plus попробует восстановить транспорт автоматически. Если не восстановится, проверьте интернет без VPN и DNS на устройстве."
)
} else if (errorKey == "err_vk_https") {
noteRecoverableNetworkIssue(
"HTTPS до VK/OK не отвечает",
"DNS сработал, но HTTPS-запрос к VK/OK не завершился. WDTT Plus попробует восстановить транспорт; если повторяется, проверьте ограничения сети оператора."
)
} else if (errorKey == "err_timeout" || errorKey == "err_conn_refused") {
noteRecoverableNetworkIssue(
"Транспорт не отвечает",
@@ -1148,6 +1467,7 @@ object TunnelManager {
"err_hard_network",
"err_local_dns_refused",
"err_vk_dns",
"err_vk_https",
"err_conn_refused",
"err_timeout",
"err_creds"
@@ -1205,12 +1525,15 @@ object TunnelManager {
}
}
private fun handleCriticalError(message: String) {
private fun handleCriticalError(
message: String,
stopReason: TunnelStopReason = TunnelStopReason.CriticalError,
) {
if (connectionIssue.value == null) {
setConnectionIssue("Подключение остановлено", "$message Проверьте настройки и попробуйте снова.")
}
updateLog("circuit_breaker", "[СТОП] $message", -1, true)
stop(TunnelStopReason.CriticalError)
stop(stopReason)
}
private fun handleHashError() {
@@ -1332,14 +1655,78 @@ object TunnelManager {
updateLog("network_restart", reason, 50, false)
activeWorkers.value = 0
resetStatsLivenessState()
killProcess()
val restartDelayMs = transportRecoveryPolicy(
params.managedConfigFirstStart
).processRestartDelayMs
scope.launch {
delay(2500)
start(context, params, isSwitching = true)
killProcess()
delay(restartDelayMs)
if (currentParams === params && running.value) {
start(context, params, isSwitching = true)
}
}
return true
}
internal fun applyUpdatedProfileConfiguration(
context: Context,
params: TunnelParams,
restartTransport: Boolean,
): TunnelProfileRuntimeApplyResult {
val previous = currentParams ?: return TunnelProfileRuntimeApplyResult.INACTIVE
if (!running.value || previous.profileIndex != params.profileIndex) {
return TunnelProfileRuntimeApplyResult.INACTIVE
}
if (!tunnelProfileRuntimeConfigurationChanged(previous, params)) {
return TunnelProfileRuntimeApplyResult.UNCHANGED
}
val appContext = context.applicationContext
currentParams = params
lastContext = appContext
activeHashIndex = 0
currentHashErrorCount = 0
wrapAuthTimeoutCount = 0
currentCaptchaMode = params.captchaMode
currentCaptchaSolveMethod = params.captchaSolveMethod
accessRefreshRequestedForProcess = false
resetNetworkRecoveryState()
resetStatsLivenessState()
clearConnectionIssue(ConnectionIssueKind.GENERAL)
activeWorkers.value = 0
if (!restartTransport) {
updateLog(
"profile_runtime_update_pending",
"[ПРОФИЛЬ] Новые параметры сохранены и будут применены при возобновлении VPN.",
20,
false,
)
return TunnelProfileRuntimeApplyResult.STORED_FOR_RESUME
}
updateLog(
"profile_runtime_update",
"[ПРОФИЛЬ] Параметры активного подключения обновлены. Мягко переподключаю транспорт.",
20,
false,
)
scope.launch {
startStopMutex.lock()
try {
if (currentParams !== params || !running.value) return@launch
killProcess()
delay(250L)
} finally {
startStopMutex.unlock()
}
if (currentParams === params && running.value) {
start(appContext, params, isSwitching = true, preserveLogs = true)
}
}
return TunnelProfileRuntimeApplyResult.RESTARTED
}
fun noteUnderlyingNetworkChanged(
reason: String,
graceMs: Long = RECOVERABLE_NETWORK_GRACE_MS,
@@ -1503,8 +1890,15 @@ object TunnelManager {
val proc = process
process = null
if (proc != null) {
try { proc.destroy() } catch (_: Exception) {}
try { proc.waitFor(500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
try {
proc.outputStream.write("STOP\n".toByteArray(Charsets.UTF_8))
proc.outputStream.flush()
} catch (_: Exception) {}
try { proc.waitFor(1500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
if (proc.isAlive) {
try { proc.destroy() } catch (_: Exception) {}
try { proc.waitFor(750, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
}
if (proc.isAlive) {
try { proc.destroyForcibly() } catch (_: Exception) {}
try { proc.waitFor(1000, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
@@ -1525,6 +1919,7 @@ object TunnelManager {
}
fun onWireGuardStoppedExternally() {
noteStopRequested()
scope.launch {
startStopMutex.lock()
try {
@@ -1542,12 +1937,14 @@ object TunnelManager {
currentParams = null
ManlCaptchaWebViewManager.cancelCaptcha()
} finally {
clearTransition()
startStopMutex.unlock()
}
}
}
fun stop(reason: TunnelStopReason = TunnelStopReason.User) {
noteStopRequested()
scope.launch {
startStopMutex.lock()
try {
@@ -1563,28 +1960,45 @@ object TunnelManager {
resetNetworkRecoveryState()
ManlCaptchaWebViewManager.cancelCaptcha()
} finally {
if (reason == TunnelStopReason.User) {
startCooldown(1500L)
}
clearTransition()
startStopMutex.unlock()
}
}
}
suspend fun stopAndWait(reason: TunnelStopReason = TunnelStopReason.User) {
suspend fun stopAndWait(
reason: TunnelStopReason = TunnelStopReason.User,
context: Context? = null,
forceVpnRelease: Boolean = false,
) {
noteStopRequested()
startStopMutex.lock()
try {
if (!running.value && currentParams == null) return
val hadManagedSession = running.value || currentParams != null || process != null
if (!hadManagedSession && !forceVpnRelease) return
val stopHelper = wgHelper ?: context?.applicationContext?.let(::WireGuardHelper)
withContext(Dispatchers.Main) {
wgHelper?.stopTunnel()
stopHelper?.stopTunnel()
}
withContext(Dispatchers.IO) {
killProcess()
running.value = false
markLogSessionStopped(reason)
if (hadManagedSession) {
markLogSessionStopped(reason)
}
resetStatsLivenessState()
currentParams = null
resetNetworkRecoveryState()
ManlCaptchaWebViewManager.cancelCaptcha()
}
} finally {
if (reason == TunnelStopReason.User) {
startCooldown(1500L)
}
clearTransition()
startStopMutex.unlock()
}
}
@@ -1597,9 +2011,15 @@ object TunnelManager {
}
}
private suspend fun handleCaptchaSolve(requestId: String, requestMode: String, redirectUri: String, sessionToken: String) {
private suspend fun handleCaptchaSolve(
expectedProcess: Process,
requestId: String,
requestMode: String,
redirectUri: String,
sessionToken: String
) {
val ctx = lastContext ?: run {
writeCaptchaResult(requestId, "error:context is null")
writeCaptchaResult(expectedProcess, requestId, "error:context is null")
return
}
val mode = requestMode.lowercase()
@@ -1622,7 +2042,7 @@ object TunnelManager {
}
}
updateLog("captcha_wv_step_4", "[КАПЧА WBV] Капча решена ✓", 5, false)
writeCaptchaResult(requestId, token)
writeCaptchaResult(expectedProcess, requestId, token)
} catch (e: IllegalStateException) {
val errorMsg = e.message ?: "WV state error"
val autoFallback = mode == "auto" && (
@@ -1636,23 +2056,23 @@ object TunnelManager {
} else {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] $errorMsg", 5)
}
writeCaptchaResult(requestId, "error:$errorMsg")
writeCaptchaResult(expectedProcess, requestId, "error:$errorMsg")
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
if (mode == "auto") {
updateLog("captcha_wv_timeout", "[КАПЧА WBV] Авто WebView не успел, идём дальше", 5, false)
} else {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] WebView не ответил вовремя", 5)
}
writeCaptchaResult(requestId, "error:timeout")
writeCaptchaResult(expectedProcess, requestId, "error:timeout")
} catch (e: kotlin.coroutines.cancellation.CancellationException) {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] Проверка отменена", 5)
writeCaptchaResult(requestId, "error:cancelled")
writeCaptchaResult(expectedProcess, requestId, "error:cancelled")
} catch (e: Exception) {
val errorMsg = e.message ?: "${e::class.simpleName}"
if (errorMsg != "tunnel stopped") {
updateWarningLog("captcha_wv_err", "[КАПЧА WBV] Текущая попытка не выполнена — $errorMsg", 5)
}
writeCaptchaResult(requestId, "error:$errorMsg")
writeCaptchaResult(expectedProcess, requestId, "error:$errorMsg")
} finally {
updateLog("captcha_wv_step_6", "[КАПЧА WBV] WebView уничтожен", 5, false)
endCaptchaSolve(captchaRequestId)
@@ -1701,16 +2121,23 @@ object TunnelManager {
return ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken)
}
private fun writeCaptchaResult(requestId: String, result: String) {
val proc = process
if (proc == null || !proc.isAlive) return
private fun writeCaptchaResult(expectedProcess: Process, requestId: String, result: String) {
if (process !== expectedProcess || !expectedProcess.isAlive) return
try {
val payload = if (requestId.isBlank()) result else "$requestId|$result"
val line = "CAPTCHA_RESULT|$payload\n"
proc.outputStream.write(line.toByteArray(Charsets.UTF_8))
proc.outputStream.flush()
expectedProcess.outputStream.write(line.toByteArray(Charsets.UTF_8))
expectedProcess.outputStream.flush()
} catch (e: Exception) {
updateLog("captcha_write_err", "[КАПЧА] Ошибка записи: ${e.message}", 200, true)
// Остановка туннеля может закрыть stdin между проверкой isAlive и записью.
// Это штатная гонка завершения, а не ошибка подключения пользователя.
if (process === expectedProcess && expectedProcess.isAlive) {
updateWarningLog(
"captcha_write_err",
"[КАПЧА] Нативный клиент не принял результат: ${e.message ?: e::class.simpleName}",
5
)
}
}
}
@@ -1749,5 +2176,18 @@ data class TunnelParams(
val captchaMode: String = "auto",
val captchaSolveMethod: String = "auto",
val fingerprint: String = "firefox",
val clientIds: String = "6287487,8202606"
val clientIds: String = DEFAULT_VK_CLIENT_IDS,
val customVkCredentialsEnabled: Boolean = false,
val customVkClientId: String = "",
val customVkClientSecret: String = "",
val profileMaxWorkers: Int = 0,
val managedConfigFirstStart: Boolean = false,
val profileIndex: Int = 0,
)
internal enum class TunnelProfileRuntimeApplyResult {
INACTIVE,
UNCHANGED,
STORED_FOR_RESUME,
RESTARTED,
}
@@ -0,0 +1,51 @@
package com.wdtt.plus
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
internal object TunnelProfileRuntimeUpdateBus {
private val mutableRequests = MutableSharedFlow<Int>(
extraBufferCapacity = 3,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
val requests = mutableRequests.asSharedFlow()
fun request(profileIndex: Int) {
if (profileIndex in 0..2) {
mutableRequests.tryEmit(profileIndex)
}
}
}
internal fun shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile: Int,
activeTunnelProfile: Int?,
tunnelRunning: Boolean,
trustedWifiWaiting: Boolean,
): Boolean =
updatedProfile in 0..2 &&
activeTunnelProfile == updatedProfile &&
(tunnelRunning || trustedWifiWaiting)
internal fun tunnelProfileRuntimeConfigurationChanged(
current: TunnelParams,
updated: TunnelParams,
): Boolean =
current.profileIndex == updated.profileIndex &&
current != updated
internal fun requestTunnelProfileRuntimeUpdate(profileIndex: Int) {
if (profileIndex !in 0..2) return
if (
!shouldRequestTunnelProfileRuntimeUpdate(
updatedProfile = profileIndex,
activeTunnelProfile = TunnelManager.activeTunnelProfile.value,
tunnelRunning = TunnelManager.running.value,
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
)
) {
return
}
TunnelProfileRuntimeUpdateBus.request(profileIndex)
}
+501 -95
View File
@@ -23,14 +23,18 @@ import androidx.core.app.NotificationCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4"
private const val TUNNEL_ALERT_CHANNEL_ID = "wdtt_tunnel_alert_v1"
@@ -39,33 +43,42 @@ private const val TUNNEL_ALERT_NOTIFICATION_ID = 2
private const val NETWORK_CHANGE_SETTLE_MS = 90_000L
private const val NETWORK_RETURN_SETTLE_MS = 45_000L
private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L
private const val STABLE_NETWORK_RECONNECT_DELAY_MS = 15_000L
private const val STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS = 2 * 60_000L
private const val WAKE_RESCUE_GRACE_MS = 60_000L
private const val WAKE_RESCUE_FAIL_OPEN_MS = 2 * 60_000L
private const val ACTIVE_PROFILE_REFRESH_INTERVAL_MS = 2 * 60_000L
private const val INITIAL_VPN_START_GRACE_MS = 90_000L
private const val TRUSTED_WIFI_ENTER_DELAY_MS = 2_000L
private const val TRUSTED_WIFI_EXIT_DELAY_MS = 5_000L
private const val TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT = 12
private const val TRUSTED_WIFI_SLOW_RESUME_RETRY_MS = 30_000L
private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_000L
private const val TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS = 75_000L
class TunnelService : Service() {
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val startRequestGate = TunnelStartRequestGate()
private var pendingStartJob: Job? = null
private var profileRuntimeUpdateJob: Job? = null
private var activeProfileRefreshJob: Job? = null
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var trustedWifiTransitionWakeLock: PowerManager.WakeLock? = null
private var updateJob: Job? = null
private var profileNameJob: Job? = null
private var networkChangeJob: Job? = null
private var lastNotificationTitle: String? = null
private var lastNotificationText: String? = null
private var notificationProfileTitle: String = "WDTT Plus"
private var connectionProfileIndex: Int? = null
private var profileStateJob: Job? = null
private var requestedStopReason: TunnelStopReason? = null
private var stopSequenceJob: Job? = null
private var intentionalStopCompleted = false
// Network Monitoring
private var connectivityManager: ConnectivityManager? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
private var lastNetworkChangeTime = 0L
private val activeNetworks = mutableSetOf<Network>()
private val activeNetworks = ConcurrentHashMap.newKeySet<Network>()
private val trustedWifiValidatedNetworks = TrustedWifiValidatedNetworkTracker<Network>()
private var isTunnelPaused = false
private var lastValidatedNetwork: Network? = null
private var lastStableNetworkReconnectAt = 0L
@@ -79,11 +92,15 @@ class TunnelService : Service() {
private val trustedWifiEvaluationScheduleLock = Any()
private var trustedWifiPendingEvaluationDelayMs: Long? = null
private var trustedWifiResumeRetryJob: Job? = null
private val trustedWifiResumeRetryLock = Any()
private var trustedWifiResumeRetryCount = 0
@Volatile
private var trustedWifiResumeInProgress = false
private var trustedWifiResumeStartedAt = 0L
private val trustedWifiTransitionMutex = Mutex()
@Volatile
private var trustedWifiWaiting = false
@Volatile
private var trustedWifiWaitingSsid = ""
private var lastStartParams: TunnelParams? = null
@@ -96,6 +113,9 @@ class TunnelService : Service() {
setupTrustedWifiMonitoring()
registerScreenStateReceiver()
registerTrustedWifiStateReceiver()
serviceScope.launch {
TunnelProfileRuntimeUpdateBus.requests.collect(::applyUpdatedTunnelProfile)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -113,7 +133,7 @@ class TunnelService : Service() {
peer = intent.getStringExtra("peer") ?: "",
vkHashes = intent.getStringExtra("vk_hashes") ?: "",
secondaryVkHash = intent.getStringExtra("secondary_vk_hash") ?: "",
workersPerHash = intent.getIntExtra("workers_per_hash", 16),
workersPerHash = intent.getIntExtra("workers_per_hash", 18),
port = intent.getIntExtra("port", 9000),
sni = intent.getStringExtra("sni") ?: "",
connectionPassword = intent.getStringExtra("connection_password") ?: "",
@@ -122,12 +142,16 @@ class TunnelService : Service() {
captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")),
captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto",
fingerprint = intent.getStringExtra("fingerprint") ?: "firefox",
clientIds = intent.getStringExtra("client_ids") ?: "6287487,8202606"
clientIds = intent.getStringExtra("client_ids") ?: DEFAULT_VK_CLIENT_IDS,
customVkCredentialsEnabled = intent.getBooleanExtra("custom_vk_credentials_enabled", false),
customVkClientId = intent.getStringExtra("custom_vk_client_id") ?: "",
customVkClientSecret = intent.getStringExtra("custom_vk_client_secret") ?: "",
profileMaxWorkers = intent.getIntExtra("profile_max_workers", 0),
managedConfigFirstStart =
intent.getBooleanExtra(MANAGED_CONFIG_FIRST_START_EXTRA, false),
profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2),
)
lastStartParams = params
TunnelManager.scope.launch(Dispatchers.Main) {
startOrWaitForTrustedWifi(params)
}
requestTunnelStart(params)
}
"STOP" -> stopTunnel(TunnelStopReason.User)
"DEPLOY_START" -> {
@@ -161,6 +185,9 @@ class TunnelService : Service() {
startPersistentForeground(createNotification("Проверка доверенной Wi-Fi сети..."))
startNotificationProfileWatcher()
startStatsUpdater()
acquireTrustedWifiTransitionWakeLock()
releaseWakeLock()
releaseWifiLock()
}
scheduleTrustedWifiEvaluation(delayMs = 0L)
}
@@ -171,44 +198,165 @@ class TunnelService : Service() {
private fun restoreTunnel() {
val notification = createNotification("Восстановление соединения...")
startPersistentForeground(notification)
val appContext = applicationContext
TunnelManager.scope.launch {
val generation = startRequestGate.next()
pendingStartJob?.cancel()
pendingStartJob = serviceScope.launch {
try {
val store = SettingsStore(appContext)
val params = buildTunnelParamsFromSettings(appContext)
val savedTunnelProfile = store.activeTunnelProfile.first()
val params = buildTunnelParamsFromSettings(appContext, savedTunnelProfile)
if (!startRequestGate.isCurrent(generation)) return@launch
if (params != null) {
launch(Dispatchers.Main) {
lastStartParams = params
val restoreWaiting = store.trustedWifiEnabled.first() && store.trustedWifiWaiting.first()
if (restoreWaiting) {
trustedWifiWaiting = true
trustedWifiWaitingSsid = store.trustedWifiWaitingSsid.first()
TrustedWifiManager.setWaiting(trustedWifiWaitingSsid)
startNotificationProfileWatcher()
startStatsUpdater()
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
startOrWaitForTrustedWifi(params)
}
val access = AccessLifecycleCoordinator.prepareStart(
appContext,
params.profileIndex,
)
if (!startRequestGate.isCurrent(generation)) return@launch
if (access is AccessStartDecision.Denied) {
reportAccessDenied(access.status)
stopTunnel(TunnelStopReason.AccessExpired)
return@launch
}
val refreshedParams = buildTunnelParamsFromSettings(
appContext,
params.profileIndex,
)
if (refreshedParams == null) {
stopTunnel(TunnelStopReason.RestoreFailed)
return@launch
}
rememberConnectionProfile(
refreshedParams.profileIndex,
persist = savedTunnelProfile == null
)
lastStartParams = refreshedParams
val restoreWaiting = store.trustedWifiEnabled.first() &&
store.trustedWifiWaiting.first()
if (!startRequestGate.isCurrent(generation)) return@launch
if (restoreWaiting) {
trustedWifiWaiting = true
trustedWifiWaitingSsid = store.trustedWifiWaitingSsid.first()
if (!startRequestGate.isCurrent(generation)) return@launch
TrustedWifiManager.setWaiting(trustedWifiWaitingSsid)
TunnelManager.noteTrustedWifiEvent(
"waiting_restored",
"Android восстановил службу ожидания; проверяем текущую сеть."
)
startNotificationProfileWatcher()
startStatsUpdater()
acquireTrustedWifiTransitionWakeLock()
releaseWakeLock()
releaseWifiLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
startOrWaitForTrustedWifi(refreshedParams)
}
} else {
launch(Dispatchers.Main) {
stopTunnel(TunnelStopReason.RestoreFailed)
}
stopTunnel(TunnelStopReason.RestoreFailed)
}
} catch (e: Exception) {
launch(Dispatchers.Main) {
if (startRequestGate.isCurrent(generation)) {
stopTunnel(TunnelStopReason.RestoreFailed)
}
}
}
}
private fun requestTunnelStart(params: TunnelParams) {
val generation = startRequestGate.next()
pendingStartJob?.cancel()
pendingStartJob = serviceScope.launch {
val access = withContext(Dispatchers.IO) {
AccessLifecycleCoordinator.prepareStart(
applicationContext,
params.profileIndex,
)
}
if (!startRequestGate.isCurrent(generation)) return@launch
when (access) {
AccessStartDecision.Allowed -> {
val refreshedParams = withContext(Dispatchers.IO) {
buildTunnelParamsFromSettings(
applicationContext,
params.profileIndex,
)
}
if (refreshedParams == null) {
stopTunnel(TunnelStopReason.RestoreFailed)
return@launch
}
rememberConnectionProfile(refreshedParams.profileIndex)
lastStartParams = refreshedParams
startOrWaitForTrustedWifi(refreshedParams)
}
is AccessStartDecision.Denied -> {
reportAccessDenied(access.status)
stopTunnel(TunnelStopReason.AccessExpired)
}
}
}
}
private fun applyUpdatedTunnelProfile(profileIndex: Int) {
if (profileIndex !in 0..2) return
val activeProfile = connectionProfileIndex
?: TunnelManager.activeTunnelProfile.value
?: return
if (activeProfile != profileIndex) return
profileRuntimeUpdateJob?.cancel()
profileRuntimeUpdateJob = serviceScope.launch {
val refreshedParams = withContext(Dispatchers.IO) {
buildTunnelParamsFromSettings(
applicationContext,
profileIndex,
)
}
if (refreshedParams == null) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profileIndex}_runtime_update_invalid",
message = "Новые параметры профиля пока не удалось применить",
warning = true,
)
return@launch
}
lastStartParams = refreshedParams
if (trustedWifiWaiting) {
TunnelManager.noteAccessLifecycleEvent(
key = "profile_${profileIndex}_runtime_update_waiting",
message = "Новые параметры будут применены после выхода из доверенной сети",
warning = false,
)
return@launch
}
when (
TunnelManager.applyUpdatedProfileConfiguration(
context = applicationContext,
params = refreshedParams,
restartTransport = !isTunnelPaused,
)
) {
TunnelProfileRuntimeApplyResult.RESTARTED ->
updateNotification("Обновление подключения...")
TunnelProfileRuntimeApplyResult.STORED_FOR_RESUME ->
updateNotification("Ожидание сети")
TunnelProfileRuntimeApplyResult.INACTIVE,
TunnelProfileRuntimeApplyResult.UNCHANGED -> Unit
}
}
}
private fun invalidatePendingStart() {
startRequestGate.invalidate()
pendingStartJob?.cancel()
pendingStartJob = null
}
private fun startTunnel(params: TunnelParams, fromTrustedWifiResume: Boolean = false) {
trustedWifiResumeRetryJob?.cancel()
trustedWifiResumeRetryJob = null
trustedWifiResumeRetryCount = 0
cancelTrustedWifiResumeRetry(resetCount = !fromTrustedWifiResume)
trustedWifiResumeInProgress = fromTrustedWifiResume
trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L
trustedWifiWaiting = false
@@ -222,35 +370,48 @@ class TunnelService : Service() {
updateNotification("Подключение...")
acquireWakeLock()
acquireWifiLock()
releaseTrustedWifiTransitionWakeLock()
// Подготавливаем CaptchaWebViewManager (не создаёт WebView — просто сохраняет контекст)
// Вызываем всегда — дёшево, а WebView создаётся на лету при каждом запросе капчи
CaptchaWebViewManager.onTunnelStart(applicationContext)
TunnelManager.start(this, params)
if (fromTrustedWifiResume) {
TunnelManager.noteTrustedWifiEvent(
"resume_start",
"Рабочая сеть подтверждена — запускаем VPN после доверенной Wi-Fi."
)
}
TunnelManager.start(this, params, preserveLogs = fromTrustedWifiResume)
startNotificationProfileWatcher()
startStatsUpdater()
startActiveProfileRefresh(params.profileIndex)
}
private fun stopTunnel(reason: TunnelStopReason = TunnelStopReason.User) {
TunnelManager.noteStopRequested()
if (stopSequenceJob?.isActive == true) return
invalidatePendingStart()
val effectiveReason = requestedStopReason ?: reason
requestedStopReason = effectiveReason
updateJob?.cancel()
profileNameJob?.cancel()
activeProfileRefreshJob?.cancel()
networkChangeJob?.cancel()
wakeRescueJob?.cancel()
trustedWifiResumeRetryJob?.cancel()
cancelTrustedWifiResumeRetry(resetCount = true)
profileNameJob = null
activeProfileRefreshJob = null
networkChangeJob = null
wakeRescueJob = null
trustedWifiResumeRetryJob = null
trustedWifiResumeRetryCount = 0
trustedWifiResumeInProgress = false
trustedWifiResumeStartedAt = 0L
releaseTrustedWifiTransitionWakeLock()
cancelTrustedWifiEvaluations()
trustedWifiWaiting = false
trustedWifiWaitingSsid = ""
lastStartParams = null
forgetConnectionProfile()
TrustedWifiManager.clear()
TunnelManager.scope.launch {
SettingsStore(applicationContext).saveTrustedWifiWaiting(false)
@@ -259,30 +420,39 @@ class TunnelService : Service() {
// Уничтожаем текущий WebView (если капча решается) и чистим контекст
CaptchaWebViewManager.onTunnelStop()
TunnelManager.stop(effectiveReason)
releaseWakeLock()
releaseWifiLock()
lastValidatedNetwork = null
lastStableNetworkReconnectAt = 0L
stableNetworkWasLost = false
activeNetworks.clear()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
trustedWifiValidatedNetworks.clear()
updateNotification("Отключение…")
// Служба должна жить до фактической остановки WireGuard и нативного клиента.
// Иначе быстрый повторный тап создаёт новую службу, пока прежний транспорт
// ещё завершается, а onDestroy ошибочно записывает системную остановку.
stopSequenceJob = serviceScope.launch {
try {
TunnelManager.stopAndWait(effectiveReason)
} finally {
intentionalStopCompleted = true
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
}
private fun startNotificationProfileWatcher() {
profileNameJob?.cancel()
val settingsStore = SettingsStore(applicationContext)
profileNameJob = TunnelManager.scope.launch(Dispatchers.Main) {
combine(
settingsStore.activeProfile,
settingsStore.profileNames
) { activeProfile, profileNames ->
val profile = activeProfile.coerceIn(0, 2)
val profile = connectionProfileIndex
?: settingsStore.activeTunnelProfile.first()
?: settingsStore.activeProfile.first().coerceIn(0, 2)
settingsStore.profileNames.collect { profileNames ->
val profileLabel = vpnProfileDisplayName(profile, profileNames)
"WDTT Plus · $profileLabel"
}.collect { prefix ->
notificationProfileTitle = prefix
notificationProfileTitle = "WDTT Plus · $profileLabel"
if (trustedWifiWaiting) {
updateTrustedWifiNotification()
} else if (TunnelManager.running.value && !isTunnelPaused) {
@@ -292,6 +462,50 @@ class TunnelService : Service() {
}
}
private fun startActiveProfileRefresh(profileIndex: Int) {
activeProfileRefreshJob?.cancel()
activeProfileRefreshJob = serviceScope.launch(Dispatchers.IO) {
while (isActive) {
delay(ACTIVE_PROFILE_REFRESH_INTERVAL_MS)
if (
connectionProfileIndex != profileIndex ||
!TunnelManager.running.value ||
isTunnelPaused ||
trustedWifiWaiting ||
TunnelManager.isCaptchaInProgress() ||
!hasAnyRealNetwork()
) {
continue
}
AccessLifecycleCoordinator.refreshProfile(
context = applicationContext,
profileIndex = profileIndex,
force = true,
)
}
}
}
private fun rememberConnectionProfile(profile: Int, persist: Boolean = true) {
val normalized = profile.coerceIn(0, 2)
connectionProfileIndex = normalized
TunnelManager.activeTunnelProfile.value = normalized
if (!persist) return
profileStateJob?.cancel()
profileStateJob = TunnelManager.scope.launch {
SettingsStore(applicationContext).saveActiveTunnelProfile(normalized)
}
}
private fun forgetConnectionProfile() {
connectionProfileIndex = null
TunnelManager.activeTunnelProfile.value = null
profileStateJob?.cancel()
profileStateJob = TunnelManager.scope.launch {
SettingsStore(applicationContext).saveActiveTunnelProfile(null)
}
}
private fun registerScreenStateReceiver() {
if (screenStateReceiver != null) return
screenStateReceiver = object : BroadcastReceiver() {
@@ -340,6 +554,8 @@ class TunnelService : Service() {
WifiManager.WIFI_STATE_DISABLING,
WifiManager.WIFI_STATE_DISABLED,
WifiManager.WIFI_STATE_UNKNOWN -> {
trustedWifiValidatedNetworks.forgetWifi()
acquireTrustedWifiTransitionWakeLock()
keepTrustedWifiForeground("Ожидание рабочей сети")
scheduleTrustedWifiEvaluation(delayMs = 0L)
scheduleTrustedWifiResumeRetry()
@@ -349,7 +565,9 @@ class TunnelService : Service() {
}
WifiManager.NETWORK_STATE_CHANGED_ACTION -> {
keepTrustedWifiForeground()
scheduleTrustedWifiEvaluation(delayMs = 0L)
// Сам broadcast не содержит стабильного Network-идентификатора:
// при быстрой смене двух Wi-Fi он может относиться уже к старой сети.
// Авторитетные lost/validated события придут через NetworkCallback.
}
}
}
@@ -382,13 +600,23 @@ class TunnelService : Service() {
return@launch
}
TunnelManager.noteWakeRescueReconnect()
updateNotification("Восстановление VPN...")
if (TunnelManager.isNetworkTransitionGraceActive()) {
updateNotification(buildTunnelNotificationText())
return@launch
}
val reconnectAt = System.currentTimeMillis()
TunnelManager.restartTransport(
val restarted = TunnelManager.restartTransport(
reason = "[СОН] После пробуждения VPN не подал признаков жизни. Мягко переподключаю транспорт.",
minIntervalMs = 60_000L
)
if (!restarted) {
// Другая ветка восстановления уже перезапускает транспорт либо ещё действует
// её защитный интервал. Не запускаем параллельный таймер, который мог бы
// ошибочно остановить уже восстанавливающийся VPN.
updateNotification(buildTunnelNotificationText())
return@launch
}
updateNotification("Восстановление VPN...")
delay(WAKE_RESCUE_FAIL_OPEN_MS)
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
@@ -447,17 +675,30 @@ class TunnelService : Service() {
}
trustedWifiNetworkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS)
if (trustedWifiWaiting) {
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS)
}
}
override fun onLost(network: Network) {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
if (trustedWifiWaiting) {
trustedWifiValidatedNetworks.lost(network)
acquireTrustedWifiTransitionWakeLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
scheduleTrustedWifiResumeRetry()
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
}
}
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
scheduleTrustedWifiEvaluation(
if (trustedWifiWaiting) TRUSTED_WIFI_EXIT_DELAY_MS else TRUSTED_WIFI_ENTER_DELAY_MS
)
if (trustedWifiWaiting) {
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS)
}
}
}
val request = NetworkRequest.Builder()
@@ -521,21 +762,43 @@ class TunnelService : Service() {
}
private fun scheduleTrustedWifiResumeRetry() {
trustedWifiResumeRetryJob?.cancel()
val delayMs = if (trustedWifiResumeRetryCount < TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT) {
TRUSTED_WIFI_EXIT_DELAY_MS
} else {
TRUSTED_WIFI_SLOW_RESUME_RETRY_MS
}
trustedWifiResumeRetryCount += 1
trustedWifiResumeRetryJob = TunnelManager.scope.launch {
delay(delayMs)
if (trustedWifiWaiting) {
evaluateTrustedWifiState()
synchronized(trustedWifiResumeRetryLock) {
if (trustedWifiResumeRetryJob?.isActive == true) return
val plan = trustedWifiResumeRetryPlan(trustedWifiResumeRetryCount)
if (plan.keepCpuAwake) {
acquireTrustedWifiTransitionWakeLock()
} else {
releaseTrustedWifiTransitionWakeLock()
}
trustedWifiResumeRetryJob = TunnelManager.scope.launch {
delay(plan.delayMs)
val shouldEvaluate = synchronized(trustedWifiResumeRetryLock) {
trustedWifiResumeRetryJob = null
if (trustedWifiWaiting) {
trustedWifiResumeRetryCount += 1
true
} else {
false
}
}
if (shouldEvaluate) evaluateTrustedWifiState()
}
}
}
private fun cancelTrustedWifiResumeRetry(resetCount: Boolean) {
synchronized(trustedWifiResumeRetryLock) {
trustedWifiResumeRetryJob?.cancel()
trustedWifiResumeRetryJob = null
if (resetCount) trustedWifiResumeRetryCount = 0
}
}
private fun isTrustedWifiResumeRetryScheduled(): Boolean =
synchronized(trustedWifiResumeRetryLock) {
trustedWifiResumeRetryJob?.isActive == true
}
private suspend fun evaluateTrustedWifiState() {
if (DeployManager.isDeploying.value) return
val store = SettingsStore(applicationContext)
@@ -581,6 +844,11 @@ class TunnelService : Service() {
TrustedWifiManager.setWaiting(wifi.ssid)
store.saveTrustedWifiWaiting(true, wifi.ssid)
withContext(Dispatchers.Main) { updateTrustedWifiNotification() }
cancelTrustedWifiResumeRetry(resetCount = true)
releaseTrustedWifiTransitionWakeLock()
}
if (trustedWifiWaiting && !isTrustedWifiResumeRetryScheduled()) {
releaseTrustedWifiTransitionWakeLock()
}
}
}
@@ -597,17 +865,26 @@ class TunnelService : Service() {
trustedWifiWaiting = true
trustedWifiWaitingSsid = cleanSsid
isTunnelPaused = false
trustedWifiResumeRetryCount = 0
trustedWifiValidatedNetworks.forgetWifi()
networkChangeJob?.cancel()
wakeRescueJob?.cancel()
trustedWifiResumeRetryJob?.cancel()
trustedWifiResumeRetryJob = null
activeProfileRefreshJob?.cancel()
activeProfileRefreshJob = null
cancelTrustedWifiResumeRetry(resetCount = true)
// Авто-WebView может ещё решать капчу, когда нативный процесс уже
// останавливается. Завершаем его до закрытия stdin клиента.
CaptchaWebViewManager.onTunnelStop()
TunnelManager.stopAndWait(TunnelStopReason.TrustedWifi)
WireGuardHelper(applicationContext).stopTunnel()
TunnelManager.noteTrustedWifiEvent(
"waiting_enter",
"Подключена доверенная сеть — VPN остановлен и ждёт выхода из неё."
)
TrustedWifiManager.setWaiting(cleanSsid)
SettingsStore(applicationContext).saveTrustedWifiWaiting(true, cleanSsid)
withContext(Dispatchers.Main) {
releaseTrustedWifiTransitionWakeLock()
releaseWakeLock()
releaseWifiLock()
startNotificationProfileWatcher()
@@ -623,6 +900,10 @@ class TunnelService : Service() {
if (!trustedWifiWaiting) return
if (!hasUsableRealNetworkForTrustedWifiResume()) {
val status = "Ожидание рабочей сети"
TunnelManager.noteTrustedWifiEvent(
"resume_wait_network",
"Wi-Fi покинута, но Android ещё не подтвердил рабочую сеть; повторяем проверку."
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) {
keepTrustedWifiForeground(status)
@@ -633,6 +914,12 @@ class TunnelService : Service() {
}
if (android.net.VpnService.prepare(applicationContext) != null) {
val status = "VPN-разрешение недоступно. Откройте WDTT Plus для восстановления."
releaseTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_permission",
"Android не дал повторно занять VPN-слот; требуется открыть приложение.",
warning = true
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) { updateNotification(status) }
return
@@ -641,17 +928,54 @@ class TunnelService : Service() {
val params = lastStartParams ?: buildTunnelParamsFromSettings(applicationContext)
if (params == null) {
val status = "Не удалось прочитать профиль VPN. Откройте WDTT Plus."
releaseTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_profile",
"Не удалось прочитать профиль для автоматического запуска.",
warning = true
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) { updateNotification(status) }
return
}
val access = AccessLifecycleCoordinator.prepareStart(
applicationContext,
params.profileIndex,
)
if (access is AccessStartDecision.Denied) {
withContext(Dispatchers.Main) {
reportAccessDenied(access.status)
stopTunnel(TunnelStopReason.AccessExpired)
}
return
}
val refreshedParams = buildTunnelParamsFromSettings(
applicationContext,
params.profileIndex,
)
if (refreshedParams == null) {
val status = "Не удалось прочитать обновлённый профиль VPN. Откройте WDTT Plus."
releaseTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_profile_refresh",
"Не удалось повторно прочитать профиль после проверки перед запуском.",
warning = true,
)
TrustedWifiManager.setStatus(status)
withContext(Dispatchers.Main) { updateNotification(status) }
return
}
lastStartParams = refreshedParams
withContext(Dispatchers.Main) {
acquireTrustedWifiTransitionWakeLock()
Log.i("TunnelService", "Доверенная Wi-Fi покинута, запускаем VPN на рабочей сети")
// startTunnel синхронно включает защитный resumeInProgress до снятия waiting.
// Поэтому очередной сетевой callback уже не может оставить сервис между
// состояниями: без VPN, без ожидания и с удалённым уведомлением.
startTunnel(params, fromTrustedWifiResume = true)
startTunnel(refreshedParams, fromTrustedWifiResume = true)
VpnWidgetProvider.updateAllWidgets(applicationContext)
}
}
@@ -661,6 +985,23 @@ class TunnelService : Service() {
keepTrustedWifiForeground()
}
private fun reportAccessDenied(status: AccessLifecycleStatus) {
val title = status.title.ifBlank { "Профиль временно недоступен" }
val message = status.message.ifBlank {
"Откройте вкладку «Туннель», чтобы проверить доступные действия."
}
TunnelManager.reportConnectionIssue(
title,
message,
kind = ConnectionIssueKind.ACCESS,
)
TunnelManager.noteAccessLifecycleEvent(
key = "start_denied",
message = title,
warning = true,
)
}
private fun keepTrustedWifiForeground(statusOverride: String? = null) {
val networkName = trustedWifiWaitingSsid.ifBlank { "доверенная Wi-Fi" }
val text = statusOverride ?: "VPN выключен в сети «$networkName» · ожидание выхода"
@@ -673,6 +1014,7 @@ class TunnelService : Service() {
private fun setupNetworkCallback() {
connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
activeNetworks.clear()
trustedWifiValidatedNetworks.clear()
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
@@ -698,10 +1040,13 @@ class TunnelService : Service() {
override fun onLost(network: Network) {
super.onLost(network)
if (trustedWifiWaiting) {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
}
activeNetworks.remove(network)
trustedWifiValidatedNetworks.lost(network)
if (trustedWifiWaiting) {
acquireTrustedWifiTransitionWakeLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
scheduleTrustedWifiResumeRetry()
}
if (AMNEZIA_STYLE_RECOVERY) {
if (lastValidatedNetwork == network) {
lastValidatedNetwork = null
@@ -726,8 +1071,22 @@ class TunnelService : Service() {
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities)
val usableRealNetwork =
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
trustedWifiValidatedNetworks.update(
network = network,
validated = usableRealNetwork,
wifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
)
if (trustedWifiWaiting) {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
if (usableRealNetwork) {
acquireTrustedWifiTransitionWakeLock()
scheduleTrustedWifiEvaluation(delayMs = 0L)
} else {
scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS)
}
}
if (AMNEZIA_STYLE_RECOVERY) {
handleStableNetworkCapabilities(network, networkCapabilities)
@@ -772,7 +1131,9 @@ class TunnelService : Service() {
if (TunnelManager.running.value) {
TunnelManager.noteUnderlyingNetworkChanged(
"Android подтвердил рабочую сеть",
graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS,
graceMs = transportRecoveryPolicy(
lastStartParams?.managedConfigFirstStart == true
).networkSettleDelayMs,
replaceGrace = false
)
}
@@ -789,27 +1150,31 @@ class TunnelService : Service() {
lastNetworkChangeTime = now
if (!TunnelManager.running.value || isTunnelPaused) return
val recoveryPolicy = transportRecoveryPolicy(
lastStartParams?.managedConfigFirstStart == true
)
TunnelManager.noteUnderlyingNetworkChanged(
reason,
graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS + 30_000L,
graceMs = recoveryPolicy.networkSettleDelayMs + 30_000L,
replaceGrace = true
)
networkChangeJob?.cancel()
networkChangeJob = TunnelManager.scope.launch(Dispatchers.Main) {
Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect")
delay(STABLE_NETWORK_RECONNECT_DELAY_MS)
delay(recoveryPolicy.networkSettleDelayMs)
if (lastNetworkChangeTime != now) return@launch
if (!TunnelManager.running.value || !hasAnyRealNetwork() || TunnelManager.isCaptchaInProgress()) return@launch
val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt
if (sinceLastReconnect < STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS) {
if (sinceLastReconnect < recoveryPolicy.reconnectMinIntervalMs) {
Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был")
return@launch
}
lastStableNetworkReconnectAt = System.currentTimeMillis()
TunnelManager.restartTransport(
reason = "[СЕТЬ] Android подтвердил новую сеть. Мягко переподключаю транспорт.",
minIntervalMs = STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS
minIntervalMs = recoveryPolicy.reconnectMinIntervalMs,
force = recoveryPolicy.forceRestart,
)
}
}
@@ -827,16 +1192,7 @@ class TunnelService : Service() {
@Suppress("DEPRECATION")
private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean {
val cm = connectivityManager
?: (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).also {
connectivityManager = it
}
return cm.allNetworks.any { network ->
val caps = cm.getNetworkCapabilities(network) ?: return@any false
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
return trustedWifiValidatedNetworks.hasUsableNetwork()
}
private fun scheduleNetworkSettleCheck(
@@ -925,6 +1281,37 @@ class TunnelService : Service() {
}
}
@Synchronized
private fun acquireTrustedWifiTransitionWakeLock() {
val lock = trustedWifiTransitionWakeLock ?: run {
val pm = getSystemService(POWER_SERVICE) as PowerManager
pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"wdtt:trusted_wifi_transition"
).apply {
setReferenceCounted(false)
trustedWifiTransitionWakeLock = this
}
}
runCatching {
if (!lock.isHeld) {
lock.acquire(TRUSTED_WIFI_TRANSITION_WAKE_LOCK_TIMEOUT_MS)
}
}.onFailure {
Log.w("TunnelService", "Не удалось удержать CPU для выхода из доверенной Wi-Fi: ${it.message}")
}
}
@Synchronized
private fun releaseTrustedWifiTransitionWakeLock() {
trustedWifiTransitionWakeLock?.let { lock ->
runCatching {
if (lock.isHeld) lock.release()
}
}
trustedWifiTransitionWakeLock = null
}
@Suppress("DEPRECATION")
private fun acquireWifiLock() {
if (wifiLock?.isHeld == true) return
@@ -968,6 +1355,8 @@ class TunnelService : Service() {
TunnelManager.running.value -> {
trustedWifiResumeInProgress = false
trustedWifiResumeStartedAt = 0L
cancelTrustedWifiResumeRetry(resetCount = true)
releaseTrustedWifiTransitionWakeLock()
}
trustedWifiResumeStartedAt > 0L &&
System.currentTimeMillis() - trustedWifiResumeStartedAt >=
@@ -977,6 +1366,15 @@ class TunnelService : Service() {
trustedWifiWaiting = true
val status = "VPN не запустился, повторяем восстановление"
Log.w("TunnelService", status)
CaptchaWebViewManager.onTunnelStop()
releaseWakeLock()
releaseWifiLock()
acquireTrustedWifiTransitionWakeLock()
TunnelManager.noteTrustedWifiEvent(
"resume_timeout",
"Автоматический запуск не начался за 30 секунд; повторяем.",
warning = true
)
TrustedWifiManager.setWaiting("", status)
SettingsStore(applicationContext).saveTrustedWifiWaiting(true)
keepTrustedWifiForeground(status)
@@ -1169,6 +1567,10 @@ class TunnelService : Service() {
override fun onDestroy() {
super.onDestroy()
val stopReasonOnUnexpectedDestroy = requestedStopReason ?: TunnelStopReason.ServiceDestroyed
val stopWasCompleted = intentionalStopCompleted
invalidatePendingStart()
serviceScope.cancel()
wakeRescueJob?.cancel()
networkChangeJob?.cancel()
screenStateReceiver?.let {
@@ -1187,13 +1589,17 @@ class TunnelService : Service() {
}
trustedWifiSettingsJob?.cancel()
cancelTrustedWifiEvaluations()
trustedWifiResumeRetryJob?.cancel()
cancelTrustedWifiResumeRetry(resetCount = false)
releaseTrustedWifiTransitionWakeLock()
if (trustedWifiWaiting || trustedWifiResumeInProgress) {
releaseWakeLock()
releaseWifiLock()
TrustedWifiManager.setStatus("Служба ожидания будет восстановлена Android")
} else {
stopTunnel(TunnelStopReason.ServiceDestroyed)
} else if (!stopWasCompleted) {
CaptchaWebViewManager.onTunnelStop()
releaseWakeLock()
releaseWifiLock()
TunnelManager.stop(stopReasonOnUnexpectedDestroy)
}
}
@@ -2,62 +2,141 @@ package com.wdtt.plus
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.flow.first
suspend fun buildTunnelParamsFromSettings(context: Context): TunnelParams? {
internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index"
internal const val MANAGED_CONFIG_FIRST_START_EXTRA = "managed_config_first_start"
internal data class TransportRecoveryPolicy(
val networkSettleDelayMs: Long,
val reconnectMinIntervalMs: Long,
val processRestartDelayMs: Long,
val forceRestart: Boolean,
)
internal fun transportRecoveryPolicy(
managedConfigFirstStart: Boolean,
): TransportRecoveryPolicy = if (managedConfigFirstStart) {
TransportRecoveryPolicy(
networkSettleDelayMs = 3_000L,
reconnectMinIntervalMs = 8_000L,
processRestartDelayMs = 250L,
forceRestart = true,
)
} else {
TransportRecoveryPolicy(
networkSettleDelayMs = 15_000L,
reconnectMinIntervalMs = 2 * 60_000L,
processRestartDelayMs = 2_500L,
forceRestart = false,
)
}
internal enum class TunnelToggleAction {
START,
STOP,
REQUEST_VPN_PERMISSION,
}
internal fun tunnelToggleAction(
running: Boolean,
trustedWifiWaiting: Boolean,
vpnPermissionRequired: Boolean,
): TunnelToggleAction = when {
running || trustedWifiWaiting -> TunnelToggleAction.STOP
vpnPermissionRequired -> TunnelToggleAction.REQUEST_VPN_PERMISSION
else -> TunnelToggleAction.START
}
internal fun displayedTunnelProfile(
selectedProfile: Int,
activeTunnelProfile: Int?,
running: Boolean,
trustedWifiWaiting: Boolean,
): Int = if (running || trustedWifiWaiting) {
activeTunnelProfile ?: selectedProfile
} else {
selectedProfile
}.coerceIn(0, 2)
internal fun shouldUseManagedConfigFirstStart(
remoteManaged: Boolean,
profileMaxWorkers: Int,
): Boolean = remoteManaged && profileMaxWorkers == TUNNEL_WORKERS_PER_GROUP
suspend fun buildTunnelParamsFromSettings(
context: Context,
profileIndex: Int? = null,
): TunnelParams? {
val store = SettingsStore(context.applicationContext)
val linkMode = store.wdttLinkMode.first()
val workersPerHash = store.workersPerHash.first()
val sni = store.sni.first()
val protocol = store.protocol.first()
val vkCallsPreflight = store.vkCallsPreflight.first()
val captchaMode = sanitizeTunnelCaptchaMode(store.captchaMode.first())
val captchaSolveMethod = store.captchaSolveMethod.first()
val fingerprint = store.selectedFingerprint.first()
val clientIds = store.activeClientIds.first()
val saved = store.tunnelProfileSnapshot(profileIndex)
return buildTunnelParams(saved)
}
return if (linkMode) {
val parts = WdttDeepLink.validate(store.wdttLink.first()).parts ?: return null
internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
val workersPerHash = normalizeTunnelWorkerCount(
saved.workersPerHash,
saved.profileMaxWorkers
)
val managedConfigFirstStart = shouldUseManagedConfigFirstStart(
remoteManaged = saved.remoteManaged,
profileMaxWorkers = saved.profileMaxWorkers,
)
val linkParts = saved.link
.takeIf { saved.linkMode }
?.let { WdttDeepLink.validate(it).parts }
return if (linkParts != null) {
TunnelParams(
peer = "${parts.host}:${parts.dtlsPort}",
vkHashes = parts.hashes,
peer = "${linkParts.host}:${linkParts.dtlsPort}",
vkHashes = linkParts.hashes,
secondaryVkHash = "",
workersPerHash = workersPerHash,
port = parts.localPort,
sni = sni,
connectionPassword = parts.password,
protocol = protocol,
vkCallsPreflight = vkCallsPreflight,
captchaMode = captchaMode,
captchaSolveMethod = captchaSolveMethod,
fingerprint = fingerprint,
clientIds = clientIds
port = linkParts.localPort,
sni = saved.sni,
connectionPassword = linkParts.password,
protocol = saved.protocol,
vkCallsPreflight = saved.vkCallsPreflight,
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
captchaSolveMethod = saved.captchaSolveMethod,
fingerprint = saved.fingerprint,
clientIds = saved.clientIds,
customVkCredentialsEnabled = saved.customVkCredentialsEnabled,
customVkClientId = saved.customVkClientId,
customVkClientSecret = saved.customVkClientSecret,
profileMaxWorkers = saved.profileMaxWorkers,
managedConfigFirstStart = managedConfigFirstStart,
profileIndex = saved.profileIndex,
)
} else {
val basePeer = store.peer.first().trim()
val hashes = store.vkHashes.first().trim()
val password = store.connectionPassword.first()
val basePeer = saved.peer.trim()
val hashes = saved.vkHashes.trim()
val password = saved.connectionPassword
if (basePeer.isBlank() || hashes.isBlank() || password.isBlank()) return null
val manualPortsEnabled = store.manualPortsEnabled.first()
val serverDtlsPort = if (manualPortsEnabled) store.serverDtlsPort.first() else 56000
val localPort = if (manualPortsEnabled) store.listenPort.first() else 9000
val serverDtlsPort = if (saved.manualPortsEnabled) saved.serverDtlsPort else 56000
val localPort = if (saved.manualPortsEnabled) saved.listenPort else 9000
val peerWithPort = if (basePeer.contains(":")) basePeer else "$basePeer:$serverDtlsPort"
TunnelParams(
peer = peerWithPort,
vkHashes = hashes,
secondaryVkHash = store.secondaryVkHash.first(),
secondaryVkHash = saved.secondaryVkHash,
workersPerHash = workersPerHash,
port = localPort,
sni = sni,
sni = saved.sni,
connectionPassword = password,
protocol = protocol,
vkCallsPreflight = vkCallsPreflight,
captchaMode = captchaMode,
captchaSolveMethod = captchaSolveMethod,
fingerprint = fingerprint,
clientIds = clientIds
protocol = saved.protocol,
vkCallsPreflight = saved.vkCallsPreflight,
captchaMode = sanitizeTunnelCaptchaMode(saved.captchaMode),
captchaSolveMethod = saved.captchaSolveMethod,
fingerprint = saved.fingerprint,
clientIds = saved.clientIds,
customVkCredentialsEnabled = saved.customVkCredentialsEnabled,
customVkClientId = saved.customVkClientId,
customVkClientSecret = saved.customVkClientSecret,
profileMaxWorkers = saved.profileMaxWorkers,
managedConfigFirstStart = managedConfigFirstStart,
profileIndex = saved.profileIndex,
)
}
}
@@ -79,6 +158,12 @@ suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? {
putExtra("captcha_solve_method", params.captchaSolveMethod)
putExtra("fingerprint", params.fingerprint)
putExtra("client_ids", params.clientIds)
putExtra("custom_vk_credentials_enabled", params.customVkCredentialsEnabled)
putExtra("custom_vk_client_id", params.customVkClientId)
putExtra("custom_vk_client_secret", params.customVkClientSecret)
putExtra("profile_max_workers", params.profileMaxWorkers)
putExtra(MANAGED_CONFIG_FIRST_START_EXTRA, params.managedConfigFirstStart)
putExtra(TUNNEL_PROFILE_INDEX_EXTRA, params.profileIndex)
}
}
@@ -0,0 +1,20 @@
package com.wdtt.plus
/** Keeps delayed service starts from reviving an obsolete or explicitly stopped request. */
internal class TunnelStartRequestGate {
private var generation: Long = 0
@Synchronized
fun next(): Long {
generation += 1
return generation
}
@Synchronized
fun invalidate() {
generation += 1
}
@Synchronized
fun isCurrent(value: Long): Boolean = value == generation
}
@@ -0,0 +1,61 @@
package com.wdtt.plus
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
enum class TunnelStopResult {
ALREADY_STOPPED,
STOPPED,
TIMED_OUT,
FAILED;
val succeeded: Boolean
get() = this == ALREADY_STOPPED || this == STOPPED
}
object TunnelStopCoordinator {
const val DEFAULT_TIMEOUT_MS = 20_000L
const val DIRECT_NETWORK_SETTLE_MS = 1_000L
suspend fun stopAndAwait(
context: Context,
timeoutMs: Long = DEFAULT_TIMEOUT_MS,
): TunnelStopResult {
val appContext = context.applicationContext
val helper = WireGuardHelper(appContext)
val managerActive = TunnelManager.running.value ||
TunnelManager.transition.value != TunnelTransition.IDLE
val wireGuardActive = runCatching { helper.isTunnelUp() }.getOrDefault(false)
if (!managerActive && !wireGuardActive) return TunnelStopResult.ALREADY_STOPPED
val serviceRequested = runCatching {
appContext.startService(
Intent(appContext, TunnelService::class.java).apply { action = "STOP" }
)
}.isSuccess
if (!serviceRequested) return TunnelStopResult.FAILED
val stopped = withTimeoutOrNull(timeoutMs.coerceAtLeast(1_000L)) {
// The service owns foreground/lifecycle cleanup. Calling the manager as well makes
// this operation awaitable and repairs a stale `running=false` state with a live
// WireGuard tunnel. Both paths are idempotent behind the same start/stop mutex.
TunnelManager.stopAndWait(
reason = TunnelStopReason.User,
context = appContext,
forceVpnRelease = true,
)
while (
TunnelManager.running.value ||
TunnelManager.transition.value != TunnelTransition.IDLE ||
helper.isTunnelUp()
) {
delay(50L)
}
true
} == true
return if (stopped) TunnelStopResult.STOPPED else TunnelStopResult.TIMED_OUT
}
}
@@ -0,0 +1,14 @@
package com.wdtt.plus
internal const val TUNNEL_WORKERS_PER_GROUP = 9
internal const val APP_MAX_WORKERS = 108
internal fun normalizeTunnelWorkerCount(requested: Int, profileMaxWorkers: Int = 0): Int {
val configuredMaximum = (profileMaxWorkers / TUNNEL_WORKERS_PER_GROUP) * TUNNEL_WORKERS_PER_GROUP
val maximum = configuredMaximum.takeIf { it >= TUNNEL_WORKERS_PER_GROUP }
?.coerceAtMost(APP_MAX_WORKERS)
?: APP_MAX_WORKERS
val rounded = ((requested.coerceAtLeast(TUNNEL_WORKERS_PER_GROUP) + TUNNEL_WORKERS_PER_GROUP / 2) /
TUNNEL_WORKERS_PER_GROUP) * TUNNEL_WORKERS_PER_GROUP
return rounded.coerceIn(TUNNEL_WORKERS_PER_GROUP, maximum)
}
@@ -0,0 +1,30 @@
package com.wdtt.plus
const val DEFAULT_VK_CLIENT_IDS = "6287487,8202606"
val BUILT_IN_VK_CLIENT_IDS: List<String> = DEFAULT_VK_CLIENT_IDS.split(',')
data class CustomVkClientCredentials(
val enabled: Boolean = false,
val clientId: String = "",
val clientSecret: String = ""
) {
val complete: Boolean
get() = isValidVkClientId(clientId) && clientSecret.isNotBlank()
}
fun normalizeVkClientId(value: String): String =
value.filter(Char::isDigit).take(20)
fun normalizeVkClientSecret(value: String): String =
value.trim().take(512)
fun isValidVkClientId(value: String): Boolean =
value.isNotBlank() && value.length <= 20 && value.all(Char::isDigit)
fun customVkCredentialsError(credentials: CustomVkClientCredentials): String? = when {
!credentials.enabled -> null
!isValidVkClientId(credentials.clientId) -> "Укажите числовой Client ID приложения VK."
credentials.clientSecret.isBlank() -> "Укажите защищённый ключ (Client secret) приложения VK."
else -> null
}
+28 -1
View File
@@ -1,6 +1,8 @@
package com.wdtt.plus
object VkJoinLink {
private val hashPattern = Regex("^[A-Za-z0-9_-]{1,512}$")
fun extractHash(input: String): String {
var s = input.trim().trim('<', '>', '"', '\'')
if (s.isBlank()) return ""
@@ -20,5 +22,30 @@ object VkJoinLink {
}
return s.trim().trimEnd('/')
}
}
fun isValidHash(value: String): Boolean = hashPattern.matches(value.trim())
fun isValidInput(input: String): Boolean {
val clean = input.trim().trim('<', '>', '"', '\'')
if (clean.isBlank()) return false
val isLink = clean.startsWith("http://", ignoreCase = true) ||
clean.startsWith("https://", ignoreCase = true)
return if (isLink) {
clean.contains("/call/join/", ignoreCase = true) &&
isValidHash(extractHash(clean))
} else {
isValidHash(clean)
}
}
fun normalizeHashes(input: String): String? {
if (input.isBlank()) return ""
val values = input.split(Regex("[,\\s]+"))
.filter { it.isNotBlank() }
if (values.isEmpty() || values.any { !isValidInput(it) }) return null
return values.map(::extractHash).distinct().joinToString(",")
}
fun extractValidHash(input: String): String =
extractHash(input).takeIf { isValidInput(input) }.orEmpty()
}
@@ -43,9 +43,24 @@ class VpnCompactWidgetProvider : AppWidgetProvider() {
val waiting = TrustedWifiManager.state.value.waiting
scope.launch {
val settingsStore = SettingsStore(context)
val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val selectedProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val activeTunnelProfile = TunnelManager.activeTunnelProfile.value
?: settingsStore.activeTunnelProfile.first()
val displayedProfile = displayedTunnelProfile(
selectedProfile = selectedProfile,
activeTunnelProfile = activeTunnelProfile,
running = running,
trustedWifiWaiting = waiting,
)
val profileNames = settingsStore.profileNames.first()
val profileName = vpnProfileDisplayName(activeProfile, profileNames)
val profileName = vpnProfileDisplayName(displayedProfile, profileNames)
val accessLifecycle =
settingsStore.accessLifecycleForProfile(displayedProfile).toUiState()
val accessBlocked =
accessLifecycle.managed &&
!accessLifecycle.allowConnect &&
!running &&
!waiting
appWidgetIds.forEach { appWidgetId ->
val views = RemoteViews(context.packageName, R.layout.vpn_widget_compact)
@@ -56,7 +71,12 @@ class VpnCompactWidgetProvider : AppWidgetProvider() {
)
views.setTextViewText(
R.id.compact_widget_profile,
if (waiting) "Ожидание" else profileName
when {
waiting -> "Ожидание"
accessBlocked ->
accessLifecycle.title.ifBlank { accessLifecycle.fallbackTitle() }
else -> profileName
}
)
val toggleIntent = Intent(context, VpnWidgetProvider::class.java).apply {
@@ -45,8 +45,18 @@ class VpnWidgetProvider : AppWidgetProvider() {
val trustedWifi = TrustedWifiManager.state.value
scope.launch {
val settingsStore = SettingsStore(context)
val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val selectedProfile = settingsStore.activeProfile.first().coerceIn(0, 2)
val activeTunnelProfile = TunnelManager.activeTunnelProfile.value
?: settingsStore.activeTunnelProfile.first()
val displayedProfile = displayedTunnelProfile(
selectedProfile = selectedProfile,
activeTunnelProfile = activeTunnelProfile,
running = running,
trustedWifiWaiting = trustedWifi.waiting,
)
val profileNames = settingsStore.profileNames.first()
val accessLifecycle =
settingsStore.accessLifecycleForProfile(displayedProfile).toUiState()
for (appWidgetId in appWidgetIds) {
updateWidgetState(
context = context,
@@ -54,8 +64,9 @@ class VpnWidgetProvider : AppWidgetProvider() {
appWidgetId = appWidgetId,
running = running,
trustedWifi = trustedWifi,
activeProfile = activeProfile,
profileNames = profileNames
activeProfile = displayedProfile,
profileNames = profileNames,
accessLifecycle = accessLifecycle,
)
}
}
@@ -65,38 +76,53 @@ class VpnWidgetProvider : AppWidgetProvider() {
super.onReceive(context, intent)
if (intent.action == ACTION_WIDGET_TOGGLE) {
runCatching {
if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) {
// Останавливаем туннель
val stopIntent = Intent(context, TunnelService::class.java).apply { action = "STOP" }
context.startService(stopIntent)
updateAllWidgets(context)
return
}
when (
tunnelToggleAction(
running = TunnelManager.running.value,
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
vpnPermissionRequired = VpnService.prepare(context) != null,
)
) {
TunnelToggleAction.STOP -> {
context.startService(
Intent(context, TunnelService::class.java).apply { action = "STOP" }
)
updateAllWidgets(context)
}
TunnelToggleAction.REQUEST_VPN_PERMISSION -> {
Toast.makeText(
context,
"Откройте WDTT Plus и выдайте VPN-разрешение",
Toast.LENGTH_LONG
).show()
openMainActivity(context)
}
TunnelToggleAction.START -> scope.launch {
try {
val startIntent = buildTunnelStartIntentFromSettings(context)
if (startIntent == null) {
Toast.makeText(
context,
"Заполните настройки подключения в WDTT Plus",
Toast.LENGTH_LONG
).show()
openMainActivity(context)
return@launch
}
if (VpnService.prepare(context) != null) {
Toast.makeText(context, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
openMainActivity(context)
return
}
// Запуск туннеля в фоне
scope.launch {
try {
val startIntent = buildTunnelStartIntentFromSettings(context)
if (startIntent == null) {
Toast.makeText(context, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show()
openMainActivity(context)
return@launch
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(startIntent)
} else {
context.startService(startIntent)
}
} catch (e: Exception) {
Log.e("VpnWidget", "Failed to start tunnel from widget", e)
Toast.makeText(
context,
"Ошибка запуска: ${e.localizedMessage}",
Toast.LENGTH_SHORT
).show()
}
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(startIntent)
} else {
context.startService(startIntent)
}
} catch (e: Exception) {
Log.e("VpnWidget", "Failed to start tunnel from widget", e)
Toast.makeText(context, "Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT).show()
}
}
}.onFailure { e ->
@@ -112,7 +138,8 @@ class VpnWidgetProvider : AppWidgetProvider() {
running: Boolean,
trustedWifi: TrustedWifiRuntimeState,
activeProfile: Int,
profileNames: List<String>
profileNames: List<String>,
accessLifecycle: AccessLifecycleUiState,
) {
val views = RemoteViews(context.packageName, R.layout.vpn_widget)
@@ -129,8 +156,24 @@ class VpnWidgetProvider : AppWidgetProvider() {
views.setTextColor(R.id.widget_status, 0xFF00E5FF.toInt()) // Неоновый голубой
views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_active)
} else {
views.setTextViewText(R.id.widget_status, "Отключено")
views.setTextColor(R.id.widget_status, 0xFF888888.toInt()) // Матовый серый
val accessBlocked = accessLifecycle.managed && !accessLifecycle.allowConnect
views.setTextViewText(
R.id.widget_status,
accessLifecycle.title.takeIf { accessBlocked && it.isNotBlank() }
?: accessLifecycle.fallbackTitle().takeIf { accessBlocked }
?: "Отключено"
)
views.setTextColor(
R.id.widget_status,
if (
accessLifecycle.severity == AccessLifecycleSeverity.ERROR &&
accessBlocked
) {
0xFFFF6B6B.toInt()
} else {
0xFF888888.toInt()
}
)
views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_inactive)
}
@@ -37,6 +37,12 @@ class WdttApplication : Application() {
}
val settingsStore = SettingsStore(this)
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
RemoteActionCatalogGateway.fetch(force = true)
}
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
AccessLifecycleCoordinator.refreshAllIfStale(this@WdttApplication)
}
// Реактивно обновляем виджеты при изменении туннеля, активного профиля или его названия.
CoroutineScope(SupervisorJob() + Dispatchers.Main).launch {
@@ -45,8 +51,9 @@ class WdttApplication : Application() {
TunnelManager.running,
TrustedWifiManager.state,
settingsStore.activeProfile,
settingsStore.profileNames
) { _, _, _, _ -> Unit }.collect {
settingsStore.profileNames,
settingsStore.activeAccessLifecycle
) { _, _, _, _, _ -> Unit }.collect {
VpnWidgetProvider.updateAllWidgets(this@WdttApplication)
}
} catch (e: Exception) {
@@ -0,0 +1,28 @@
package com.wdtt.plus
object WdttDocument {
const val MIME_TYPE = "application/vnd.wdtt.plus"
const val FILE_EXTENSION = ".wdtt"
const val LEGACY_TRANSFER_MIME_TYPE = "application/vnd.wdtt.plus.transfer"
const val LEGACY_CLIENT_MIME_TYPE = "application/vnd.wdtt.plus.client"
fun acceptedMimeTypes(): Array<String> = arrayOf(
MIME_TYPE,
LEGACY_TRANSFER_MIME_TYPE,
LEGACY_CLIENT_MIME_TYPE,
"application/json",
"application/octet-stream",
"text/plain",
)
fun isAcceptedMimeType(value: String?): Boolean {
val normalized = value?.substringBefore(';')?.trim()?.lowercase().orEmpty()
return acceptedMimeTypes().any { it == normalized }
}
fun fileName(stem: String): String {
val cleanStem = stem.trim().removeSuffix(FILE_EXTENSION).ifBlank { "WDTT-Plus" }
return cleanStem + FILE_EXTENSION
}
}
@@ -16,6 +16,7 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.ByteArrayInputStream
import java.security.MessageDigest
class WireGuardHelper(context: Context) {
private val appContext = context.applicationContext
@@ -24,6 +25,7 @@ class WireGuardHelper(context: Context) {
private companion object {
val wgMutex = Mutex()
var sharedTunnel: WgTunnel? = null
var sharedConfigFingerprint: String? = null
}
class WgTunnel(
@@ -38,6 +40,7 @@ class WireGuardHelper(context: Context) {
val isCurrentTunnel = sharedTunnel === this
if (isCurrentTunnel) {
sharedTunnel = null
sharedConfigFingerprint = null
}
if (isCurrentTunnel && !suppressDownCallback) {
onExternalDown?.invoke()
@@ -55,19 +58,6 @@ class WireGuardHelper(context: Context) {
throw IllegalStateException("VPN-разрешение не выдано")
}
ensureGoBackendServiceStarted()
sharedTunnel?.let { existingTunnel ->
try {
existingTunnel.suppressDownCallback = true
backend.setState(existingTunnel, Tunnel.State.DOWN, null)
} catch (e: Exception) {
Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}")
}
sharedTunnel = null
delay(150)
}
val parsedConfig = Config.parse(ByteArrayInputStream(configString.toByteArray(Charsets.UTF_8)))
val builder = Interface.Builder()
@@ -132,11 +122,42 @@ class WireGuardHelper(context: Context) {
.addPeer(peerBuilder.build())
.build()
sharedTunnel?.let { existingTunnel ->
val existingUp = runCatching {
backend.getState(existingTunnel) == Tunnel.State.UP
}.getOrDefault(false)
if (
shouldReuseRunningWireGuard(
tunnelUp = existingUp,
currentConfigFingerprint = sharedConfigFingerprint,
updatedConfig = finalConfig,
)
) {
Log.d("WG", "WireGuard config unchanged; keeping the current VPN interface")
return@withContext
}
}
ensureGoBackendServiceStarted()
sharedTunnel?.let { existingTunnel ->
try {
existingTunnel.suppressDownCallback = true
backend.setState(existingTunnel, Tunnel.State.DOWN, null)
} catch (e: Exception) {
Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}")
}
sharedTunnel = null
sharedConfigFingerprint = null
delay(150)
}
val nextTunnel = WgTunnel {
TunnelManager.onWireGuardStoppedExternally()
}
setTunnelUpWithRetry(nextTunnel, finalConfig)
sharedTunnel = nextTunnel
sharedConfigFingerprint = wireGuardConfigFingerprint(finalConfig)
Log.d("WG", "WireGuard tunnel started successfully")
} catch (e: Exception) {
val detailed = "WireGuard start failed: ${e.readableMessage()}; ${configString.describeWireGuardConfig()}"
@@ -154,6 +175,7 @@ class WireGuardHelper(context: Context) {
currentTunnel.suppressDownCallback = true
backend.setState(currentTunnel, Tunnel.State.DOWN, null)
sharedTunnel = null
sharedConfigFingerprint = null
delay(150)
startTunnelLocked(configFlow)
Log.d("WG", "WireGuard tunnel reloaded for new exceptions")
@@ -179,6 +201,7 @@ class WireGuardHelper(context: Context) {
it.suppressDownCallback = true
backend.setState(it, Tunnel.State.DOWN, null)
sharedTunnel = null
sharedConfigFingerprint = null
Log.d("WG", "WireGuard tunnel stopped")
}
} catch (e: Exception) {
@@ -236,3 +259,17 @@ class WireGuardHelper(context: Context) {
return "config lines=${lines.size}, interface=$hasInterface, peer=$hasPeer, privateKey=$hasPrivateKey, publicKey=$hasPublicKey, address=$hasAddress, endpoint=$endpoint"
}
}
internal fun shouldReuseRunningWireGuard(
tunnelUp: Boolean,
currentConfigFingerprint: String?,
updatedConfig: Config,
): Boolean =
tunnelUp &&
currentConfigFingerprint != null &&
currentConfigFingerprint == wireGuardConfigFingerprint(updatedConfig)
internal fun wireGuardConfigFingerprint(config: Config): String =
MessageDigest.getInstance("SHA-256")
.digest(config.toWgQuickString().toByteArray(Charsets.UTF_8))
.joinToString(separator = "") { byte -> "%02x".format(byte.toInt() and 0xff) }
@@ -0,0 +1,13 @@
package com.wdtt.plus.ui
internal fun collapsingHeaderOffsetAfterScroll(
currentOffsetPx: Float,
headerHeightPx: Float,
deltaPx: Float,
allowExpand: Boolean,
): Float {
if (headerHeightPx <= 0f || deltaPx == 0f) return currentOffsetPx
if (deltaPx > 0f && !allowExpand) return currentOffsetPx
return (currentOffsetPx + deltaPx).coerceIn(-headerHeightPx, 0f)
}
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,9 @@ package com.wdtt.plus.ui
import android.content.pm.PackageManager
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
@@ -57,76 +59,6 @@ object AppCache {
var cachedList: List<AppItem>? = null
}
private val VpnDetectionExactPackages = setOf(
"ru.sberbankmobile",
"ru.tinkoff.mb",
"ru.vtb24.mobilebanking.android",
"ru.alfabank.mobile.android",
"ru.ozon.app.android",
"com.wildberries.ru",
"ru.beru.android",
"ru.megamarket",
"ru.sbermarket",
"ru.samokat.android",
"com.avito.android",
"ru.yandex.searchplugin",
"ru.yandex.yandexmaps",
"ru.yandex.music",
"ru.kinopoisk",
"com.yandex.browser",
"ru.yandex.taxi",
"com.vkontakte.android",
"com.vk.vkvideo",
"ru.vk.music",
"ru.ok.android",
"ru.rutube.app",
"ru.mail.mailapp",
"ru.mail.cloud",
"ru.mts",
"ru.beeline.services",
"ru.tele2.mytele2",
"ru.megafon.mlk",
"ru.rostel",
"ru.gosuslugi.mobile",
"ru.vk.store",
"ru.dublgis.dgismobile",
"ru.maximoff.max"
)
private val VpnDetectionKeywords = listOf(
"sber", "сбер",
"tinkoff", "t-bank", "tbank", "тинькофф", "тбанк",
"vtb", "втб",
"alfa", "alpha", "альфа",
"ozon", "озон",
"wildberries", "вайлдберриз",
"yandex", "яндекс",
"vkontakte", "вконтакте",
"rutube", "рутуб",
"gosuslugi", "госуслуг",
"dublgis", "2gis", "dgis", "дубльгис",
"avito", "авито",
"mts", "мтс",
"beeline", "билайн",
"megafon", "мегафон",
"tele2", "теле2",
"mail.ru", "mailapp",
"ok.ru", "odnoklassniki",
"kinopoisk", "кинопоиск",
"samokat", "самокат",
"megamarket", "sbermarket",
"rostel", "ростел",
"maximoff"
)
private fun AppItem.matchesVpnDetectionApp(): Boolean {
val packageLower = packageName.lowercase()
if (packageLower in VpnDetectionExactPackages) return true
val titleLower = name.lowercase()
val haystack = "$packageLower $titleLower"
return VpnDetectionKeywords.any { keyword -> haystack.contains(keyword) }
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExceptionsTab(
@@ -229,22 +161,50 @@ fun ExceptionsTab(
}
}
val collapsingHeaderConnection = remember(topBlockHeightPx) {
fun consumeHeaderScroll(deltaPx: Float, allowExpand: Boolean): Float {
val previousOffset = topBlockOffsetPx
val nextOffset = collapsingHeaderOffsetAfterScroll(
currentOffsetPx = previousOffset,
headerHeightPx = topBlockHeightPx,
deltaPx = deltaPx,
allowExpand = allowExpand,
)
if (nextOffset != previousOffset) {
topBlockOffsetPx = nextOffset
topBlockPositionInitialized = true
}
return nextOffset - previousOffset
}
val collapsingHeaderConnection = remember(topBlockHeightPx, listState) {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (topBlockHeightPx <= 0f) return Offset.Zero
val delta = available.y
val canCollapse = delta < 0f && topBlockOffsetPx > -topBlockHeightPx
val canExpand = delta > 0f && topBlockOffsetPx < 0f
if (!canCollapse && !canExpand) return Offset.Zero
val consumed = consumeHeaderScroll(
deltaPx = delta,
allowExpand = !listState.canScrollBackward,
)
return Offset(x = 0f, y = consumed)
}
val previousOffset = topBlockOffsetPx
topBlockOffsetPx = (previousOffset + delta).coerceIn(-topBlockHeightPx, 0f)
topBlockPositionInitialized = true
return Offset(x = 0f, y = topBlockOffsetPx - previousOffset)
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource,
): Offset {
if (available.y <= 0f) return Offset.Zero
val headerConsumed = consumeHeaderScroll(
deltaPx = available.y,
allowExpand = true,
)
return Offset(x = 0f, y = headerConsumed)
}
}
}
val searchHeaderScrollState = rememberScrollableState { deltaPx ->
consumeHeaderScroll(deltaPx = deltaPx, allowExpand = true)
}
val collapseFraction = if (topBlockHeightPx > 0f) {
(-topBlockOffsetPx / topBlockHeightPx).coerceIn(0f, 1f)
} else {
@@ -356,7 +316,12 @@ fun ExceptionsTab(
OutlinedButton(
onClick = {
val detectedPackages = appsList
.filter { it.matchesVpnDetectionApp() }
.filter {
matchesQuickExclusionApp(
name = it.name,
packageName = it.packageName,
)
}
.map { it.packageName }
.toSet()
if (detectedPackages.isEmpty()) {
@@ -383,7 +348,7 @@ fun ExceptionsTab(
)
}
Text(
"Банки, маркетплейсы и другие приложения, чувствительные к VPN. Поиск выполняется по известным названиям.",
"Приложения из белых списков мобильного интернета и другие сервисы, чувствительные к VPN. Выбираются только найденные на устройстве.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 6.dp)
@@ -409,7 +374,11 @@ fun ExceptionsTab(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp * collapseFraction, bottom = 12.dp)
.height(52.dp),
.height(52.dp)
.scrollable(
state = searchHeaderScrollState,
orientation = Orientation.Vertical,
),
shape = RoundedCornerShape(16.dp),
leadingIcon = { Icon(Icons.Default.Search, null, modifier = Modifier.size(20.dp)) },
singleLine = true,
@@ -12,6 +12,7 @@ import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -19,7 +20,6 @@ import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import kotlinx.coroutines.launch
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -37,7 +37,11 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.TunnelStopCoordinator
import com.wdtt.plus.TunnelStopResult
import com.wdtt.plus.sanitizeVpnProfileNameInput
import com.wdtt.plus.vpnProfileDefaultName
import com.wdtt.plus.vpnProfileDisplayName
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
@@ -56,6 +60,12 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Share
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import android.widget.Toast
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
private const val PROFILE_RESET_TIMEOUT_MS = 10_000L
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
@Composable
@@ -65,6 +75,7 @@ fun FloatingToolbar(
onActiveProfileChange: (Int) -> Unit,
onProfileNameChange: (Int, String) -> Unit,
interfaceRole: String,
adminModeAllowed: Boolean,
onInterfaceRoleChange: (String) -> Unit,
currentTheme: String,
onThemeChange: (String) -> Unit,
@@ -80,10 +91,19 @@ fun FloatingToolbar(
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false)
val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList())
val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle()
val customVkCredentialsEnabled by settingsStore.customVkCredentialsEnabled.collectAsStateWithLifecycle(initialValue = false)
val customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false)
val savedToolbarYFraction by settingsStore.floatingToolbarYFraction.collectAsStateWithLifecycle(
initialValue = -2f
)
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
val tunnelTransition by TunnelManager.transition.collectAsStateWithLifecycle()
val connectedProfile by TunnelManager.activeTunnelProfile.collectAsStateWithLifecycle()
val configuration = LocalConfiguration.current
val density = LocalDensity.current
val screenHeightPx = remember(configuration.screenHeightDp, density) {
@@ -96,19 +116,39 @@ fun FloatingToolbar(
var parentWidthPx by remember { mutableFloatStateOf(0f) }
var parentHeightPx by remember { mutableFloatStateOf(0f) }
var offsetY by rememberSaveable { mutableFloatStateOf(-1f) }
var offsetY by remember { mutableFloatStateOf(-1f) }
var toolbarPositionRestored by remember { mutableStateOf(false) }
var isRightSide by rememberSaveable { mutableStateOf(true) }
var isExpanded by rememberSaveable { mutableStateOf(false) }
var tabHeightPx by remember { mutableFloatStateOf(0f) }
var panelHeightPx by remember { mutableFloatStateOf(0f) }
var renamingProfile by remember { mutableStateOf<Int?>(null) }
var resettingProfile by remember { mutableStateOf<Int?>(null) }
var resetCountdown by remember { mutableIntStateOf(5) }
var resetInProgress by remember { mutableStateOf(false) }
var profileNameInput by rememberSaveable { mutableStateOf("") }
var showTrustedWifiSettings by rememberSaveable { mutableStateOf(false) }
var showVkClientSettings by rememberSaveable { mutableStateOf(false) }
val tabWidthDp = 42.dp
val tabHeightDp = 52.dp
val panelWidthDp = 220.dp
val isAdminRole = interfaceRole != "user"
// Move the thumb immediately on tap instead of waiting for the DataStore round trip.
// The persisted value still remains the source of truth and resynchronizes this state.
var displayedInterfaceRole by remember(interfaceRole, adminModeAllowed) {
mutableStateOf(if (adminModeAllowed) interfaceRole else "user")
}
val isAdminRole = adminModeAllowed && displayedInterfaceRole == "admin"
LaunchedEffect(resettingProfile) {
resetCountdown = 5
if (resettingProfile != null) {
while (resetCountdown > 0) {
delay(1_000L)
resetCountdown--
}
}
}
val tabWidthPx = remember(density) { with(density) { tabWidthDp.toPx() } }
val fallbackTabHeightPx = remember(density) { with(density) { tabHeightDp.toPx() } }
@@ -128,7 +168,7 @@ fun FloatingToolbar(
val minOffsetY = safeTopPx + edgePaddingPx
val maxOffsetY = (currentParentHeight - safeBottomPx - floatingHeightPx - edgePaddingPx)
.coerceAtLeast(minOffsetY)
val defaultOffsetY = (currentParentHeight * 0.24f).coerceIn(minOffsetY, maxOffsetY)
val defaultOffsetY = (currentParentHeight * 0.30f).coerceIn(minOffsetY, maxOffsetY)
val targetXPx = if (isRightSide) currentParentWidth - tabWidthPx else 0f
@@ -138,8 +178,29 @@ fun FloatingToolbar(
label = "tab_shift"
)
LaunchedEffect(minOffsetY, maxOffsetY) {
offsetY = if (offsetY < 0f) defaultOffsetY else offsetY.coerceIn(minOffsetY, maxOffsetY)
LaunchedEffect(savedToolbarYFraction, minOffsetY, maxOffsetY) {
if (savedToolbarYFraction < -1f) return@LaunchedEffect
offsetY = if (!toolbarPositionRestored || offsetY < 0f) {
if (savedToolbarYFraction >= 0f && maxOffsetY > minOffsetY) {
minOffsetY + (maxOffsetY - minOffsetY) * savedToolbarYFraction
} else {
defaultOffsetY
}
} else {
offsetY.coerceIn(minOffsetY, maxOffsetY)
}
toolbarPositionRestored = true
}
fun persistToolbarPosition() {
if (!toolbarPositionRestored) return
val availableRange = maxOffsetY - minOffsetY
val fraction = if (availableRange > 0f) {
((offsetY - minOffsetY) / availableRange).coerceIn(0f, 1f)
} else {
0f
}
scope.launch { settingsStore.saveFloatingToolbarYFraction(fraction) }
}
Box(
@@ -159,6 +220,8 @@ fun FloatingToolbar(
}
.pointerInput(minOffsetY, maxOffsetY) {
detectDragGestures(
onDragEnd = { persistToolbarPosition() },
onDragCancel = { persistToolbarPosition() },
onDrag = { change, dragAmount ->
change.consume()
offsetY = (offsetY + dragAmount.y).coerceIn(minOffsetY, maxOffsetY)
@@ -248,7 +311,10 @@ fun FloatingToolbar(
.widthIn(min = 72.dp, max = 180.dp)
.clip(profileShape)
.combinedClickable(
onClick = { onActiveProfileChange(profile) },
onClick = {
onActiveProfileChange(profile)
isExpanded = false
},
onLongClick = {
renamingProfile = profile
profileNameInput = profileLabel
@@ -280,7 +346,7 @@ fun FloatingToolbar(
shape = RoundedCornerShape(12.dp)
) {
Icon(Icons.Filled.Share, contentDescription = null, modifier = Modifier.size(18.dp))
Text(" Передать или получить", fontSize = 12.sp)
Text(" Получить или передать", fontSize = 12.sp)
}
HorizontalDivider(
@@ -340,7 +406,14 @@ fun FloatingToolbar(
color = MaterialTheme.colorScheme.onSurface
)
Text(
if (isAdminRole) "VPN и настройка своего сервера" else "Подключение и работа VPN",
when {
!adminModeAllowed ->
"Режим «Админ» доступен для самостоятельного профиля"
isAdminRole ->
"VPN и настройка своего сервера"
else ->
"Подключение и работа VPN"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 15.sp
@@ -348,7 +421,14 @@ fun FloatingToolbar(
}
Switch(
checked = isAdminRole,
onCheckedChange = { checked -> onInterfaceRoleChange(if (checked) "admin" else "user") },
onCheckedChange = { checked ->
val role = if (checked) "admin" else "user"
if (role != displayedInterfaceRole) {
displayedInterfaceRole = role
onInterfaceRoleChange(role)
}
},
enabled = adminModeAllowed,
modifier = Modifier.scale(0.85f)
)
}
@@ -501,94 +581,41 @@ fun FloatingToolbar(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
Text(
"Client IDs",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(start = 4.dp, bottom = 4.dp)
)
val scope = rememberCoroutineScope()
val clientIdsList = activeClientIds.split(",").map { it.trim() }.filter { it.isNotEmpty() }
val checkResultsJson by settingsStore.clientIdCheckResults.collectAsStateWithLifecycle(initialValue = "{}")
var checkResults by remember(checkResultsJson) {
mutableStateOf(try {
val json = org.json.JSONObject(checkResultsJson)
val map = mutableMapOf<String, Boolean>()
val keys = json.keys()
while (keys.hasNext()) {
val key = keys.next() as String
map[key] = json.getBoolean(key)
}
map
} catch (e: Exception) { emptyMap() })
}
var isChecking by remember { mutableStateOf(false) }
val knownIds = listOf("6287487", "8202606")
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
knownIds.forEach { id ->
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = clientIdsList.contains(id),
onCheckedChange = { checked ->
val newList = if (checked) {
if (!clientIdsList.contains(id)) clientIdsList + id else clientIdsList
} else {
clientIdsList - id
}
if (newList.isNotEmpty()) {
onClientIdsChange(newList.joinToString(","))
}
},
modifier = Modifier.scale(0.8f)
)
Text(
text = id,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface
)
}
if (checkResults.containsKey(id)) {
Text(
text = if (checkResults[id] == true) "✅" else "❌",
fontSize = 12.sp
)
}
}
}
Button(
onClick = {
isChecking = true
scope.launch(kotlinx.coroutines.Dispatchers.IO) {
val results = checkResults.toMutableMap()
knownIds.forEach { id ->
results[id] = checkVkClientId(id)
}
val newJson = org.json.JSONObject()
results.forEach { (k, v) -> newJson.put(k, v) }
settingsStore.saveClientIdCheckResults(newJson.toString())
isChecking = false
}
},
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),
enabled = !isChecking,
contentPadding = PaddingValues(0.dp)
) {
Text(if (isChecking) "Checking..." else "Проверить", fontSize = 12.sp)
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { showVkClientSettings = true }
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) {
Text(
"Клиенты VK",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
when {
!customVkCredentialsEnabled -> "VKCalls → встроенный резерв"
customVkCredentialsComplete -> "VKCalls → свой → встроенный резерв"
else -> "Заполните резервные реквизиты"
},
style = MaterialTheme.typography.bodySmall,
color = if (customVkCredentialsEnabled && !customVkCredentialsComplete) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
lineHeight = 15.sp
)
}
Switch(
checked = customVkCredentialsEnabled,
onCheckedChange = null,
modifier = Modifier.scale(0.85f)
)
}
}
}
@@ -596,38 +623,72 @@ fun FloatingToolbar(
}
renamingProfile?.let { profile ->
AlertDialog(
onDismissRequest = { renamingProfile = null },
title = {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text("Название профиля")
IconButton(onClick = { renamingProfile = null }) {
Icon(Icons.Filled.Close, contentDescription = "Закрыть")
}
}
ProfileMenuDialog(
profileNameInput = profileNameInput,
onProfileNameInputChange = { profileNameInput = sanitizeVpnProfileNameInput(it) },
onResetRequested = {
resetCountdown = 5
resettingProfile = profile
},
text = {
OutlinedTextField(
value = profileNameInput,
onValueChange = { profileNameInput = sanitizeVpnProfileNameInput(it) },
label = { Text("Название") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
onSave = {
onProfileNameChange(profile, profileNameInput)
renamingProfile = null
},
confirmButton = {
Button(
onClick = {
onProfileNameChange(profile, profileNameInput)
onDismiss = { renamingProfile = null }
)
}
resettingProfile?.let { profile ->
val profileLabel = vpnProfileDisplayName(profile, profileNames)
val potentiallyConnectedProfile = profile == (connectedProfile ?: activeProfile)
val resetsConnectedProfile = potentiallyConnectedProfile &&
(tunnelRunning || tunnelTransition != com.wdtt.plus.TunnelTransition.IDLE)
ProfileResetDialog(
profileLabel = profileLabel,
defaultProfileLabel = vpnProfileDefaultName(profile),
countdown = resetCountdown,
inProgress = resetInProgress,
disconnectsActiveVpn = resetsConnectedProfile,
onConfirm = {
if (resetCountdown > 0 || resetInProgress) return@ProfileResetDialog
resetInProgress = true
scope.launch {
runCatching {
if (potentiallyConnectedProfile) {
val stopResult = TunnelStopCoordinator.stopAndAwait(context)
check(stopResult.succeeded) {
when (stopResult) {
TunnelStopResult.TIMED_OUT ->
"VPN не остановился за отведённое время"
else -> "Не удалось остановить VPN"
}
}
}
val resetCompleted = withTimeoutOrNull(PROFILE_RESET_TIMEOUT_MS) {
settingsStore.resetProfile(profile)
true
} == true
check(resetCompleted) {
"Очистка профиля не завершилась за 10 секунд. Повторите попытку."
}
}.onSuccess {
profileNameInput = vpnProfileDefaultName(profile)
resettingProfile = null
renamingProfile = null
isExpanded = false
Toast.makeText(context, "Профиль «$profileLabel» очищен", Toast.LENGTH_SHORT).show()
}.onFailure { error ->
Toast.makeText(
context,
error.message ?: "Не удалось очистить профиль",
Toast.LENGTH_LONG
).show()
}
) {
Text("Сохранить")
resetInProgress = false
}
},
onDismiss = {
if (!resetInProgress) resettingProfile = null
}
)
}
@@ -638,36 +699,250 @@ fun FloatingToolbar(
onDismiss = { showTrustedWifiSettings = false }
)
}
if (showVkClientSettings) {
VkClientSettingsDialog(
settingsStore = settingsStore,
activeClientIds = activeClientIds,
onClientIdsChange = onClientIdsChange,
onDismiss = { showVkClientSettings = false }
)
}
}
}
private fun checkVkClientId(appId: String): Boolean {
for (i in 0..1) {
try {
val url = java.net.URL("https://oauth.vk.com/authorize?client_id=$appId&display=mobile&response_type=token")
val conn = url.openConnection() as java.net.HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 5000
conn.readTimeout = 5000
val code = conn.responseCode
val stream = if (code >= 400) conn.errorStream else conn.inputStream
val response = stream?.bufferedReader()?.readText() ?: ""
// If it returns a json error like {"error":"invalid_client"...}
if (response.contains("\"error\"") && (response.contains("invalid_client") || response.contains("invalid_request"))) {
return false
@Composable
private fun ProfileMenuDialog(
profileNameInput: String,
onProfileNameInputChange: (String) -> Unit,
onResetRequested: () -> Unit,
onSave: () -> Unit,
onDismiss: () -> Unit
) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
BoxWithConstraints(
modifier = Modifier.fillMaxSize().padding(8.dp),
contentAlignment = Alignment.Center
) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.widthIn(max = 560.dp)
.heightIn(max = maxHeight * 0.92f),
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 8.dp
) {
Box {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(22.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Text(
"Профиль",
modifier = Modifier.padding(end = 48.dp),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary
)
OutlinedTextField(
value = profileNameInput,
onValueChange = onProfileNameInputChange,
label = { Text("Название") },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onResetRequested,
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)
) {
Text("Очистить", fontWeight = FontWeight.SemiBold)
}
Button(
onClick = onSave,
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
shape = RoundedCornerShape(16.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)
) {
Text("Сохранить", fontWeight = FontWeight.SemiBold)
}
}
Spacer(Modifier.height(4.dp))
}
ProfileDialogCloseButton(
contentDescription = "Вернуться в настройки",
onClick = onDismiss,
modifier = Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 10.dp)
)
}
}
// If it returns HTML (login form or captcha), it's a valid client ID
return true
} catch (e: Exception) {
// Error, will retry
}
}
return false
}
@Composable
private fun ProfileResetDialog(
profileLabel: String,
defaultProfileLabel: String,
countdown: Int,
inProgress: Boolean,
disconnectsActiveVpn: Boolean,
onConfirm: () -> Unit,
onDismiss: () -> Unit
) {
Dialog(
onDismissRequest = { if (!inProgress) onDismiss() },
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
BoxWithConstraints(
modifier = Modifier.fillMaxSize().padding(8.dp),
contentAlignment = Alignment.Center
) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.widthIn(max = 560.dp)
.heightIn(max = maxHeight * 0.92f),
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 8.dp
) {
Box {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(22.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Text(
"Очистить профиль?",
modifier = Modifier.padding(end = 48.dp),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.error
)
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer
) {
Column(
modifier = Modifier.padding(15.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
"Будет полностью очищена вся локальная информация профиля «$profileLabel».",
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.bodyLarge
)
Text(
"Удалятся настройки подключения, VK-хеши, ссылки, пароли и SSH-ключи, параметры сервера, списки приложений и остальные данные этого профиля.",
style = MaterialTheme.typography.bodyMedium
)
Text(
"Название вернётся к стандартному: «$defaultProfileLabel». Операция необратима. Вы уверены?",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold
)
}
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f)
) {
Text(
buildString {
append("На самом VPS и в других профилях ничего не удаляется.")
if (disconnectsActiveVpn) append(" Активное VPN-подключение этого профиля будет остановлено.")
},
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Button(
onClick = onConfirm,
enabled = countdown <= 0 && !inProgress,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onError,
disabledContainerColor = MaterialTheme.colorScheme.errorContainer,
disabledContentColor = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.68f)
)
) {
Text(
when {
inProgress -> "Очищаю профиль…"
countdown > 0 -> "Очистить через $countdown с"
else -> "Полностью очистить профиль"
},
fontWeight = FontWeight.Bold
)
}
Spacer(Modifier.height(4.dp))
}
ProfileDialogCloseButton(
contentDescription = "Вернуться к профилю",
onClick = onDismiss,
enabled = !inProgress,
modifier = Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 10.dp)
)
}
}
}
}
}
@Composable
private fun ProfileDialogCloseButton(
contentDescription: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true
) {
IconButton(onClick = onClick, modifier = modifier, enabled = enabled) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.78f),
modifier = Modifier.size(34.dp)
) {
Box(contentAlignment = Alignment.Center) {
Icon(
Icons.Filled.Close,
contentDescription = contentDescription,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(22.dp)
)
}
}
}
}
@Composable
private fun ThemeOption(
+607 -30
View File
@@ -52,11 +52,14 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Cloud
import androidx.compose.material.icons.filled.Code
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Info
@@ -65,13 +68,17 @@ import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -94,6 +101,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@@ -104,6 +112,11 @@ import com.wdtt.plus.BuildConfig
import com.wdtt.plus.DeviceCheckAction
import com.wdtt.plus.DeviceCompatibility
import com.wdtt.plus.R
import com.wdtt.plus.RemoteActionCatalogGateway
import com.wdtt.plus.RemoteActionForm
import com.wdtt.plus.RemoteContinuationLauncher
import com.wdtt.plus.RemoteUiAction
import com.wdtt.plus.RemoteUiActionLauncher
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.TrustedWifiManager
@@ -114,7 +127,9 @@ import com.wdtt.plus.WDTTColors
import com.wdtt.plus.AppReleaseInfo
import com.wdtt.plus.AppUpdateCandidate
import com.wdtt.plus.AppUpdateDownloadProgress
import com.wdtt.plus.ClientNetworkDiagnosticsReport
import com.wdtt.plus.canRequestApkInstall
import com.wdtt.plus.collectClientNetworkDiagnostics
import com.wdtt.plus.downloadUpdateApk
import com.wdtt.plus.fetchLatestReleaseInfo
import com.wdtt.plus.installUpdateApk
@@ -123,6 +138,7 @@ import com.wdtt.plus.resolveAppUpdateCandidate
import com.wdtt.plus.selectUpdateApkAsset
import com.wdtt.plus.deviceCheckActionIntent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -132,6 +148,7 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.UUID
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.min
@@ -142,7 +159,7 @@ private const val IssuesUrl = "https://github.com/Ivan4537/WDTT-Plus/issues/new/
private const val DeveloperProfileUrl = "https://github.com/Ivan4537"
private const val RepositoryUrl = "https://github.com/Ivan4537/WDTT-Plus"
private const val ChangelogUrl = "$RepositoryUrl/blob/main/CHANGELOG.md"
private const val DonateUrl = "https://yoomoney.ru/to/410012216336438"
private const val ProjectDonateFallbackUrl = "https://yoomoney.ru/to/410012216336438"
private const val OriginalDonateUrl = "https://yoomoney.ru/to/4100119505530465/"
private val DonateActionButtonColor = Color(0xFF00AEA5)
@@ -221,7 +238,9 @@ private fun openDeviceCheckAction(context: Context, action: DeviceCheckAction) {
fun InfoTab(
actionsExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) },
projectExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) },
scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) },
projectSupportDialogRequest: Int = 0,
onProjectSupportDialogRequestConsumed: () -> Unit = {},
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
@@ -238,12 +257,23 @@ fun InfoTab(
var updateDownloadStatus by rememberSaveable { mutableStateOf("") }
var updateDownloadBusy by remember { mutableStateOf(false) }
var pendingUpdateApkPath by rememberSaveable { mutableStateOf<String?>(null) }
var showHelpDialog by remember { mutableStateOf(false) }
var showSupportDialog by remember { mutableStateOf(false) }
var showHelpDialog by remember { mutableStateOf(false) }
var showQuestionDialog by remember { mutableStateOf(false) }
var showSupportDialog by remember { mutableStateOf(false) }
var pendingActionForm by remember { mutableStateOf<RemoteUiAction?>(null) }
var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) }
var questionAction by remember { mutableStateOf<RemoteUiAction?>(null) }
var questionActionLoading by remember { mutableStateOf(false) }
var isCheckingDevice by remember { mutableStateOf(false) }
var deviceCheckReport by remember { mutableStateOf<com.wdtt.plus.DeviceCompatibilityReport?>(null) }
var actionsExpanded by actionsExpandedState
var projectExpanded by projectExpandedState
var projectExpanded by projectExpandedState
LaunchedEffect(projectSupportDialogRequest) {
if (projectSupportDialogRequest > 0) {
showSupportDialog = true
onProjectSupportDialogRequestConsumed()
}
}
val updateLatestVersion by settingsStore.updateLatestVersion.collectAsStateWithLifecycle(initialValue = "")
val updateLastError by settingsStore.updateLastError.collectAsStateWithLifecycle(initialValue = "")
val updateStatus = remember(isCheckingUpdates, updateLatestVersion, updateLastError, currentVersion) {
@@ -276,6 +306,15 @@ fun InfoTab(
}
}
LaunchedEffect(Unit) {
actionCatalog = RemoteActionCatalogGateway.fetch()
}
LaunchedEffect(Unit) {
questionActionLoading = true
questionAction = RemoteActionCatalogGateway.fetchQuestionAction()
questionActionLoading = false
}
fun requestDownloadedUpdateInstall(apkFile: File) {
pendingUpdateApkPath = apkFile.absolutePath
if (!canRequestApkInstall(context)) {
@@ -317,6 +356,25 @@ fun InfoTab(
val diagnosticsSummary = withContext(Dispatchers.Default) {
buildSupportReportSummary(context.applicationContext, settingsStore)
}
val clientNetworkDiagnostics = try {
collectClientNetworkDiagnostics(context.applicationContext)
} catch (error: CancellationException) {
throw error
} catch (error: Throwable) {
ClientNetworkDiagnosticsReport(
summaryLines = listOf("Активная диагностика сети телефона: не выполнена"),
items = listOf(
com.wdtt.plus.DeviceCheckItem(
title = "Активная диагностика сети телефона",
status = "не выполнена",
details = error.message?.take(180) ?: error.javaClass.simpleName,
recommendation = "Повторите проверку устройства при активной сети.",
severity = com.wdtt.plus.DeviceCheckSeverity.Warning,
action = DeviceCheckAction.NetworkSettings
)
)
)
}
val report = withContext(Dispatchers.Default) {
DeviceCompatibility.check(
context = context.applicationContext,
@@ -325,9 +383,10 @@ fun InfoTab(
)
}
return report.copy(
summaryLines = diagnosticsSummary,
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines,
items = listOf(versionItem) +
report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE }
report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } +
clientNetworkDiagnostics.items
)
}
@@ -355,7 +414,9 @@ fun InfoTab(
InfoHeroCard(
currentVersion = currentVersion,
releaseDate = releaseDate,
onSupportClick = { showSupportDialog = true }
onSupportClick = {
showSupportDialog = true
}
)
ExpandableSectionCard(
@@ -384,8 +445,17 @@ fun InfoTab(
) {
WideActionTile(
title = "Поднять вопрос",
subtitle = "Выбрать шаблон GitHub issue",
onClick = { openUrlInBrowser(context, IssuesUrl) },
subtitle = "Выбрать подходящий способ обращения",
onClick = {
showQuestionDialog = true
if (questionAction == null && !questionActionLoading) {
scope.launch {
questionActionLoading = true
questionAction = RemoteActionCatalogGateway.fetchQuestionAction()
questionActionLoading = false
}
}
},
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_github),
@@ -672,12 +742,35 @@ fun InfoTab(
}
if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false })
if (showQuestionDialog) {
QuestionDestinationDialog(
remoteAction = questionAction,
remoteActionLoading = questionActionLoading,
onDismiss = { showQuestionDialog = false },
onGitHubClick = {
showQuestionDialog = false
openUrlInBrowser(context, IssuesUrl)
},
onRemoteActionClick = { action ->
showQuestionDialog = false
scope.launch {
if (!RemoteUiActionLauncher.open(context, action)) {
Toast.makeText(
context,
"Не удалось открыть страницу. Проверьте браузер.",
Toast.LENGTH_LONG,
).show()
}
}
},
)
}
deviceCheckReport?.let { report ->
DeviceCompatibilityDialog(
report = report,
title = "Проверка устройства",
subtitle = "Расширенная проверка не запускает VPN, но показывает совместимость устройства, настройки Android и статус подключения.",
note = "Кнопка «Скопировать отчёт» добавит в буфер версию приложения, Android, ABI, память, сеть, WebView, native-клиент и текущие настройки без секретных значений.",
subtitle = "Расширенная проверка не запускает VPN, но безопасно проверяет системный DNS, DNS-путь клиента и доступность узлов VK/OK.",
note = "Кнопка «Скопировать отчёт» повторит сетевые пробы и добавит их результат без VK-хешей, паролей, токенов и локальных IP-адресов телефона.",
onDismiss = { deviceCheckReport = null },
onCopy = {
scope.launch {
@@ -696,18 +789,189 @@ fun InfoTab(
)
}
if (showSupportDialog) {
SupportProjectDialog(
AdditionalActionsDialog(
onDismiss = { showSupportDialog = false },
onDonateModClick = { openUrlInBrowser(context, DonateUrl) },
onDonateOriginalClick = { openUrlInBrowser(context, OriginalDonateUrl) }
primaryAction = actionCatalog.at("about"),
secondaryAction = actionCatalog.at("tunnel"),
onActionClick = { action ->
if (action.form != null) {
showSupportDialog = false
pendingActionForm = action
} else {
showSupportDialog = false
scope.launch {
if (!RemoteUiActionLauncher.open(context, action)) {
Toast.makeText(
context,
"Не удалось открыть страницу. Проверьте браузер.",
Toast.LENGTH_LONG,
).show()
}
}
}
},
onProjectFallbackClick = {
showSupportDialog = false
openUrlInBrowser(context, ProjectDonateFallbackUrl)
},
onDonateOriginalClick = {
showSupportDialog = false
openUrlInBrowser(context, OriginalDonateUrl)
}
)
}
pendingActionForm?.form?.let { form ->
RemoteActionFormDialog(
form = form,
onDismiss = {
pendingActionForm = null
showSupportDialog = true
},
onComplete = {
pendingActionForm = null
showSupportDialog = true
},
onFallbackClick = {
openUrlInBrowser(context, ProjectDonateFallbackUrl)
pendingActionForm = null
showSupportDialog = true
},
)
}
}
@Composable
private fun SupportProjectDialog(
private fun QuestionDestinationDialog(
remoteAction: RemoteUiAction?,
remoteActionLoading: Boolean,
onDismiss: () -> Unit,
onGitHubClick: () -> Unit,
onRemoteActionClick: (RemoteUiAction) -> Unit,
) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
Box(
modifier = Modifier.fillMaxSize().padding(20.dp),
contentAlignment = Alignment.Center,
) {
Surface(
shape = RoundedCornerShape(28.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
shadowElevation = 18.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 560.dp),
) {
Column(
modifier = Modifier.fillMaxWidth().padding(20.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.primaryContainer,
) {
Box(
modifier = Modifier.size(42.dp),
contentAlignment = Alignment.Center,
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.HelpOutline,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(21.dp),
)
}
}
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
Text(
"Поднять вопрос",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
)
Text(
"Выберите подходящий вариант обращения.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
FilledTonalIconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = null)
}
}
WideActionTile(
title = "Проблема в приложении",
subtitle = "Открыть шаблоны обращений GitHub",
onClick = onGitHubClick,
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_github),
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer,
)
},
)
remoteAction?.let { action ->
WideActionTile(
title = action.label,
subtitle = action.message,
onClick = { onRemoteActionClick(action) },
icon = {
Icon(
Icons.AutoMirrored.Filled.HelpOutline,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer,
)
},
)
}
if (remoteAction == null && remoteActionLoading) {
Surface(
shape = RoundedCornerShape(20.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.62f),
modifier = Modifier.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
strokeWidth = 2.dp,
)
Text(
"Проверяем доступные способы помощи…",
style = MaterialTheme.typography.bodyMedium,
)
}
}
}
}
}
}
}
}
@Composable
private fun AdditionalActionsDialog(
onDismiss: () -> Unit,
onDonateModClick: () -> Unit,
primaryAction: RemoteUiAction?,
secondaryAction: RemoteUiAction?,
onActionClick: (RemoteUiAction) -> Unit,
onProjectFallbackClick: () -> Unit,
onDonateOriginalClick: () -> Unit
) {
Dialog(
@@ -766,15 +1030,35 @@ private fun SupportProjectDialog(
}
}
SupportDonateBlock(
title = "WDTT Plus",
body = "Поддержка этой версии помогает развивать доработки приложения, серверной части, Telegram-бота и удобство для пользователей.",
buttonText = "ЮMoney",
onClick = onDonateModClick,
emphasized = true
)
if (primaryAction?.form != null) {
ExternalSupportBlock(
title = primaryAction.title,
body = primaryAction.message,
buttonText = primaryAction.label,
onClick = { onActionClick(primaryAction) },
emphasized = true,
)
} else {
ExternalSupportBlock(
title = "WDTT Plus",
body = (
"Поддержка помогает развивать приложение, серверную "
+ "часть и Telegram-бота."
),
buttonText = "ЮMoney",
onClick = onProjectFallbackClick,
emphasized = true,
)
}
SupportDonateBlock(
secondaryAction?.let { action ->
RemoteInfoActionBlock(
action = action,
onClick = { onActionClick(action) },
)
}
ExternalSupportBlock(
title = "Автор оригинального приложения",
body = "Оригинальная основа проекта создана amurcanov. Можно отдельно поддержать автора исходного приложения.",
buttonText = "ЮMoney",
@@ -789,7 +1073,285 @@ private fun SupportProjectDialog(
}
@Composable
private fun SupportDonateBlock(
private fun RemoteActionFormDialog(
form: RemoteActionForm,
onDismiss: () -> Unit,
onComplete: () -> Unit,
onFallbackClick: () -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var valueText by rememberSaveable(form.token) { mutableStateOf(form.initialValue) }
var requestId by rememberSaveable(form.token) { mutableStateOf(UUID.randomUUID().toString()) }
var busy by remember(form.token) { mutableStateOf(false) }
var errorMessage by remember(form.token) { mutableStateOf("") }
var fallbackAvailable by remember(form.token) { mutableStateOf(false) }
val numericValue = valueText.toLongOrNull()
val valueValid = numericValue != null && numericValue in form.minimum..form.maximum
fun selectValue(value: String) {
valueText = value
requestId = UUID.randomUUID().toString()
errorMessage = ""
fallbackAvailable = false
}
Dialog(
onDismissRequest = { if (!busy) onDismiss() },
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
Surface(
shape = RoundedCornerShape(28.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
shadowElevation = 18.dp,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.primaryContainer,
) {
Box(Modifier.size(42.dp), contentAlignment = Alignment.Center) {
Icon(
Icons.Default.Favorite,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp),
)
}
}
Text(
form.title,
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
)
FilledTonalIconButton(
onClick = onDismiss,
enabled = !busy,
) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
Text(
form.message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 20.sp,
)
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
form.choices.chunked(2).forEach { rowChoices ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
rowChoices.forEach { choice ->
OutlinedButton(
onClick = { selectValue(choice.value) },
enabled = !busy,
modifier = Modifier.weight(1f),
colors = if (valueText == choice.value) {
ButtonDefaults.outlinedButtonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
)
} else {
ButtonDefaults.outlinedButtonColors()
},
) {
Text(choice.label, fontWeight = FontWeight.SemiBold)
}
}
if (rowChoices.size == 1) {
Spacer(Modifier.weight(1f))
}
}
}
}
OutlinedTextField(
value = valueText,
onValueChange = { raw ->
selectValue(raw.filter(Char::isDigit).take(form.maxCharacters))
},
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
label = { Text(form.inputLabel) },
suffix = {
if (form.inputSuffix.isNotBlank()) {
Text(form.inputSuffix)
}
},
singleLine = true,
isError = valueText.isNotEmpty() && !valueValid,
supportingText = {
Text(
if (valueValid || valueText.isEmpty()) {
form.supportingText
} else {
form.invalidText
}
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(16.dp),
)
if (errorMessage.isNotBlank()) {
Surface(
color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.64f),
shape = RoundedCornerShape(14.dp),
) {
Text(
errorMessage,
modifier = Modifier.fillMaxWidth().padding(12.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
)
}
}
Button(
onClick = {
if (!valueValid) return@Button
busy = true
errorMessage = ""
fallbackAvailable = false
scope.launch {
runCatching {
RemoteActionCatalogGateway.execute(
form = form,
requestId = requestId,
value = valueText,
)
}.onSuccess { target ->
RemoteContinuationLauncher.launch(context, target)
onComplete()
}.onFailure { error ->
errorMessage = error.message ?: form.failureMessage
fallbackAvailable = true
}
busy = false
}
},
enabled = valueValid && !busy,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(17.dp),
colors = ButtonDefaults.buttonColors(
containerColor = DonateActionButtonColor,
contentColor = Color.White,
),
) {
if (busy) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
strokeWidth = 2.dp,
color = Color.White,
)
Spacer(Modifier.width(9.dp))
Text(form.busyLabel, fontWeight = FontWeight.Bold)
} else {
Text(
form.submitLabel.replace("{value}", valueText),
fontWeight = FontWeight.Bold,
)
}
}
if (fallbackAvailable) {
OutlinedButton(
onClick = onFallbackClick,
enabled = !busy,
modifier = Modifier.fillMaxWidth().heightIn(min = 46.dp),
shape = RoundedCornerShape(16.dp),
) {
Text(form.fallbackLabel, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.width(6.dp))
Icon(
Icons.AutoMirrored.Filled.OpenInNew,
contentDescription = null,
modifier = Modifier.size(17.dp),
)
}
}
}
}
}
}
@Composable
private fun RemoteInfoActionBlock(
action: RemoteUiAction,
onClick: () -> Unit,
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f),
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
border = BorderStroke(
1.dp,
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)
)
) {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(9.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(9.dp)
) {
Icon(Icons.Default.Cloud, contentDescription = null, modifier = Modifier.size(21.dp))
Text(
action.title,
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold
)
}
Text(
action.message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.86f),
lineHeight = 18.sp
)
OutlinedButton(
onClick = onClick,
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp),
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 7.dp)
) {
Text(action.label, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.width(6.dp))
Icon(
Icons.AutoMirrored.Filled.OpenInNew,
contentDescription = null,
modifier = Modifier.size(17.dp)
)
}
}
}
}
@Composable
private fun ExternalSupportBlock(
title: String,
body: String,
buttonText: String,
@@ -834,7 +1396,11 @@ private fun SupportDonateBlock(
onClick = onClick,
shape = RoundedCornerShape(18.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (emphasized) DonateActionButtonColor else MaterialTheme.colorScheme.primary,
containerColor = if (emphasized) {
DonateActionButtonColor
} else {
MaterialTheme.colorScheme.primary
},
contentColor = Color.White
),
modifier = Modifier
@@ -1428,6 +1994,11 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
.coerceAtMost(4)
val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.getOrNull()
val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull()
val customVkCredentialsEnabled = runCatching { settingsStore.customVkCredentialsEnabled.first() }.getOrNull()
val customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull()
val builtInVkClientCount = runCatching {
settingsStore.activeClientIds.first().split(',').count { it.trim().isNotEmpty() }
}.getOrNull()
val captchaMode = runCatching { settingsStore.captchaMode.first() }.getOrNull()
val fingerprint = runCatching { settingsStore.selectedFingerprint.first() }.getOrNull()
val linkMode = runCatching { settingsStore.wdttLinkMode.first() }.getOrNull()
@@ -1447,7 +2018,9 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
} else {
"не требуется"
}
val tunnelIssue = TunnelManager.connectionIssue.value?.title.orEmpty().ifBlank { "нет" }
val tunnelIssue = TunnelManager.connectionIssue.value?.let { issue ->
"${issue.title}: ${issue.action}"
}.orEmpty().ifBlank { "нет" }
return buildString {
appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}")
@@ -1498,8 +2071,12 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
appendLine("Профиль: ${activeProfile ?: "недоступно"}")
appendLine("Потоки: ${workers ?: "недоступно"}")
appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}")
appendLine("VKCalls: ${vkCallsEnabled ?: "недоступно"}")
appendLine("Captcha mode: ${captchaMode ?: "недоступно"}")
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
appendLine(
"Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " +
"заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}"
)
appendLine("Captcha mode (legacy): ${captchaMode ?: "недоступно"}")
appendLine("TLS fingerprint: ${fingerprint ?: "недоступно"}")
appendLine("Режим ссылки: ${linkMode ?: "недоступно"}")
appendLine("Роль интерфейса: ${interfaceRole?.ifBlank { "не выбрана" } ?: "недоступно"}")
@@ -0,0 +1,166 @@
package com.wdtt.plus.ui
import android.content.Context
import android.content.SharedPreferences
import com.wdtt.plus.SecureStringStore
internal data class StoredOutboundForms(
val forms: OutboundProfileForms,
val warpMtu: String,
)
/**
* Локальные черновики выходного IP относятся к конкретному VPN-профилю.
* Пароли и WireGuard-конфиг хранятся через Android Keystore.
*/
internal class OutboundFormsStore(context: Context) {
private val prefs =
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
private val secureStore = SecureStringStore(context.applicationContext)
init {
migrateLegacyValuesToProfileZero()
}
fun load(profileIndex: Int): StoredOutboundForms {
val profile = profileIndex.coerceIn(0, 2)
return StoredOutboundForms(
forms = OutboundProfileForms(
localProxyPort = string(profile, LOCAL_PROXY_PORT, "1080"),
localProxyLogin = string(profile, LOCAL_PROXY_LOGIN, ""),
localProxyPassword = secret(profile, LOCAL_PROXY_PASSWORD),
externalProxyKindName = string(profile, EXTERNAL_PROXY_KIND, "Socks5"),
externalProxyHost = string(profile, EXTERNAL_PROXY_HOST, ""),
externalProxyPort = string(profile, EXTERNAL_PROXY_PORT, "1080"),
externalProxyLogin = string(profile, EXTERNAL_PROXY_LOGIN, ""),
externalProxyPassword = secret(profile, EXTERNAL_PROXY_PASSWORD),
wireGuardExitHost = string(profile, WG_EXIT_HOST, ""),
wireGuardExitSshPort = string(profile, WG_EXIT_SSH_PORT, "22"),
wireGuardExitUser = string(profile, WG_EXIT_USER, "root"),
wireGuardExitPassword = secret(profile, WG_EXIT_PASSWORD),
wireGuardExitPort = string(profile, WG_EXIT_PORT, "51820"),
wireGuardExitDns = string(profile, WG_EXIT_DNS, "1.1.1.1,8.8.8.8"),
importedWireGuardConfig = secret(profile, IMPORTED_WG_CONFIG),
),
warpMtu = string(profile, WARP_MTU, "1280"),
)
}
fun save(profileIndex: Int, forms: OutboundProfileForms, warpMtu: String) {
val profile = profileIndex.coerceIn(0, 2)
val editor = prefs.edit()
.putString(key(profile, LOCAL_PROXY_PORT), forms.localProxyPort)
.putString(key(profile, LOCAL_PROXY_LOGIN), forms.localProxyLogin)
.putString(key(profile, EXTERNAL_PROXY_KIND), forms.externalProxyKindName)
.putString(key(profile, EXTERNAL_PROXY_HOST), forms.externalProxyHost)
.putString(key(profile, EXTERNAL_PROXY_PORT), forms.externalProxyPort)
.putString(key(profile, EXTERNAL_PROXY_LOGIN), forms.externalProxyLogin)
.putString(key(profile, WG_EXIT_HOST), forms.wireGuardExitHost)
.putString(key(profile, WG_EXIT_SSH_PORT), forms.wireGuardExitSshPort)
.putString(key(profile, WG_EXIT_USER), forms.wireGuardExitUser)
.putString(key(profile, WG_EXIT_PORT), forms.wireGuardExitPort)
.putString(key(profile, WG_EXIT_DNS), forms.wireGuardExitDns)
.putString(key(profile, WARP_MTU), warpMtu)
editor.putSecret(profile, LOCAL_PROXY_PASSWORD, forms.localProxyPassword)
editor.putSecret(profile, EXTERNAL_PROXY_PASSWORD, forms.externalProxyPassword)
editor.putSecret(profile, WG_EXIT_PASSWORD, forms.wireGuardExitPassword)
editor.putSecret(profile, IMPORTED_WG_CONFIG, forms.importedWireGuardConfig)
editor.apply()
}
private fun string(profile: Int, name: String, default: String): String =
prefs.getString(key(profile, name), default) ?: default
private fun secret(profile: Int, name: String): String {
val encryptedKey = encryptedKey(profile, name)
secureStore.decrypt(prefs.getString(encryptedKey, null))?.let { return it }
return prefs.getString(key(profile, name), "").orEmpty()
}
private fun SharedPreferences.Editor.putSecret(profile: Int, name: String, value: String) {
val plainKey = key(profile, name)
remove(plainKey)
if (value.isBlank()) {
remove(encryptedKey(profile, name))
} else {
putString(encryptedKey(profile, name), secureStore.encrypt(value))
}
}
private fun migrateLegacyValuesToProfileZero() {
val legacyNames = NON_SECRET_NAMES + SECRET_NAMES
if (legacyNames.none(prefs::contains)) return
val editor = prefs.edit()
NON_SECRET_NAMES.forEach { name ->
if (prefs.contains(name) && !prefs.contains(key(0, name))) {
editor.putString(key(0, name), prefs.getString(name, "").orEmpty())
}
editor.remove(name)
}
SECRET_NAMES.forEach { name ->
val legacyValue = prefs.getString(name, "").orEmpty()
if (
legacyValue.isNotBlank() &&
!prefs.contains(encryptedKey(0, name)) &&
!prefs.contains(key(0, name))
) {
editor.putString(encryptedKey(0, name), secureStore.encrypt(legacyValue))
}
editor.remove(name)
}
editor.apply()
}
companion object {
const val PREFS_NAME = "wdtt_outbound_forms"
private const val LOCAL_PROXY_PORT = "local_proxy_port"
private const val LOCAL_PROXY_LOGIN = "local_proxy_login"
private const val LOCAL_PROXY_PASSWORD = "local_proxy_password"
private const val EXTERNAL_PROXY_KIND = "external_proxy_kind"
private const val EXTERNAL_PROXY_HOST = "external_proxy_host"
private const val EXTERNAL_PROXY_PORT = "external_proxy_port"
private const val EXTERNAL_PROXY_LOGIN = "external_proxy_login"
private const val EXTERNAL_PROXY_PASSWORD = "external_proxy_password"
private const val WG_EXIT_HOST = "wg_exit_host"
private const val WG_EXIT_SSH_PORT = "wg_exit_ssh_port"
private const val WG_EXIT_USER = "wg_exit_user"
private const val WG_EXIT_PASSWORD = "wg_exit_password"
private const val WG_EXIT_PORT = "wg_exit_port"
private const val WG_EXIT_DNS = "wg_exit_dns"
private const val WARP_MTU = "warp_mtu"
private const val IMPORTED_WG_CONFIG = "imported_wg_config"
private val NON_SECRET_NAMES = listOf(
LOCAL_PROXY_PORT,
LOCAL_PROXY_LOGIN,
EXTERNAL_PROXY_KIND,
EXTERNAL_PROXY_HOST,
EXTERNAL_PROXY_PORT,
EXTERNAL_PROXY_LOGIN,
WG_EXIT_HOST,
WG_EXIT_SSH_PORT,
WG_EXIT_USER,
WG_EXIT_PORT,
WG_EXIT_DNS,
WARP_MTU,
)
private val SECRET_NAMES = listOf(
LOCAL_PROXY_PASSWORD,
EXTERNAL_PROXY_PASSWORD,
WG_EXIT_PASSWORD,
IMPORTED_WG_CONFIG,
)
internal fun key(profile: Int, name: String): String =
"profile_${profile.coerceIn(0, 2)}_$name"
internal fun encryptedKey(profile: Int, name: String): String =
"${key(profile, name)}_encrypted"
internal fun isSecretPlainKey(key: String): Boolean =
SECRET_NAMES.any { key.endsWith("_$it") || key == it }
}
}
@@ -0,0 +1,212 @@
package com.wdtt.plus.ui
/**
* Android-приложения сервисов, которые остаются доступными при ограничениях
* мобильного интернета, а также приложения, часто ограничивающие работу через VPN.
*
* Список пакетов и названий актуализирован по перечням Минцифры и карточкам
* приложений в российских магазинах. Поиск выполняется только среди уже
* установленных приложений, поэтому отсутствующие пакеты ни на что не влияют.
*/
internal val QuickExclusionExactPackages = setOf(
// Государственные и социальные сервисы
"ru.rostel",
"ru.gosuslugi.goskey",
"com.octopod.russianpost.client.android",
"ru.crptech.mark",
// Банки и платежи
"ru.sberbankmobile",
"ru.tinkoff.mb",
"ru.vtb24.mobilebanking.android",
"ru.alfabank.mobile.android",
"logo.com.mbanking",
"ru.mts.bank",
"ru.lewis.dbo",
"ru.gazprombank.android.mobilebank.app",
"ru.nspk.mirpay",
"ru.nspk.sbpay",
// Соцсети, связь и магазины приложений
"com.vkontakte.android",
"com.vk.im",
"com.vk.vkvideo",
"ru.vk.music",
"ru.ok.android",
"ru.oneme.app",
"ru.mail.mailapp",
"ru.mail.cloud",
"ru.vk.store",
// Маркетплейсы, объявления и работа
"ru.ozon.app.android",
"com.wildberries.ru",
"ru.beru.android",
"ru.megamarket",
"ru.sbermarket",
"ru.instamart",
"ru.samokat.android",
"com.avito.android",
"ru.domclick.mortgage",
"ru.hh.android",
// Яндекс
"ru.yandex.searchplugin",
"ru.yandex.yandexmaps",
"ru.yandex.music",
"ru.kinopoisk",
"com.yandex.browser",
"ru.yandex.taxi",
// Операторы связи
"ru.mts",
"ru.beeline.services",
"ru.tele2.mytele2",
"ru.megafon.mlk",
// Магазины, доставка и рестораны
"ru.vkusvill",
"com.icemobile.lenta.prod",
"ru.reksoft.okey",
"ru.myauchan.droid",
"www.metro.com",
"ru.tander.magnit",
"ru.pyaterochka.app.browser",
"ru.perekrestok.app",
"club.chizhik",
"com.logistic.sdek",
"ru.dodopizza.app",
"ru.burgerking",
"com.apegroup.mcdonaldsrussia",
// Транспорт, навигация и путешествия
"ru.dublgis.dgismobile",
"ru.rzd.pass",
"ru.tutu.tutu_emp",
"com.carshering",
"youdrive.today",
"com.belkacar",
"ru.aeroflot",
"com.taxsee.taxsee",
"ru.maximoff.max",
// Видео, музыка, новости и погода
"ru.rutube.app",
"ru.ivi.client",
"ru.more.play",
"ru.zen.android",
"gpm.tnt_premier",
"ru.mts.mtstv",
"ru.radioplayer",
"com.gismeteo.client",
)
internal val QuickExclusionKeywords = listOf(
"sber", "сбер",
"tinkoff", "t-bank", "tbank", "тинькофф", "т-банк", "тбанк",
"vtb", "втб",
"alfa", "alpha", "альфа",
"psbank", "промсвязьбанк", "псб",
"gazprombank", "газпромбанк",
"mir pay", "mirpay", "мир пэй",
"sbpay", "сбпэй",
"ozon", "озон",
"wildberries", "вайлдберриз",
"yandex", "яндекс",
"vkontakte", "вконтакте",
"rutube", "рутуб",
"gosuslugi", "госуслуг", "госключ",
"честный знак",
"dublgis", "2gis", "dgis", "дубльгис",
"avito", "авито",
"domclick", "домклик",
"headhunter", "hh.ru",
"mts", "мтс",
"beeline", "билайн",
"megafon", "мегафон",
"tele2", "теле2",
"mail.ru", "mailapp",
"ok.ru", "odnoklassniki", "одноклассники",
"kinopoisk", "кинопоиск",
"samokat", "самокат",
"megamarket", "мегамаркет", "sbermarket",
"kuper", "купер", "instamart",
"rostel", "ростел",
"почта россии", "russianpost",
"max: общение", "макс: общение", "oneme",
"vkusvill", "вкусвилл",
"lenta.prod", "лента – доставка", "лента - доставка",
"okeydostavka", "гипермаркеты и доставка",
"myauchan", "мой ашан",
"metro: продукты", "метро: продукты",
"tander.magnit", "магнит: акции",
"pyaterochka", "пятёрочка:", "пятерочка:",
"perekrestok", "перекрёсток доставка", "перекресток доставка",
"club.chizhik", "чижик - доставка", "чижик — доставка",
"cdek", "сдэк",
"dostavista", "достависта",
"dodopizza", "додо пицца",
"burgerking", "бургер кинг",
"mcdonaldsrussia", "вкусно — и точка", "вкусно - и точка",
"детский мир", "detmir",
"петрович", "petrovich",
"spar —", "spar -", "мой spar",
"дикси", "dixy",
"vprok", "впрок",
"5post", "fivepost",
"много лосося",
"rzd.pass", "ржд пассажирам",
"tutu", "туту:",
"carshering", "делимобиль",
"citydrive", "ситидрайв", "youdrive",
"belkacar", "белкаcar",
"aeroflot", "аэрофлот",
"pobeda", "победа",
"s7 airlines",
"деловые линии",
"гранд сервис экспресс",
"taxsee", "maxim — заказ такси", "maxim - заказ такси", "maximoff",
"gismeteo", "гисметео",
"ivi.client", "иви:",
"more.play", "okko:",
"zen.android", "дзен",
"tnt_premier", "premier —", "premier -",
"mtstv", "кион",
"radioplayer", "радиоплеер",
"medsi", "медси",
"мать и дитя",
"iomt.istok",
"сателлит online",
"м-лайн", "m-line",
"inme",
"yuwell anytime",
"follow anytime", "anytime follow",
"ican health", "ican reach",
"mq cgm",
"freestyle libre",
"medtrum",
"syai link",
"poctech cgm",
"hematonix",
"дианянь",
"lumipod", "glutec", "lumiflex",
"trueconf", "труконф",
"лизаалерт",
"рувики",
"добро.рф",
"цезарь сателлит",
"тензор",
"скб контур",
"эвотор",
"мп. инспектор",
"1с:",
"hrlink",
"кхл",
)
internal fun matchesQuickExclusionApp(name: String, packageName: String): Boolean {
val packageLower = packageName.lowercase()
if (packageLower in QuickExclusionExactPackages) return true
val haystack = "$packageLower ${name.lowercase()}"
return QuickExclusionKeywords.any(haystack::contains)
}
@@ -128,6 +128,8 @@ import com.wdtt.plus.ServerClientCreateRequest
import com.wdtt.plus.ServerClientInfo
import com.wdtt.plus.ServerTrafficPeriod
import com.wdtt.plus.TransferFiles
import com.wdtt.plus.WdttDocument
import com.wdtt.plus.VkJoinLink
import com.wdtt.plus.WDTTColors
import com.wdtt.plus.connectionLink
import kotlinx.coroutines.Dispatchers
@@ -163,6 +165,21 @@ private enum class ClientVkHashFilter { All, Present, Missing }
private enum class ClientsServerRefreshState { Unknown, Ready, Error }
private data class ClientQrData(
val title: String,
val bitmap: Bitmap,
val missingVkHashes: Boolean
)
private fun vkHashInputError(value: String): String? {
if (value.isBlank()) return null
return if (VkJoinLink.normalizeHashes(value) == null) {
"Проверьте VK-хеш: допустимы латинские буквы, цифры, _ и - либо ссылка VK-звонка."
} else {
null
}
}
internal fun serverClientsAccessIssue(
host: String,
hostValid: Boolean,
@@ -354,7 +371,7 @@ fun ServerClientsSection(
var changedPasswordClient by remember { mutableStateOf<ServerClientInfo?>(null) }
var pendingAction by remember { mutableStateOf<PendingClientAction?>(null) }
var expiryClient by remember { mutableStateOf<ServerClientInfo?>(null) }
var qrData by remember { mutableStateOf<Pair<String, Bitmap>?>(null) }
var qrData by remember { mutableStateOf<ClientQrData?>(null) }
var detailsClient by remember { mutableStateOf<ServerClientInfo?>(null) }
var showServerTools by rememberSaveable { mutableStateOf(false) }
var createdClient by remember { mutableStateOf<ServerClientInfo?>(null) }
@@ -814,10 +831,16 @@ fun ServerClientsSection(
scope.launch {
runCatching {
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-${selectedClient.safeFileName()}.wdtt", link)
TransferFiles.writeTransferText(
context,
WdttDocument.fileName(
"WDTT-Plus-${selectedClient.safeFileName()}"
),
link
)
}
}.onSuccess {
shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus")
}.onFailure {
Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show()
}
@@ -827,7 +850,13 @@ fun ServerClientsSection(
scope.launch {
runCatching {
withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
}.onSuccess { qrData = selectedClient.displayName() to it }
}.onSuccess {
qrData = ClientQrData(
title = selectedClient.displayName(),
bitmap = it,
missingVkHashes = selectedClient.vkHash.isBlank()
)
}
.onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() }
}
},
@@ -1039,7 +1068,13 @@ fun ServerClientsSection(
onQr = {
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, transfer) } }
.onSuccess { qrData = "Перенос: ${client.displayName()}" to it }
.onSuccess {
qrData = ClientQrData(
title = "Перенос: ${client.displayName()}",
bitmap = it,
missingVkHashes = client.vkHash.isBlank()
)
}
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
}
},
@@ -1050,7 +1085,12 @@ fun ServerClientsSection(
TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt-client", transfer)
}
}.onSuccess {
shareUri(context, it, "application/vnd.wdtt.plus.client", "Передать клиента WDTT Plus")
shareUri(
context,
it,
WdttDocument.LEGACY_CLIENT_MIME_TYPE,
"Передать клиента WDTT Plus"
)
}.onFailure { status = "Ошибка: ${it.message ?: "файл клиента не создан"}" }
}
}
@@ -1119,7 +1159,8 @@ fun ServerClientsSection(
title = "Клиент создан",
password = client.password,
link = link,
noLinkText = "VK-хеш не задан. Пароль уже работает; ссылку, QR и файл можно создать после добавления хеша в «Подробнее».",
missingVkHashes = client.vkHash.isBlank(),
noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.",
onDismiss = { createdClient = null },
onCopyPassword = { copyText(context, "Пароль WDTT", client.password) },
onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } },
@@ -1128,7 +1169,9 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
.onSuccess { qrData = client.displayName() to it }
.onSuccess {
qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank())
}
.onFailure { Toast.makeText(context, it.message ?: "Не удалось создать QR.", Toast.LENGTH_LONG).show() }
}
}
@@ -1137,8 +1180,14 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") }
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(
context,
WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"),
value
)
}
}.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") }
.onFailure { Toast.makeText(context, it.message ?: "Не удалось создать файл.", Toast.LENGTH_LONG).show() }
}
}
@@ -1157,7 +1206,8 @@ fun ServerClientsSection(
statusText = "Клиент импортирован и найден в списке.",
password = client.password,
link = link,
noLinkText = "VK-хеш не задан. Клиент добавлен; хеш можно указать в «Подробнее».",
missingVkHashes = client.vkHash.isBlank(),
noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.",
onDismiss = { importedClient = null },
onCopyPassword = { copyText(context, "Пароль импортированного клиента", client.password) },
onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } },
@@ -1166,7 +1216,9 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
.onSuccess { qrData = client.displayName() to it }
.onSuccess {
qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank())
}
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
}
}
@@ -1175,8 +1227,14 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") }
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(
context,
WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"),
value
)
}
}.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus") }
.onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" }
}
}
@@ -1194,7 +1252,8 @@ fun ServerClientsSection(
title = "Пароль изменён",
password = client.password,
link = link,
noLinkText = "VK-хеш не задан. Новый пароль уже работает; добавьте хеш в «Подробнее», чтобы сформировать ссылку.",
missingVkHashes = client.vkHash.isBlank(),
noLinkText = "Не удалось создать ссылку. Проверьте адрес сервера и порты клиента.",
onDismiss = { changedPasswordClient = null },
onCopyPassword = { copyText(context, "Новый пароль WDTT", client.password) },
onCopyLink = { link?.let { copyText(context, "Новая ссылка WDTT", it) } },
@@ -1203,7 +1262,9 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
.onSuccess { qrData = client.displayName() to it }
.onSuccess {
qrData = ClientQrData(client.displayName(), it, client.vkHash.isBlank())
}
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
}
}
@@ -1212,8 +1273,14 @@ fun ServerClientsSection(
link?.let { value ->
scope.launch {
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать новое подключение WDTT Plus") }
withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(
context,
WdttDocument.fileName("WDTT-Plus-${client.safeFileName()}"),
value
)
}
}.onSuccess { shareUri(context, it, WdttDocument.MIME_TYPE, "Передать новое подключение WDTT Plus") }
.onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" }
}
}
@@ -1287,17 +1354,18 @@ fun ServerClientsSection(
}
}
qrData?.let { (title, bitmap) ->
qrData?.let { qr ->
ClientQrDialog(
title = title,
bitmap = bitmap,
title = qr.title,
bitmap = qr.bitmap,
missingVkHashes = qr.missingVkHashes,
onDismiss = { qrData = null },
onShare = {
scope.launch {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png"
val fileName = "WDTT-Plus-QR-${qr.title.safeQrFileName()}-$stamp.png"
runCatching {
withContext(Dispatchers.IO) { TransferFiles.writeQrPng(context, fileName, bitmap) }
withContext(Dispatchers.IO) { TransferFiles.writeQrPng(context, fileName, qr.bitmap) }
}.onSuccess { shareUri(context, it, "image/png", "Передать QR-код WDTT Plus") }
.onFailure { Toast.makeText(context, it.message ?: "Не удалось поделиться QR.", Toast.LENGTH_LONG).show() }
}
@@ -1305,8 +1373,11 @@ fun ServerClientsSection(
onSave = {
scope.launch {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val fileName = "WDTT-Plus-QR-${qr.title.safeQrFileName()}-$stamp.png"
runCatching {
withContext(Dispatchers.IO) { TransferFiles.saveQrToGallery(context, "WDTT-Plus-client-$stamp.png", bitmap) }
withContext(Dispatchers.IO) {
TransferFiles.saveQrToGallery(context, fileName, qr.bitmap)
}
}.onSuccess {
Toast.makeText(context, "QR-код сохранён.", Toast.LENGTH_SHORT).show()
}.onFailure {
@@ -1394,7 +1465,7 @@ private fun ServerClientCard(
)
if (client.vkHash.isBlank()) {
Text(
"VK-хеш не задан: быструю ссылку/QR создать нельзя, пока не обновить хеш.",
"VK-хеш не задан: доступ можно передать, но клиенту нужно добавить свой перед запуском.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
@@ -1684,6 +1755,7 @@ private fun AccessResultDialog(
statusText: String? = null,
password: String,
link: String?,
missingVkHashes: Boolean,
noLinkText: String,
onDismiss: () -> Unit,
onCopyPassword: () -> Unit,
@@ -1718,7 +1790,15 @@ private fun AccessResultDialog(
if (link == null) {
Text(noLinkText, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
} else {
Text("Ссылка содержит пароль и VK-хеш. Не публикуйте её.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
Text(
if (missingVkHashes) {
"VK-хеш не задан. Передать можно, но клиенту нужно добавить свой перед запуском."
} else {
"Ссылка содержит пароль и VK-хеш. Не публикуйте её."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
@@ -1754,6 +1834,7 @@ private fun ClientDetailsDialog(
var hash by rememberSaveable(client.password) { mutableStateOf(client.vkHash) }
var ports by rememberSaveable(client.password) { mutableStateOf(client.ports) }
val portsValid = ports.isPortsSpec()
val hashError = vkHashInputError(hash)
val link = remember(client, fallbackHost, publicHost, sourceProfileName) {
client.connectionLink(fallbackHost, publicHost, sourceProfileName)
}
@@ -1854,8 +1935,10 @@ private fun ClientDetailsDialog(
)
OutlinedTextField(
value = hash,
onValueChange = { hash = it },
onValueChange = { hash = it.take(4096) },
label = { Text("VK-хеш или ссылка") },
supportingText = { hashError?.let { Text(it) } },
isError = hashError != null,
minLines = 2,
modifier = Modifier.fillMaxWidth()
)
@@ -1903,7 +1986,10 @@ private fun ClientDetailsDialog(
},
confirmButton = {
if (step == ClientDetailsStep.Edit) {
Button(onClick = { onSave(label, hash, ports) }, enabled = !busy && portsValid) { Text("Сохранить") }
Button(
onClick = { onSave(label, hash, ports) },
enabled = !busy && portsValid && hashError == null
) { Text("Сохранить") }
}
}
)
@@ -1949,7 +2035,8 @@ private fun ServerToolsDialog(
ServerToolsStep.Overview -> {
Text("Состояние", fontWeight = FontWeight.Bold)
InfoLine("Клиенты", "${state.passwordCount}/${state.maxPasswords}")
InfoLine("Устройства", state.deviceCount.toString())
InfoLine("Устройства клиентов", state.deviceCount.toString())
InfoLine("Устройства владельца", state.ownerDeviceCount.toString())
InfoLine("Истёкшие", state.expiredCount.toString())
InfoLine("Забытые устройства", state.orphanDeviceCount.toString())
InfoLine(
@@ -2549,6 +2636,7 @@ private fun CreateClientWizardDialog(
var customPassword by rememberSaveable { mutableStateOf("") }
val effectivePorts = if (useDefaultPorts) defaultPorts else customPorts
val portsValid = effectivePorts.isPortsSpec()
val hashError = vkHashInputError(vkHash)
val passwordError = if (useAutoPassword || customPassword.isEmpty()) null else when {
ClientPasswordRules.validate(customPassword) != null -> ClientPasswordRules.validate(customPassword)
customPassword == mainPassword -> "Пароль клиента не должен совпадать с главным паролем."
@@ -2614,11 +2702,16 @@ private fun CreateClientWizardDialog(
}
ClientWizardStep.Hash -> {
Text("VK-хеш", fontWeight = FontWeight.Bold)
Text("Нужен для быстрой ссылки, QR и файла. Можно вставить сам хеш или ссылку приглашения.", style = MaterialTheme.typography.bodySmall)
Text(
"Лучше добавить перед передачей. Без хеша доступ тоже можно отправить, но клиенту придётся добавить свой.",
style = MaterialTheme.typography.bodySmall
)
OutlinedTextField(
value = vkHash,
onValueChange = { vkHash = it },
onValueChange = { vkHash = it.take(4096) },
label = { Text("Хеш или ссылка") },
supportingText = { hashError?.let { Text(it) } },
isError = hashError != null,
minLines = 2,
modifier = Modifier.fillMaxWidth()
)
@@ -2682,6 +2775,13 @@ private fun CreateClientWizardDialog(
Text("VK-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}")
Text("Порты: $effectivePorts")
Text("Пароль: ${if (useAutoPassword) "будет создан автоматически" else customPassword}")
if (vkHash.isBlank()) {
Text(
"Без VK-хеша клиент добавит свой перед запуском.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
}
Text(
"Новый доступ начнёт работать сразу, текущие подключения не прервутся.",
style = MaterialTheme.typography.bodySmall,
@@ -2696,6 +2796,7 @@ private fun CreateClientWizardDialog(
confirmButton = {
Button(
enabled = !busy &&
(step != ClientWizardStep.Hash || hashError == null) &&
(step != ClientWizardStep.Ports || portsValid) &&
(step != ClientWizardStep.Password || passwordValid),
onClick = {
@@ -2811,6 +2912,7 @@ private fun ExtendClientDialog(
private fun ClientQrDialog(
title: String,
bitmap: Bitmap,
missingVkHashes: Boolean,
onDismiss: () -> Unit,
onShare: () -> Unit,
onSave: () -> Unit
@@ -2837,7 +2939,15 @@ private fun ClientQrDialog(
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Image(bitmap = bitmap.asImageBitmap(), contentDescription = "QR-код WDTT Plus", modifier = Modifier.fillMaxWidth())
}
Text("QR содержит пароль и VK-хеш. Не публикуйте изображение.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
Text(
if (missingVkHashes) {
"VK-хеш не задан. Клиенту нужно добавить свой перед запуском."
} else {
"QR содержит пароль и VK-хеш. Не публикуйте изображение."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,35 @@
package com.wdtt.plus.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
internal fun StableSegmentedButtonIcon(selected: Boolean) {
Box(
modifier = Modifier.size(18.dp),
contentAlignment = Alignment.Center
) {
AnimatedVisibility(
visible = selected,
enter = fadeIn(tween(120)),
exit = fadeOut(tween(90))
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
}
}
}
@@ -64,6 +64,7 @@ import com.journeyapps.barcodescanner.ScanOptions
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TransferFiles
import com.wdtt.plus.WdttTransferCodec
import com.wdtt.plus.WdttDocument
import com.wdtt.plus.QrCaptureActivity
import com.wdtt.plus.vpnProfileDisplayName
import kotlinx.coroutines.Dispatchers
@@ -112,7 +113,7 @@ fun TransferCenterDialog(
onIncomingContent(text)
}
}
val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) runCatchingUi {
val text = withContext(Dispatchers.IO) { TransferFiles.readText(context, uri) }
onIncomingContent(text)
@@ -129,6 +130,12 @@ fun TransferCenterDialog(
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Box(modifier = Modifier.fillMaxWidth()) {
Text(
"Получение/Передача",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
modifier = Modifier.align(androidx.compose.ui.Alignment.CenterStart),
)
IconButton(
onClick = onDismiss,
enabled = !busy,
@@ -137,7 +144,14 @@ fun TransferCenterDialog(
Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
}
}
Text("Получение VPN", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text("Получить профиль", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Добавьте профиль через камеру, изображение или файл. "
+ "Если сервис выдал обновление, приложение применит его "
+ "к связанному профилю.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -154,11 +168,13 @@ fun TransferCenterDialog(
)
}
TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") }
TransferButton("Файл", Icons.Default.FileOpen, busy) { fileLauncher.launch("*/*") }
TransferButton("Файл", Icons.Default.FileOpen, busy) {
fileLauncher.launch(WdttDocument.acceptedMimeTypes())
}
}
HorizontalDivider()
Text("Передача $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text("Передать $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.",
style = MaterialTheme.typography.bodySmall,
@@ -185,9 +201,15 @@ fun TransferCenterDialog(
runCatchingUi {
val link = settingsStore.connectionLinkForProfile(activeProfile)
val uri = withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-${activeProfileLabel.safeTransferFileName()}.wdtt", link)
TransferFiles.writeTransferText(
context,
WdttDocument.fileName(
"WDTT-Plus-${activeProfileLabel.safeTransferFileName()}"
),
link
)
}
shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
shareUri(context, uri, WdttDocument.MIME_TYPE, "Передать подключение WDTT Plus")
}
}
}
@@ -253,7 +275,12 @@ fun TransferCenterDialog(
val uri = withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-admin-$stamp.wdtt-backup", encrypted)
}
shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать настройки WDTT Plus")
shareUri(
context,
uri,
WdttDocument.LEGACY_TRANSFER_MIME_TYPE,
"Передать настройки WDTT Plus"
)
}
}
}
@@ -279,9 +306,10 @@ fun TransferCenterDialog(
onSave = {
scope.launch {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png"
runCatching {
withContext(Dispatchers.IO) {
TransferFiles.saveQrToGallery(context, "WDTT-Plus-QR-$stamp.png", bitmap)
TransferFiles.saveQrToGallery(context, fileName, bitmap)
}
}.onSuccess {
Toast.makeText(context, "QR-код сохранён в галерею.", Toast.LENGTH_SHORT).show()
@@ -0,0 +1,940 @@
package com.wdtt.plus.ui
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.VpnKey
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.plus.BUILT_IN_VK_CLIENT_IDS
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.isValidVkClientId
import com.wdtt.plus.normalizeVkClientId
import com.wdtt.plus.normalizeVkClientSecret
import java.security.MessageDigest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import kotlin.math.ceil
import kotlin.math.max
private const val VK_CLIENT_ID_PROBE_VERSION = 3
internal const val VK_CLIENT_ID_PROBE_COOLDOWN_MS = 10_000L
private const val VK_CLIENT_ID_PROBE_CHECKED_AT = "_checked_at"
private const val VK_ID_CABINET_URL = "https://id.vk.ru/about/business/go/"
internal enum class VkClientIdProbeStatus {
LegacyCompatible,
LegacyRejected,
CheckFailed
}
internal data class VkClientIdProbeCache(
val results: Map<String, VkClientIdProbeStatus>,
val checkedAt: Long
)
internal fun vkClientIdProbeCooldownRemainingMillis(now: Long, lastStartedAt: Long): Long {
if (lastStartedAt <= 0L) return 0L
val elapsed = (now - lastStartedAt).coerceAtLeast(0L)
return (VK_CLIENT_ID_PROBE_COOLDOWN_MS - elapsed).coerceAtLeast(0L)
}
internal fun vkClientIdAvailabilityMessage(
ids: List<String>,
results: Map<String, VkClientIdProbeStatus>
): String {
val cleanIds = ids.map(String::trim).filter(String::isNotEmpty).distinct()
val available = cleanIds.filter { results[it] == VkClientIdProbeStatus.LegacyCompatible }
val rejected = cleanIds.filter { results[it] == VkClientIdProbeStatus.LegacyRejected }
val failed = cleanIds.filter { results[it] == VkClientIdProbeStatus.CheckFailed }
return when {
cleanIds.size == 1 && available.isNotEmpty() ->
"Client ID ${cleanIds.first()} принимается резервным способом"
cleanIds.size == 1 && rejected.isNotEmpty() ->
"Client ID ${cleanIds.first()} не принимается резервным способом"
cleanIds.size == 1 ->
"Не удалось проверить Client ID ${cleanIds.first()}: сеть или временная ошибка VK"
rejected.isEmpty() && failed.isEmpty() -> "Все встроенные Client ID доступны для резервного способа"
else -> buildList {
if (available.isNotEmpty()) add("Доступны: ${available.joinToString(", ")}")
if (rejected.isNotEmpty()) add("Не принимаются: ${rejected.joinToString(", ")}")
if (failed.isNotEmpty()) add("Не удалось проверить: ${failed.joinToString(", ")}")
}.joinToString(". ", postfix = ".")
}
}
internal fun vkClientIdsForAutomaticProbe(
customCredentialsEnabled: Boolean,
customClientId: String,
customClientSecret: String
): List<String> = if (customCredentialsEnabled) {
customClientId.trim().takeIf(::isValidVkClientId)
?.takeIf { customClientSecret.trim().isNotEmpty() }
?.let(::listOf)
.orEmpty()
} else {
BUILT_IN_VK_CLIENT_IDS
}
private object VkClientIdProbeRateLimiter {
private var lastStartedAt = 0L
@Synchronized
fun acquire(now: Long, persistedCheckedAt: Long): Long {
val effectiveLastStartedAt = max(lastStartedAt, persistedCheckedAt)
val remaining = vkClientIdProbeCooldownRemainingMillis(now, effectiveLastStartedAt)
if (remaining == 0L) lastStartedAt = now
return remaining
}
}
@Composable
fun VkClientSettingsDialog(
settingsStore: SettingsStore,
activeClientIds: String,
onClientIdsChange: (String) -> Unit,
onDismiss: () -> Unit
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val configuration = LocalConfiguration.current
val enabledState by remember(settingsStore) {
settingsStore.customVkCredentialsEnabled.map { it as Boolean? }
}.collectAsStateWithLifecycle(initialValue = null)
val savedClientIdState by remember(settingsStore) {
settingsStore.customVkClientId.map { it as String? }
}.collectAsStateWithLifecycle(initialValue = null)
val savedClientSecretState by remember(settingsStore) {
settingsStore.customVkClientSecret.map { it as String? }
}.collectAsStateWithLifecycle(initialValue = null)
val checkResultsJsonState by remember(settingsStore) {
settingsStore.clientIdCheckResults.map { it as String? }
}.collectAsStateWithLifecycle(initialValue = null)
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
val enabled = enabledState == true
val savedClientId = savedClientIdState.orEmpty()
val savedClientSecret = savedClientSecretState.orEmpty()
val settingsReady = enabledState != null && savedClientIdState != null &&
savedClientSecretState != null && checkResultsJsonState != null
val probeCache = remember(checkResultsJsonState) {
parseVkClientIdCheckResults(checkResultsJsonState.orEmpty())
}
val checkResults = probeCache.results
val builtInSelection = remember(activeClientIds) {
activeClientIds.split(',').map { it.trim() }.filter { it.isNotEmpty() }
}
var clientIdInput by rememberSaveable { mutableStateOf("") }
var clientSecretInput by rememberSaveable { mutableStateOf("") }
var inputsInitialized by rememberSaveable { mutableStateOf(false) }
var secretFocused by remember { mutableStateOf(false) }
var checkingIds by remember { mutableStateOf<Set<String>>(emptySet()) }
var showHelp by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(settingsReady) {
if (settingsReady && !inputsInitialized) {
clientIdInput = savedClientId
clientSecretInput = savedClientSecret
inputsInitialized = true
}
}
val normalizedClientId = normalizeVkClientId(clientIdInput)
val normalizedClientSecret = normalizeVkClientSecret(clientSecretInput)
val customInputComplete = isValidVkClientId(normalizedClientId) && normalizedClientSecret.isNotBlank()
val hasUnsavedChanges = inputsInitialized && (
normalizedClientId != savedClientId || normalizedClientSecret != savedClientSecret
)
fun checkIds(ids: List<String>, manual: Boolean) {
val cleanIds = ids.map(String::trim).filter(::isValidVkClientId).distinct()
if (cleanIds.isEmpty()) return
if (checkingIds.isNotEmpty()) {
if (manual) Toast.makeText(context, "Проверка уже выполняется", Toast.LENGTH_SHORT).show()
return
}
val startedAt = System.currentTimeMillis()
val cooldownRemaining = VkClientIdProbeRateLimiter.acquire(startedAt, probeCache.checkedAt)
if (cooldownRemaining > 0L) {
if (manual) {
val seconds = ceil(cooldownRemaining / 1_000.0).toInt().coerceAtLeast(1)
Toast.makeText(
context,
"Повторная проверка будет доступна через $seconds с",
Toast.LENGTH_SHORT
).show()
}
return
}
checkingIds = cleanIds.toSet()
scope.launch {
try {
val checkedNow = withContext(Dispatchers.IO) {
buildMap {
cleanIds.forEach { id ->
put(id, checkVkClientId(id))
}
}
}
val freshResults = checkResults.toMutableMap().apply { putAll(checkedNow) }
settingsStore.saveClientIdCheckResults(
encodeVkClientIdCheckResults(freshResults, startedAt)
)
Toast.makeText(
context,
vkClientIdAvailabilityMessage(cleanIds, checkedNow),
Toast.LENGTH_LONG
).show()
} finally {
checkingIds = emptySet()
}
}
}
LaunchedEffect(settingsReady, enabled, savedClientId, savedClientSecret) {
if (settingsReady) {
checkIds(
vkClientIdsForAutomaticProbe(enabled, savedClientId, savedClientSecret),
manual = false
)
}
}
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.fillMaxHeight(0.9f)
.heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)),
shape = RoundedCornerShape(30.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
shadowElevation = 8.dp
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) {
Icon(Icons.Default.VpnKey, contentDescription = null, modifier = Modifier.size(25.dp))
}
}
Column(modifier = Modifier.weight(1f)) {
Text(
"Клиенты VK",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
"Настройка для текущего VPN-профиля",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
if (!settingsReady) {
Box(
modifier = Modifier.fillMaxWidth().height(180.dp),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
} else {
if (tunnelRunning) {
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.errorContainer
) {
Text(
"VPN сейчас работает. Чтобы изменить резервные Client ID, сначала выключите VPN. Проверка доступности остаётся доступной.",
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
fontWeight = FontWeight.SemiBold
)
}
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
) {
Row(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text("Собственные резервные реквизиты", fontWeight = FontWeight.SemiBold)
Text(
if (enabled) {
"После быстрого VKCalls сначала пробуется ваш Client ID."
} else {
"После быстрого VKCalls используются встроенные Client ID."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch(
checked = enabled,
enabled = !tunnelRunning,
onCheckedChange = { checked ->
scope.launch { settingsStore.saveCustomVkCredentialsEnabled(checked) }
}
)
}
}
if (enabled) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text("Резервные реквизиты приложения VK", fontWeight = FontWeight.Bold)
Text(
"Оба поля обязательны",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = { showHelp = true }) {
Icon(
Icons.AutoMirrored.Filled.HelpOutline,
contentDescription = "Как получить Client ID и secret"
)
}
}
OutlinedTextField(
value = clientIdInput,
onValueChange = { clientIdInput = normalizeVkClientId(it) },
modifier = Modifier.fillMaxWidth(),
label = { Text("Client ID") },
supportingText = { Text("ID приложения из кабинета VK ID") },
enabled = !tunnelRunning,
singleLine = true,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = KeyboardType.Number
)
)
OutlinedTextField(
value = clientSecretInput,
onValueChange = { clientSecretInput = it.take(512) },
modifier = Modifier
.fillMaxWidth()
.onFocusChanged { secretFocused = it.isFocused },
label = { Text("Client secret") },
supportingText = {
Text("Защищённый ключ скрывается после выхода из поля")
},
enabled = !tunnelRunning,
singleLine = true,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = KeyboardType.Password
),
visualTransformation = if (secretFocused) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
}
)
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.45f)
) {
Text(
"Защищённый ключ сохраняется в зашифрованном виде через Android Keystore и не добавляется в журналы.",
modifier = Modifier.padding(13.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
}
if (hasUnsavedChanges) {
Text(
"Есть несохранённые изменения",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary,
fontWeight = FontWeight.SemiBold
)
}
Button(
onClick = {
scope.launch {
settingsStore.saveCustomVkCredentials(
normalizedClientId,
normalizedClientSecret
)
clientIdInput = normalizedClientId
clientSecretInput = normalizedClientSecret
Toast.makeText(context, "Реквизиты сохранены", Toast.LENGTH_SHORT).show()
}
},
enabled = !tunnelRunning && customInputComplete && hasUnsavedChanges,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp)
) {
Text("Сохранить")
}
val customProbeResult = checkResults[normalizedClientId]
OutlinedButton(
onClick = { checkIds(listOf(normalizedClientId), manual = true) },
enabled = isValidVkClientId(normalizedClientId) && checkingIds.isEmpty(),
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp)
) {
Text(if (normalizedClientId in checkingIds) "Проверка…" else "Проверить Client ID")
}
if (customProbeResult != null && normalizedClientId !in checkingIds) {
val statusColor = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible -> MaterialTheme.colorScheme.primaryContainer
VkClientIdProbeStatus.LegacyRejected -> MaterialTheme.colorScheme.errorContainer
VkClientIdProbeStatus.CheckFailed -> MaterialTheme.colorScheme.tertiaryContainer
}
val statusContentColor = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible -> MaterialTheme.colorScheme.onPrimaryContainer
VkClientIdProbeStatus.LegacyRejected -> MaterialTheme.colorScheme.onErrorContainer
VkClientIdProbeStatus.CheckFailed -> MaterialTheme.colorScheme.onTertiaryContainer
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = statusColor
) {
Row(
modifier = Modifier.fillMaxWidth().padding(13.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Icon(
imageVector = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible -> Icons.Default.CheckCircle
VkClientIdProbeStatus.LegacyRejected -> Icons.Default.Cancel
VkClientIdProbeStatus.CheckFailed -> Icons.Default.WarningAmber
},
contentDescription = null,
tint = statusContentColor
)
Text(
text = when (customProbeResult) {
VkClientIdProbeStatus.LegacyCompatible ->
"Client ID принимается резервным способом"
VkClientIdProbeStatus.LegacyRejected ->
"Client ID не принимается резервным способом"
VkClientIdProbeStatus.CheckFailed ->
"Проверку выполнить не удалось: сеть или временная ошибка VK"
},
style = MaterialTheme.typography.bodySmall,
color = statusContentColor,
fontWeight = FontWeight.SemiBold
)
}
}
}
Text(
"Сохранённый собственный Client ID проверяется автоматически при входе. Это второй вариант после VKCalls. Такая проверка подтверждает только приём ID старым способом VK; получение TURN-данных окончательно проверяется при подключении.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Text("Встроенный резерв", fontWeight = FontWeight.Bold)
Text(
if (enabled) {
"Используется, если VKCalls и собственные реквизиты не сработали. Встроенный ID можно проверить нажатием на строку."
} else {
"Используется, если VKCalls не сработал. Проверка запускается автоматически при входе; нажмите на строку для повтора."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
BUILT_IN_VK_CLIENT_IDS.forEach { id ->
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.42f),
onClick = { checkIds(listOf(id), manual = true) }
) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = id in builtInSelection,
enabled = !tunnelRunning,
onCheckedChange = { checked ->
val updated = if (checked) {
(builtInSelection + id).distinct()
} else {
builtInSelection - id
}
if (updated.isNotEmpty()) {
onClientIdsChange(updated.joinToString(","))
} else {
Toast.makeText(
context,
"Нельзя отключить все Client ID: без них программа перестанет работать",
Toast.LENGTH_LONG
).show()
}
}
)
Column(modifier = Modifier.weight(1f)) {
Text(id, fontWeight = FontWeight.SemiBold)
Text(
if (id in builtInSelection) "Выбран для резерва" else "Отключён",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Box(
modifier = Modifier.size(36.dp),
contentAlignment = Alignment.Center
) {
when {
id in checkingIds -> CircularProgressIndicator(
modifier = Modifier.size(22.dp),
strokeWidth = 2.5.dp
)
checkResults[id] == VkClientIdProbeStatus.LegacyCompatible -> Icon(
Icons.Default.CheckCircle,
contentDescription = "Client ID доступен для резервного способа",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
checkResults[id] == VkClientIdProbeStatus.LegacyRejected -> Icon(
Icons.Default.Cancel,
contentDescription = "Client ID недоступен для резервного способа",
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(24.dp)
)
checkResults[id] == VkClientIdProbeStatus.CheckFailed -> Icon(
Icons.Default.WarningAmber,
contentDescription = "Не удалось проверить Client ID",
tint = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.size(24.dp)
)
else -> Text(
"—",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f))
Text(
if (enabled) {
"Порядок подключения: быстрый VKCalls без капчи → собственные реквизиты → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
} else {
"Порядок подключения: быстрый VKCalls без капчи → встроенный резерв. Если резервный способ запросит капчу, приложение попробует решить её автоматически."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
if (showHelp) {
VkClientCredentialsHelpDialog(onDismiss = { showHelp = false })
}
}
@Composable
private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) {
val context = LocalContext.current
val clipboard = LocalClipboardManager.current
val configuration = LocalConfiguration.current
val packageName = context.packageName
val signingSha1 = remember(context) { appSigningSha1(context) }
fun copy(value: String, message: String) {
clipboard.setText(AnnotatedString(value))
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Surface(
modifier = Modifier
.fillMaxWidth(0.92f)
.fillMaxHeight(0.9f)
.heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)),
shape = RoundedCornerShape(30.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 10.dp,
shadowElevation = 10.dp
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
"Резервные реквизиты VK",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
"Резервный провайдер через кабинет VK ID",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.65f)
) {
Text(
"Собственные реквизиты относятся только к резервному legacy-провайдеру. Для основного быстрого VKCalls они не нужны. Понадобятся ID приложения и Защищённый ключ из одного приложения VK; сервисный ключ доступа не подходит.",
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
}
HelpStep(
number = 1,
title = "Откройте кабинет VK ID",
text = "Войдите в аккаунт владельца приложения, откройте раздел «Мои приложения» и нажмите «Добавить приложение»."
)
Button(
onClick = {
runCatching {
context.startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse(VK_ID_CABINET_URL)))
}
},
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp)
) {
Text("Открыть кабинет VK ID")
}
HelpStep(
number = 2,
title = "Создайте Android-приложение",
text = "Укажите понятное название, выберите платформу Android, затем заполните имя пакета и SHA-1 подписи установленного APK."
)
CopyValueCard(
label = "Название пакета",
value = packageName,
onCopy = { copy(packageName, "Название пакета скопировано") }
)
CopyValueCard(
label = "SHA-1 подписи этого APK",
value = signingSha1.ifBlank { "Не удалось определить" },
onCopy = signingSha1.takeIf(String::isNotBlank)?.let { sha1 ->
{ copy(sha1, "SHA-1 скопирован") }
}
)
HelpStep(
number = 3,
title = "Скопируйте реквизиты",
text = "После создания откройте карточку приложения → «Приложение» → «Информация о приложении». Поле «ID приложения» вставьте как Client ID, а поле «Защищённый ключ» — как Client secret."
)
HelpStep(
number = 4,
title = "Сохраните и проверьте",
text = "Вернитесь в WDTT Plus, заполните оба поля, нажмите «Сохранить», затем «Проверить Client ID». Для полного доступа к ключам VK может попросить подтвердить профиль бизнеса."
)
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.55f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.25f))
) {
Column(
modifier = Modifier.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Text("Важно", fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onErrorContainer)
Text(
"Не публикуйте Защищённый ключ, не отправляйте его в чат и не добавляйте в GitHub. Новое приложение VK ID может не иметь прав старой TURN-цепочки: статус проверки показывает распознавание legacy OAuth, а окончательный результат виден только при реальном подключении. При неудаче приложение продолжит через встроенный резерв.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer
)
}
}
Button(
onClick = onDismiss,
modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp)
) {
Text("Понятно")
}
}
}
}
}
}
@Composable
private fun HelpStep(number: Int, title: String, text: String) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.Top
) {
Surface(shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer) {
Box(modifier = Modifier.size(30.dp), contentAlignment = Alignment.Center) {
Text(number.toString(), fontWeight = FontWeight.Bold)
}
}
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(title, fontWeight = FontWeight.Bold)
Text(
text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 18.sp
)
}
}
}
@Composable
private fun CopyValueCard(label: String, value: String, onCopy: (() -> Unit)?) {
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f)
) {
Row(
modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 4.dp, top = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(value, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)
}
IconButton(onClick = { onCopy?.invoke() }, enabled = onCopy != null) {
Icon(Icons.Default.ContentCopy, contentDescription = "Копировать")
}
}
}
}
internal fun parseVkClientIdCheckResults(raw: String): VkClientIdProbeCache = runCatching {
val json = JSONObject(raw)
if (json.optInt("_probe_version") != VK_CLIENT_ID_PROBE_VERSION) {
return@runCatching VkClientIdProbeCache(emptyMap(), 0L)
}
val results = buildMap {
val keys = json.keys()
while (keys.hasNext()) {
val key = keys.next()
if (key != "_probe_version" && key != VK_CLIENT_ID_PROBE_CHECKED_AT) {
runCatching { VkClientIdProbeStatus.valueOf(json.optString(key)) }
.getOrNull()
?.let { put(key, it) }
}
}
}
VkClientIdProbeCache(
results = results,
checkedAt = json.optLong(VK_CLIENT_ID_PROBE_CHECKED_AT, 0L).coerceAtLeast(0L)
)
}.getOrDefault(VkClientIdProbeCache(emptyMap(), 0L))
private fun encodeVkClientIdCheckResults(
results: Map<String, VkClientIdProbeStatus>,
checkedAt: Long
): String =
JSONObject().apply {
put("_probe_version", VK_CLIENT_ID_PROBE_VERSION)
put(VK_CLIENT_ID_PROBE_CHECKED_AT, checkedAt.coerceAtLeast(0L))
results.forEach { (id, result) -> put(id, result.name) }
}.toString()
internal val vkLegacyOAuthProbeEndpoints = listOf(
"https://oauth.vk.ru/authorize",
"https://oauth.vk.com/authorize"
)
private fun checkVkClientId(appId: String): VkClientIdProbeStatus {
val cleanAppId = appId.trim()
if (!isValidVkClientId(cleanAppId)) return VkClientIdProbeStatus.LegacyRejected
var legacyRejected = false
for (endpoint in vkLegacyOAuthProbeEndpoints) {
var connection: java.net.HttpURLConnection? = null
try {
val url = java.net.URL(
"$endpoint?client_id=$cleanAppId&display=mobile&response_type=token"
)
connection = url.openConnection() as java.net.HttpURLConnection
connection.requestMethod = "GET"
connection.connectTimeout = 5_000
connection.readTimeout = 5_000
val responseCode = connection.responseCode
if (isVkLegacyClientIdProbeSuccessful(responseCode, connection.contentType.orEmpty())) {
return VkClientIdProbeStatus.LegacyCompatible
}
if (isVkLegacyClientIdProbeRejected(responseCode)) {
legacyRejected = true
}
} catch (_: Exception) {
// Try the compatibility domain below.
} finally {
connection?.disconnect()
}
}
return if (legacyRejected) {
VkClientIdProbeStatus.LegacyRejected
} else {
VkClientIdProbeStatus.CheckFailed
}
}
internal fun isVkLegacyClientIdProbeSuccessful(statusCode: Int, contentType: String): Boolean =
statusCode in 200..299 && contentType.startsWith("text/html", ignoreCase = true)
internal fun isVkLegacyClientIdProbeRejected(statusCode: Int): Boolean =
statusCode in 400..499 && statusCode != 408 && statusCode != 429
@Suppress("DEPRECATION")
private fun appSigningSha1(context: Context): String = runCatching {
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNING_CERTIFICATES)
} else {
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
}
val signature = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val signingInfo = packageInfo.signingInfo ?: return@runCatching ""
if (signingInfo.hasMultipleSigners()) {
signingInfo.apkContentsSigners.firstOrNull()
} else {
signingInfo.signingCertificateHistory.firstOrNull()
}
} else {
packageInfo.signatures?.firstOrNull()
} ?: return@runCatching ""
MessageDigest.getInstance("SHA-1")
.digest(signature.toByteArray())
.joinToString(":") { byte -> "%02X".format(byte) }
}.getOrDefault("")