fix(tunnel): сохранять параметры amneziawg и показывать протокол доступа

This commit is contained in:
samosvalishe committed 2026-09-12 17:29:28 +03:00
1 parent 53941bdf6d
commit 315f07ff53
11 files changed
+134 -30

No files matched your search

@@ -0,0 +1,14 @@
package com.freeturn.app.data.config
/** Протокол выданного/импортируемого доступа - для подписей в UI. */
enum class AccessProtocol {
PROXY, WG, AWG;
companion object {
fun of(wgConf: String?): AccessProtocol = when {
wgConf.isNullOrBlank() -> PROXY
CoreConfigJson.isAmneziaConfig(wgConf) -> AWG
else -> WG
}
}
}
@@ -75,9 +75,27 @@ data class CoreConfigJson(
const val PROXY_MODE_TCP = "tcp" const val PROXY_MODE_TCP = "tcp"
const val PROXY_MODE_UDP = "udp" const val PROXY_MODE_UDP = "udp"
const val TUNNEL_MODE_NONE = "none" const val TUNNEL_MODE_NONE = "none"
const val TUNNEL_MODE_WG = "wg" const val TUNNEL_MODE_AWG = "awg"
const val PLATFORM_MOBILE = "mobile" const val PLATFORM_MOBILE = "mobile"
// Зеркало amnezia-ключей парсера ядра (internal/tunnel/wgconf). Только для
// подписи в UI: ядру всегда уходит awg, так что расхождение не рвёт связь.
private val AMNEZIA_CONFIG_KEYS = setOf(
"jc", "jmin", "jmax", "s1", "s2", "s3", "s4",
"h1", "h2", "h3", "h4", "headerprotectionkey",
"i1", "i2", "i3", "i4", "i5",
"contentpaddingaddition", "rekeyaftertime", "rekeytimeout",
"rejectaftertime", "keepalivetimeout", "maxhandshakeattempts",
"randomtrailers", "disablecookies"
)
fun isAmneziaConfig(conf: String): Boolean =
conf.lineSequence().any { rawLine ->
val line = rawLine.substringBefore('#').substringBefore(';').trim()
val key = line.substringBefore('=').trim().lowercase()
key in AMNEZIA_CONFIG_KEYS
}
fun encode(cfg: CoreConfigJson): String = json.encodeToString(cfg) fun encode(cfg: CoreConfigJson): String = json.encodeToString(cfg)
} }
} }
@@ -143,7 +161,9 @@ fun ClientConfig.toCoreJson(
log = CoreConfigJson.Log(debug = debugMode), log = CoreConfigJson.Log(debug = debugMode),
kcp = if (tcpMode) srv.kcp.toCoreJson() else null, kcp = if (tcpMode) srv.kcp.toCoreJson() else null,
tunnel = CoreConfigJson.Tunnel( tunnel = CoreConfigJson.Tunnel(
mode = if (wireGuardActive) CoreConfigJson.TUNNEL_MODE_WG // Бэкенд туннеля один: awg лишь не глушит маскировку, на чистом
// WG-конфиге равен wg - а wg молча срезал бы amnezia-параметры.
mode = if (wireGuardActive) CoreConfigJson.TUNNEL_MODE_AWG
else CoreConfigJson.TUNNEL_MODE_NONE, else CoreConfigJson.TUNNEL_MODE_NONE,
config = if (wireGuardActive) wireGuardConfig else "", config = if (wireGuardActive) wireGuardConfig else "",
mtu = ClientConfig.WG_MTU, mtu = ClientConfig.WG_MTU,
@@ -17,18 +17,26 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.ui.theme.Spacing import com.freeturn.app.ui.theme.Spacing
/** /**
* Чипы доступа: протокол (WireGuard/прокси) + признак обфускации. Общий вид для * Чипы доступа: протокол (WireGuard/AmneziaWG/прокси) + признак обфускации.
* sheet выдачи доступа и sheet импорта. * Общий вид для sheet выдачи доступа и sheet импорта.
*/ */
@Composable @Composable
fun ProtocolPills(wg: Boolean, obfOn: Boolean) { fun ProtocolPills(protocol: AccessProtocol, obfOn: Boolean) {
Row(horizontalArrangement = Arrangement.spacedBy(Spacing.sm)) { Row(horizontalArrangement = Arrangement.spacedBy(Spacing.sm)) {
Pill( Pill(
iconRes = if (wg) R.drawable.vpn_key_24px else R.drawable.public_24px, iconRes = if (protocol == AccessProtocol.PROXY) R.drawable.public_24px
text = stringResource(if (wg) R.string.share_protocol_wg else R.string.share_protocol_proxy), else R.drawable.vpn_key_24px,
text = stringResource(
when (protocol) {
AccessProtocol.AWG -> R.string.protocol_awg
AccessProtocol.WG -> R.string.protocol_wg
AccessProtocol.PROXY -> R.string.protocol_proxy
}
),
container = MaterialTheme.colorScheme.secondaryContainer, container = MaterialTheme.colorScheme.secondaryContainer,
content = MaterialTheme.colorScheme.onSecondaryContainer content = MaterialTheme.colorScheme.onSecondaryContainer
) )
@@ -6,10 +6,12 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.ui.components.SectionLabel import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.components.SettingsCard import com.freeturn.app.ui.components.SettingsCard
import com.freeturn.app.ui.components.SettingsEntryRow import com.freeturn.app.ui.components.SettingsEntryRow
@@ -29,11 +31,18 @@ internal fun WireGuardConfigCard(
onLoadFile: () -> Unit onLoadFile: () -> Unit
) { ) {
val configLoaded = wgConfig.isNotBlank() val configLoaded = wgConfig.isNotBlank()
val protocol = remember(wgConfig) { AccessProtocol.of(wgConfig) }
SectionLabel(stringResource(R.string.connection_config_section)) SectionLabel(stringResource(R.string.connection_config_section))
SettingsCard { SettingsCard {
SettingsEntryRow( SettingsEntryRow(
iconRes = R.drawable.cloud_download_24px, iconRes = R.drawable.cloud_download_24px,
title = stringResource(R.string.load_wg_conf), title = stringResource(R.string.load_wg_conf),
subtitle = if (configLoaded) {
stringResource(
if (protocol == AccessProtocol.AWG) R.string.protocol_awg
else R.string.protocol_wg
)
} else null,
trailingRes = if (configLoaded) R.drawable.check_circle_24px else null, trailingRes = if (configLoaded) R.drawable.check_circle_24px else null,
trailingTint = MaterialTheme.extendedColorScheme.success, trailingTint = MaterialTheme.extendedColorScheme.success,
enabled = !privacyMode, enabled = !privacyMode,
@@ -42,6 +42,7 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.data.config.ObfProfile import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.HapticUtil import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.components.SectionLabel import com.freeturn.app.ui.components.SectionLabel
@@ -179,11 +180,19 @@ fun SetupConfigStep(
} }
} }
if (draft.wgCustomConf) { if (draft.wgCustomConf) {
val hasConf = draft.wgConfText.isNotBlank()
val protocol = remember(draft.wgConfText) { AccessProtocol.of(draft.wgConfText) }
SettingsRowDivider() SettingsRowDivider()
SettingsEntryRow( SettingsEntryRow(
iconRes = R.drawable.cloud_download_24px, iconRes = R.drawable.cloud_download_24px,
title = stringResource(R.string.load_wg_conf), title = stringResource(R.string.load_wg_conf),
trailingRes = if (draft.wgConfText.isNotBlank()) R.drawable.check_circle_24px else null, subtitle = if (hasConf) {
stringResource(
if (protocol == AccessProtocol.AWG) R.string.protocol_awg
else R.string.protocol_wg
)
} else null,
trailingRes = if (hasConf) R.drawable.check_circle_24px else null,
trailingTint = MaterialTheme.extendedColorScheme.success, trailingTint = MaterialTheme.extendedColorScheme.success,
onClick = onLoadWgFile onClick = onLoadWgFile
) )
@@ -32,6 +32,7 @@ import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberBottomSheetState import androidx.compose.material3.rememberBottomSheetState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
@@ -41,6 +42,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.data.config.ObfProfile import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.ui.components.EmptyState import com.freeturn.app.ui.components.EmptyState
import com.freeturn.app.ui.components.InlineErrorCard import com.freeturn.app.ui.components.InlineErrorCard
@@ -124,7 +126,7 @@ fun ImportSheet(
) )
ProtocolPills( ProtocolPills(
wg = link.wgConf.isNotBlank(), protocol = remember(link.wgConf) { AccessProtocol.of(link.wgConf) },
obfOn = link.obfProfile.isNotEmpty() && link.obfProfile != ObfProfile.NONE obfOn = link.obfProfile.isNotEmpty() && link.obfProfile != ObfProfile.NONE
) )
@@ -121,7 +121,7 @@ fun ShareConnectionTab(
onSetMode(false) onSetMode(false)
}, },
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2) shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
) { Text(stringResource(R.string.share_protocol_wg)) } ) { Text(stringResource(R.string.protocol_wg)) }
SegmentedButton( SegmentedButton(
selected = !state.useWg, selected = !state.useWg,
onClick = { onClick = {
@@ -129,7 +129,7 @@ fun ShareConnectionTab(
onSetMode(true) onSetMode(true)
}, },
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2) shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
) { Text(stringResource(R.string.share_protocol_proxy)) } ) { Text(stringResource(R.string.protocol_proxy)) }
} }
} }
ShareProtocolCard(state = state, onRetryInfo = onRetryInfo) ShareProtocolCard(state = state, onRetryInfo = onRetryInfo)
@@ -243,8 +243,8 @@ private fun ShareProtocolCard(state: ShareUiState, onRetryInfo: () -> Unit) {
) )
Text( Text(
stringResource( stringResource(
if (wg) R.string.share_protocol_wg if (wg) R.string.protocol_wg
else R.string.share_protocol_proxy else R.string.protocol_proxy
), ),
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface, color = MaterialTheme.colorScheme.onSurface,
@@ -92,11 +92,11 @@ fun ShareResultSheet(result: ShareResult, shareInfo: ShareInfo?, onDismiss: () -
textAlign = TextAlign.Center textAlign = TextAlign.Center
) )
// Протокол - по факту выданного доступа (result.isWg), обфускация - из share-info. // Протокол - по факту выданного доступа (result.protocol), обфускация - из share-info.
val obfOn = shareInfo?.let { val obfOn = shareInfo?.let {
it.obfProfile.isNotEmpty() && it.obfProfile != ObfProfile.NONE it.obfProfile.isNotEmpty() && it.obfProfile != ObfProfile.NONE
} ?: false } ?: false
ProtocolPills(wg = result.isWg, obfOn = obfOn) ProtocolPills(protocol = result.protocol, obfOn = obfOn)
Text( Text(
stringResource(R.string.share_result_desc), stringResource(R.string.share_result_desc),
@@ -4,6 +4,7 @@ import android.content.Context
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.data.config.ClientConfig import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.config.ClientId import com.freeturn.app.data.config.ClientId
import com.freeturn.app.data.server.Server import com.freeturn.app.data.server.Server
@@ -20,7 +21,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
data class ShareResult(val userName: String, val link: String, val isWg: Boolean) data class ShareResult(val userName: String, val link: String, val protocol: AccessProtocol)
data class RevokeTarget( data class RevokeTarget(
val name: String, val name: String,
@@ -241,7 +242,7 @@ class ShareViewModel(
link = ShareLinkBuilder.build( link = ShareLinkBuilder.build(
server, info, userName, null, st.manualClientId.trim(), st.sharedVkLink server, info, userName, null, st.manualClientId.trim(), st.sharedVkLink
), ),
wg = false wgConf = null
) )
return return
} }
@@ -258,7 +259,7 @@ class ShareViewModel(
link = ShareLinkBuilder.build( link = ShareLinkBuilder.build(
server, info, userName, peer.clientConf, cid, st.sharedVkLink server, info, userName, peer.clientConf, cid, st.sharedVkLink
), ),
wg = true, wgConf = peer.clientConf,
newPeer = WgPeer( newPeer = WgPeer(
pubkey = peer.pubkey, pubkey = peer.pubkey,
name = userName, name = userName,
@@ -279,7 +280,7 @@ class ShareViewModel(
link = ShareLinkBuilder.build( link = ShareLinkBuilder.build(
server, info, userName, null, cid, st.sharedVkLink server, info, userName, null, cid, st.sharedVkLink
), ),
wg = false, wgConf = null,
newClient = SharedClient(clientId = cid, name = userName) newClient = SharedClient(clientId = cid, name = userName)
) )
} }
@@ -292,7 +293,7 @@ class ShareViewModel(
serverId: String, serverId: String,
userName: String, userName: String,
link: String, link: String,
wg: Boolean, wgConf: String?,
newPeer: WgPeer? = null, newPeer: WgPeer? = null,
newClient: SharedClient? = null newClient: SharedClient? = null
) { ) {
@@ -302,7 +303,7 @@ class ShareViewModel(
cur.copy( cur.copy(
creating = false, creating = false,
userName = "", userName = "",
result = ShareResult(userName, link, wg), result = ShareResult(userName, link, AccessProtocol.of(wgConf)),
peers = if (appendable && newPeer != null) cur.peers + newPeer else cur.peers, peers = if (appendable && newPeer != null) cur.peers + newPeer else cur.peers,
clients = if (appendable && newClient != null) cur.clients + newClient else cur.clients clients = if (appendable && newClient != null) cur.clients + newClient else cur.clients
) )
@@ -365,7 +366,7 @@ class ShareViewModel(
server, info, peer.name, access.clientConf, server, info, peer.name, access.clientConf,
access.clientId, st.sharedVkLink access.clientId, st.sharedVkLink
), ),
isWg = true protocol = AccessProtocol.of(access.clientConf)
) )
) )
} }
@@ -390,7 +391,7 @@ class ShareViewModel(
link = ShareLinkBuilder.build( link = ShareLinkBuilder.build(
server, info, client.name, null, client.clientId, it.sharedVkLink server, info, client.name, null, client.clientId, it.sharedVkLink
), ),
isWg = false protocol = AccessProtocol.PROXY
) )
) )
} }
+4 -3
View File
@@ -28,9 +28,10 @@
<string name="share_info_loading">Проверка сервера…</string> <string name="share_info_loading">Проверка сервера…</string>
<string name="share_info_error">Сервер недоступен</string> <string name="share_info_error">Сервер недоступен</string>
<string name="share_info_retry">Повторить</string> <string name="share_info_retry">Повторить</string>
<string name="share_protocol_wg">WireGuard</string> <string name="protocol_wg">WireGuard</string>
<string name="share_protocol_wg_desc">Пользователь подключается по WireGuard</string> <string name="protocol_awg">AmneziaWG</string>
<string name="share_protocol_proxy">Прокси</string> <string name="protocol_proxy">Прокси</string>
<string name="share_protocol_wg_desc">Пользователь подключается по VPN - WireGuard или AmneziaWG</string>
<string name="share_protocol_proxy_desc">Пользователь подключается через прокси</string> <string name="share_protocol_proxy_desc">Пользователь подключается через прокси</string>
<string name="share_chip_obf">Обфускация</string> <string name="share_chip_obf">Обфускация</string>
<string name="share_access_type">Тип доступа</string> <string name="share_access_type">Тип доступа</string>
@@ -5,6 +5,7 @@ import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.jsonPrimitive
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
@@ -42,15 +43,54 @@ class CoreConfigJsonTest {
assertTrue(own.contains("ffffffffffffffffffffffffffffffff")) assertTrue(own.contains("ffffffffffffffffffffffffffffffff"))
} }
// Режим всегда awg: на чистом WG-конфиге ядро ведёт себя как в wg,
// а wg молча срезал бы amnezia-параметры.
@Test @Test
fun tunnelCarriesWgConfig() { fun tunnelCarriesAwgModeForAnyConfig() {
val wg = base.copy( val plain = base.copy(
tunnelTransport = TunnelTransport.WIREGUARD, tunnelTransport = TunnelTransport.WIREGUARD,
wireGuardConfig = "[Interface]\nAddress = 10.8.0.2/32\n", wireGuardConfig = "[Interface]\nAddress = 10.8.0.2/32\n",
) )
val tunnel = parse(wg)["tunnel"]!!.jsonObject val tunnel = parse(plain)["tunnel"]!!.jsonObject
assertEquals("wg", tunnel["mode"]!!.jsonPrimitive.content) assertEquals("awg", tunnel["mode"]!!.jsonPrimitive.content)
assertEquals(ClientConfig.WG_MTU, tunnel["mtu"]!!.jsonPrimitive.content.toInt()) assertEquals(ClientConfig.WG_MTU, tunnel["mtu"]!!.jsonPrimitive.content.toInt())
val awg = plain.copy(wireGuardConfig = "[Interface]\nAddress = 10.8.0.2/32\nJc = 4\n")
val awgTunnel = parse(awg)["tunnel"]!!.jsonObject
assertEquals("awg", awgTunnel["mode"]!!.jsonPrimitive.content)
assertTrue(awgTunnel["config"]!!.jsonPrimitive.content.contains("Jc = 4"))
}
// Набор ключей - зеркало парсера ядра (internal/tunnel/wgconf).
@Test
fun detectsAmneziaConfigKeys() {
assertFalse(CoreConfigJson.isAmneziaConfig("[Interface]\nAddress = 10.8.0.2/32\nPrivateKey = xxx\n"))
assertFalse(CoreConfigJson.isAmneziaConfig("# Jc = 4\n[Interface]\nAddress = 10.8.0.2/32\n"))
assertFalse(CoreConfigJson.isAmneziaConfig("; S1 = 15\n[Interface]\nAddress = 10.8.0.2/32\n"))
assertTrue(CoreConfigJson.isAmneziaConfig("[Interface]\nAddress = 10.8.0.2/32\nJc = 4\n"))
assertTrue(CoreConfigJson.isAmneziaConfig("[Interface]\nheaderprotectionkey = 0x12345678\n"))
assertTrue(CoreConfigJson.isAmneziaConfig("[Interface]\ns1 = 50\n"))
assertTrue(CoreConfigJson.isAmneziaConfig("[Interface]\nH4 = 9999 ; inline comment\n"))
assertTrue(CoreConfigJson.isAmneziaConfig("[Interface]\nJmin = 50\nJmax = 100\n"))
}
@Test
fun tunnelModeNoneWhenInactive() {
val disabled = base.copy(
tunnelTransport = TunnelTransport.NONE,
wireGuardConfig = "Jc = 4",
)
val tunnel = parse(disabled)["tunnel"]!!.jsonObject
assertEquals("none", tunnel["mode"]!!.jsonPrimitive.content)
assertEquals("", tunnel["config"]!!.jsonPrimitive.content)
}
@Test
fun accessProtocolFollowsConf() {
assertEquals(AccessProtocol.PROXY, AccessProtocol.of(""))
assertEquals(AccessProtocol.PROXY, AccessProtocol.of(null))
assertEquals(AccessProtocol.WG, AccessProtocol.of("[Interface]\nAddress = 10.8.0.2/32\n"))
assertEquals(AccessProtocol.AWG, AccessProtocol.of("[Interface]\nJc = 4\n"))
} }
// Лишний ключ в proxy валит старт ядра (DisallowUnknownFields), а не тест схемы. // Лишний ключ в proxy валит старт ядра (DisallowUnknownFields), а не тест схемы.