diff --git a/README.md b/README.md index 8c4d6831..b8644b4b 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ ### Performance & Censorship Resistance - **MASQUE over HTTP/1.1, HTTP/2, and HTTP/3 (QUIC)** +- **Control-Plane Edge Relayer & Automatic Failover** +- **Dynamic Remote Configuration & Endpoint Sync** - **TLS Fragmentation (Record & Packet)** - **uTLS Fingerprint Emulation** - **Upstream Proxy Chaining** @@ -41,6 +43,7 @@ - **Automatic Connection Recovery** ### User Experience & System Integration +- **Light, Dark & System Adaptive Themes** - **Real-Time Traffic & Latency Diagnostics** - **Public & Exit IP Detection** - **Global Server Locations** diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 71ee2418..71b47f4a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -23,8 +23,8 @@ android { applicationId = "com.vauth.foxyvpn" minSdk = 26 targetSdk = 35 - versionCode = 49 - versionName = "2.0.3" + versionCode = 50 + versionName = "2.0.4" } splits { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b227e217..c7f5bd6f 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -63,7 +63,7 @@ android:name=".widget.QuickConnectWidgetProvider" android:label="@string/quick_connect" android:icon="@drawable/widget_preview" - android:exported="false"> + android:exported="true"> @@ -71,6 +71,10 @@ android:name="android.appwidget.provider" android:resource="@xml/quick_connect_widget_info" /> + + @@ -225,14 +231,16 @@ class FastlyChallengeSolver(private val cookieJar: SimpleCookieJar) { ): String { val patUrl = "$prefixUrl/pat?token=${URLEncoder.encode(token, "UTF-8")}" val builder = Request.Builder().url(patUrl) - for ((key, value) in FoxyRemoteConfig.current.solver.headers) { + val solverHeaders = FoxyRemoteConfig.current.solver.headers + for ((key, value) in solverHeaders) { builder.header(key, value) } + val effectiveUA = solverHeaders["User-Agent"] ?: userAgent val request = builder .header("Accept", "text/plain") .header("Content-Type", "application/json") - .header("User-Agent", userAgent) + .header("User-Agent", effectiveUA) .header("Origin", baseOrigin(prefixUrl)) .post(ByteArray(0).toRequestBody(null)) .build() @@ -398,6 +406,8 @@ class FastlyChallengeSolver(private val cookieJar: SimpleCookieJar) { val page = try { fetchText(solver, pageUrl, userAgent = userAgent, allowChallenge = true) + } catch (cancellation: CancellationException) { + throw cancellation } catch (_: Exception) { return false } @@ -447,14 +457,16 @@ class FastlyChallengeSolver(private val cookieJar: SimpleCookieJar) { .toString() .toRequestBody("application/json".toMediaType()) val builder = Request.Builder().url("$prefixUrl/fst-post-back") - for ((key, value) in FoxyRemoteConfig.current.solver.headers) { + val solverHeaders = FoxyRemoteConfig.current.solver.headers + for ((key, value) in solverHeaders) { builder.header(key, value) } + val effectiveUA = solverHeaders["User-Agent"] ?: userAgent val request = builder .header("Content-Type", "application/json") .header("Accept", "application/json") - .header("User-Agent", userAgent) + .header("User-Agent", effectiveUA) .header("Origin", baseOrigin(prefixUrl)) .post(postBody) .build() diff --git a/app/src/main/java/com/vauth/foxyvpn/data/FirefoxAccountHeaders.kt b/app/src/main/java/com/vauth/foxyvpn/data/FirefoxAccountHeaders.kt index 64a2164c..4f866df8 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/FirefoxAccountHeaders.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/FirefoxAccountHeaders.kt @@ -22,12 +22,6 @@ internal object FirefoxAccountHeaders { get() = FoxyRemoteConfig.current.browser.headers["User-Agent"] ?: resolvePlaceholders("Mozilla/5.0 (Android {android_version}; Mobile; rv:$major.0) Gecko/$major.0 Firefox/$major.0") - val desktopUserAgent: String - get() = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:$major.0) Gecko/20100101 Firefox/$major.0" - - val userAgent: String - get() = controlPlaneUserAgent - fun apply(builder: Request.Builder): Request.Builder { val headers = FoxyRemoteConfig.current.controlPlane.headers for ((key, value) in headers) { @@ -36,6 +30,8 @@ internal object FirefoxAccountHeaders { return builder } + fun applyOAuth(builder: Request.Builder): Request.Builder = apply(builder) + suspend fun refresh(client: OkHttpClient) { mutex.withLock { nextRefreshNanos?.let { if (System.nanoTime() - it < 0L) return } diff --git a/app/src/main/java/com/vauth/foxyvpn/data/FoxyRemoteConfig.kt b/app/src/main/java/com/vauth/foxyvpn/data/FoxyRemoteConfig.kt index bfdcd9b5..e531fe10 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/FoxyRemoteConfig.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/FoxyRemoteConfig.kt @@ -48,8 +48,8 @@ data class EndpointsConfig( ) val DEFAULT_RELAYERS: Map = emptyMap() -val DEFAULT_RELAYER_ROUTES: Set = setOf("guardian") -val DEFAULT_FAILOVER_CODES: Set = setOf(451) +val DEFAULT_RELAYER_ROUTES: Set = setOf("guardian", "fxa", "config", "server_list") +val DEFAULT_FAILOVER_CODES: Set = setOf(406, 451) data class RemoteConfig( val version: Int, @@ -104,7 +104,10 @@ private val DEFAULT_SOLVER = ComponentConfig( headers = mapOf( - "User-Agent" to resolvePlaceholders("MozillaVPN/2.24.0 (sys:android {android_version})"), + "User-Agent" to + resolvePlaceholders( + "Mozilla/5.0 (Android {android_version}; Mobile; rv:159.0) Gecko/159.0 Firefox/159.0" + ), "Accept-Encoding" to "identity", ), ) diff --git a/app/src/main/java/com/vauth/foxyvpn/data/FxaAuthRepository.kt b/app/src/main/java/com/vauth/foxyvpn/data/FxaAuthRepository.kt index d93f2b62..2b245d04 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/FxaAuthRepository.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/FxaAuthRepository.kt @@ -106,33 +106,6 @@ class FxaAuthRepository( } } - suspend fun completeBrowserLoginWithTokens( - accessToken: String, - refreshToken: String?, - expiresInSeconds: Long, - ): Result = - withContext(Dispatchers.IO) { - val epoch = tokenStore.sessionEpoch - runCatching { - loginMutex.withLock { - check(tokenStore.sessionEpoch == epoch) { "Sign-in was superseded" } - val ttl = - if (expiresInSeconds > 0) expiresInSeconds - else DEFAULT_ACCESS_TOKEN_TTL_SECONDS.toLong() - tokenStore.completeLoginIfCurrent( - RuntimeAuth( - accessToken = accessToken.trim(), - refreshToken = refreshToken?.trim()?.ifBlank { null }, - expiresAtEpochSeconds = System.currentTimeMillis() / 1000 + ttl, - ), - epoch, - ) - Unit - } - } - .onFailure { if (it is CancellationException) throw it } - } - suspend fun completeBrowserLogin(sessionToken: String): Result = withContext(Dispatchers.IO) { val epoch = tokenStore.sessionEpoch @@ -223,11 +196,14 @@ class FxaAuthRepository( val tokenData = try { FirefoxAccountHeaders.refresh(client) - try { - executeFxaRequest(fullUrl = FoxyRemoteConfig.current.endpoints.controlPlane.oauthToken, jsonBody = body) - } catch (_: FastlyBlockedException) { - executeFxaRequest(fullUrl = FoxyRemoteConfig.current.endpoints.controlPlane.oauthFallback, jsonBody = body) - } + val primaryUrl = FoxyRemoteConfig.current.endpoints.controlPlane.oauthToken + val fallbackUrl = resolveOAuthFallback(primaryUrl) + executeFxaRequest( + fullUrl = primaryUrl, + jsonBody = body, + fallbackUrl = fallbackUrl, + isOAuth = true, + ) } catch (rejected: FxaApiError) { throw FxaRefreshFailure( rejected.message ?: "FxA rejected the refresh token", @@ -286,7 +262,17 @@ class FxaAuthRepository( } private fun FxaApiError.isPermanentRefreshRejection(): Boolean { - return statusCode == 400 || statusCode == 401 || statusCode == 403 || errno == 108 + return errno == 108 || (statusCode == 400 && ( + message?.contains("invalid_grant", ignoreCase = true) == true || + message?.contains("invalid token", ignoreCase = true) == true + )) + } + + private fun resolveOAuthFallback(primaryUrl: String): String { + val configured = FoxyRemoteConfig.current.endpoints.controlPlane.oauthFallback + return if (configured != primaryUrl) configured + else if (primaryUrl.contains("oauth.accounts.firefox.com")) "https://api.accounts.firefox.com/v1/oauth/token" + else "https://oauth.accounts.firefox.com/v1/token" } private fun expiryFrom(tokenData: JSONObject): Long { @@ -311,8 +297,11 @@ class FxaAuthRepository( .header("Authorization", header) .post("{}".toRequestBody(jsonMediaType)) .build() - runCatching { + try { client.newCall(request).awaitResponse().use { } + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { } } @@ -331,20 +320,29 @@ class FxaAuthRepository( } var tokenData: JSONObject? = null var lastError: Throwable? = null - for (attempt in 0 until 10) { - coroutineContext.ensureActive() - try { - tokenData = exchangeSessionWithOAuthCode(sessionToken) - break - } catch (cancellation: CancellationException) { - throw cancellation - } catch (e: Exception) { - lastError = e - if (e.isUnconfirmedSession() && attempt < 9) { - delay(CONFIRM_POLL_DELAY_MS) - continue + try { + tokenData = exchangeSessionDirect(sessionToken) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + tokenData = null + } + if (tokenData == null) { + for (attempt in 0 until 10) { + coroutineContext.ensureActive() + try { + tokenData = exchangeSessionWithOAuthCode(sessionToken) + break + } catch (cancellation: CancellationException) { + throw cancellation + } catch (e: Exception) { + lastError = e + if (e.isUnconfirmedSession() && attempt < 9) { + delay(CONFIRM_POLL_DELAY_MS) + continue + } + throw e } - throw e } } val data = tokenData ?: throw (lastError ?: FxaApiError("Sign-in failed", null, 500)) @@ -364,6 +362,28 @@ class FxaAuthRepository( destroySession(sessionToken) } + private suspend fun exchangeSessionDirect(sessionToken: String): JSONObject = + withContext(Dispatchers.IO) { + val body = JSONObject().apply { + put("client_id", FIREFOX_CLIENT_ID) + put("grant_type", "fxa-credentials") + put("scope", OAUTH_SCOPE) + put("access_type", "offline") + } + val primaryUrl = FoxyRemoteConfig.current.endpoints.controlPlane.oauthToken + val tokens = executeFxaRequest( + fullUrl = primaryUrl, + jsonBody = body, + sessionToken = sessionToken, + fallbackUrl = resolveOAuthFallback(primaryUrl), + isOAuth = true, + ) + if (tokens.optString("access_token").isBlank()) { + throw FxaApiError("Direct token response is missing access token", null, 500) + } + tokens + } + private suspend fun exchangeSessionWithOAuthCode(sessionToken: String): JSONObject = withContext(Dispatchers.IO) { val secret = ByteArray(32).also { SecureRandom().nextBytes(it) } @@ -403,6 +423,7 @@ class FxaAuthRepository( fullUrl = FoxyRemoteConfig.current.endpoints.controlPlane.authorization, jsonBody = authorizeBody, sessionToken = sessionToken, + isOAuth = true, ) val code = authResponse.optString("code", "") @@ -419,11 +440,14 @@ class FxaAuthRepository( put("code_verifier", verifier) } + val primaryUrl = FoxyRemoteConfig.current.endpoints.controlPlane.oauthToken val tokens = executeFxaRequest( - fullUrl = FoxyRemoteConfig.current.endpoints.controlPlane.oauthToken, + fullUrl = primaryUrl, jsonBody = tokenBody, sessionToken = null, + fallbackUrl = resolveOAuthFallback(primaryUrl), + isOAuth = true, ) if (tokens.optString("access_token").isBlank()) { @@ -438,39 +462,77 @@ class FxaAuthRepository( method: String = "POST", jsonBody: JSONObject, sessionToken: String? = null, + fallbackUrl: String? = null, + isOAuth: Boolean = false, ): JSONObject = withTimeout(120_000L) { withContext(Dispatchers.IO) { - val url = fullUrl.toHttpUrl() - val origin = "${url.scheme}://${url.host}" + var currentUrl = fullUrl.toHttpUrl() val bodyBytes = jsonBody.toString().toByteArray(Charsets.UTF_8) val hawkCreds = sessionToken?.let { deriveHawkCredentials(it) } - fun buildRequest(): Request { - val builder = - Request.Builder() - .url(url) - .applyFirefoxHeaders() - .header("Content-Type", "application/json") + fun buildRequest(targetUrl: HttpUrl): Request { + val builder = Request.Builder().url(targetUrl) + if (isOAuth) { + FirefoxAccountHeaders.applyOAuth(builder) + } else { + builder.applyFirefoxHeaders().header("Content-Type", "application/json") + } if (hawkCreds != null) { builder.header( "Authorization", - hawkHeader(method, url, hawkCreds.first, hawkCreds.second, bodyBytes), + hawkHeader(method, targetUrl, hawkCreds.first, hawkCreds.second, bodyBytes), ) } builder.method(method, bodyBytes.toRequestBody(jsonMediaType)) return builder.build() } - var response: Response = client.newCall(buildRequest()).awaitResponse() + var response: Response = client.newCall(buildRequest(currentUrl)).awaitResponse() + + if (response.code == 406 && fallbackUrl != null) { + val candidateFallback = fallbackUrl.toHttpUrl() + val fallbackReq = buildRequest(candidateFallback) + val fallbackResp = + try { + client.newCall(fallbackReq).awaitResponse() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + null + } + if (fallbackResp != null) { + if (fallbackResp.isSuccessful) { + response.close() + response = fallbackResp + currentUrl = candidateFallback + } else if (fallbackResp.code == 400) { + val fbText = fallbackResp.body?.readBoundedText().orEmpty() + val isInvalid = fbText.contains("108") || fbText.contains("invalid_grant", ignoreCase = true) + if (isInvalid) { + response.close() + response = fallbackResp + currentUrl = candidateFallback + } else { + fallbackResp.close() + } + } else { + fallbackResp.close() + } + } + } + var attempts = 1 while (response.code == 406 && attempts < FXA_MAX_CHALLENGE_ATTEMPTS) { val challengedBody = response.use { it.body?.readBoundedText().orEmpty() } try { + val solverUA = + if (isOAuth) FirefoxAccountHeaders.browserUserAgent + else FirefoxAccountHeaders.controlPlaneUserAgent challengeSolver.solveAndInstall( challengedBody, - origin, - FirefoxAccountHeaders.controlPlaneUserAgent, + currentUrl.toString(), + solverUA, ) } catch (cancellation: CancellationException) { throw cancellation @@ -479,7 +541,7 @@ class FxaAuthRepository( FoxyRemoteConfig.triggerRefresh() throw FastlyBlockedException(FRIENDLY_406_MESSAGE, solveFailure) } - response = client.newCall(buildRequest()).awaitResponse() + response = client.newCall(buildRequest(currentUrl)).awaitResponse() attempts++ } diff --git a/app/src/main/java/com/vauth/foxyvpn/data/GuardianClient.kt b/app/src/main/java/com/vauth/foxyvpn/data/GuardianClient.kt index d897fd07..ab043e43 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/GuardianClient.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/GuardianClient.kt @@ -120,9 +120,16 @@ class GuardianClient( var passFailure: Exception? = null try { pass = fetchProxyPass(endpoint, accessToken) + } catch (cancellation: CancellationException) { + throw cancellation } catch (invalid: TokenInvalidError) { - runCatching { activateGuardian(endpoint, accessToken) } - pass = runCatching { fetchProxyPass(endpoint, accessToken) }.getOrNull() + try { + activateGuardian(endpoint, accessToken) + pass = fetchProxyPass(endpoint, accessToken) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + } } catch (exceeded: QuotaExceededError) { quotaExceeded = exceeded } catch (e: Exception) { @@ -137,14 +144,18 @@ class GuardianClient( "${endpoint.trimEnd('/')}/api/v1/fpn/status" } val statusEntitlement = - runCatching { + try { authorizedRequest("GET", statusUrl, accessToken).use { resp -> if (resp.code == 200) { val text = resp.body?.readBoundedText().orEmpty() parseEntitlement(JSONObject(text)) } else null } - }.getOrNull() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + null + } val remaining = pass?.quotaRemaining @@ -259,7 +270,7 @@ class GuardianClient( } } -internal fun jwtExpiryEpochSeconds(token: String): Long? { +internal fun jwtExpiryEpochSeconds(token: String, nowSeconds: Long = System.currentTimeMillis() / 1_000L): Long? { val parts = token.split('.') if (parts.size < 2) return null val payload = @@ -275,5 +286,26 @@ internal fun jwtExpiryEpochSeconds(token: String): Long? { ) } .getOrNull() ?: return null - return runCatching { JSONObject(payload).optLong("exp", 0L) }.getOrNull()?.takeIf { it > 0 } + return runCatching { + val json = JSONObject(payload) + val exp = json.optLong("exp", 0L) + if (exp <= 0L) return@runCatching null + val iat = json.optLong("iat", 0L) + val nbf = json.optLong("nbf", 0L) + val start = when { + nbf > 0L -> nbf + iat > 0L -> iat + else -> 0L + } + if (start > 0L && exp > start) { + val offset = nowSeconds - start + if (kotlin.math.abs(offset) > 60L) { + nowSeconds + (exp - start) + } else { + exp + } + } else { + exp + } + }.getOrNull() } diff --git a/app/src/main/java/com/vauth/foxyvpn/data/RelayerInterceptor.kt b/app/src/main/java/com/vauth/foxyvpn/data/RelayerInterceptor.kt index 31a59963..45d80f7c 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/RelayerInterceptor.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/RelayerInterceptor.kt @@ -1,9 +1,9 @@ package com.vauth.foxyvpn.data -import android.util.Base64 import java.io.IOException import java.util.concurrent.TimeUnit import kotlinx.coroutines.CancellationException +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response @@ -45,14 +45,15 @@ class RelayerInterceptor( } var directException: Exception? = null - var directFailureResponse: Response? = null + var directFailoverCode: Int? = null try { val directResponse = chain.withConnectTimeout(DIRECT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS).proceed(request) if (directResponse.isSuccessful || directResponse.code !in config.failoverCodes) { return directResponse } + directFailoverCode = directResponse.code AppLogger.i("Relayer", "Direct connection returned status ${directResponse.code}, starting relayer failover") - directFailureResponse = directResponse + directResponse.close() } catch (e: Exception) { if (e is CancellationException) throw e AppLogger.i("Relayer", "Direct connection failed (${e.message ?: e::class.java.simpleName}), starting relayer failover") @@ -64,9 +65,14 @@ class RelayerInterceptor( AppLogger.i("Relayer", "Attempting request via $relayerUrl") val relayed = buildRelayedRequest(request, relayerUrl) val response = chain.proceed(relayed) + val relayError = response.header("X-Relay-Error") + if (relayError != null) { + AppLogger.w("Relayer", "Relayer $relayerUrl refused: $relayError") + response.close() + continue + } if (response.code !in config.failoverCodes) { AppLogger.i("Relayer", "Request succeeded via $relayerUrl (status ${response.code})") - directFailureResponse?.close() return response } AppLogger.w("Relayer", "Relayer $relayerUrl returned failover status ${response.code}") @@ -78,9 +84,6 @@ class RelayerInterceptor( } AppLogger.w("Relayer", "All candidate relayers failed for request") - if (directFailureResponse != null) { - return directFailureResponse - } if (directException != null) { when (directException) { is IOException -> throw directException @@ -88,6 +91,9 @@ class RelayerInterceptor( else -> throw IOException(directException) } } + if (directFailoverCode != null) { + throw IOException("Direct request failed with HTTP $directFailoverCode and all candidate relayers failed") + } return chain.proceed(request) } @@ -126,21 +132,22 @@ class RelayerInterceptor( private fun buildRelayedRequest(originalRequest: Request, relayerBaseUrl: String): Request { val originalUrl = originalRequest.url.toString() - val b64 = Base64.encodeToString( - originalUrl.toByteArray(Charsets.UTF_8), - Base64.URL_SAFE or Base64.NO_WRAP, - ).trim() val rawBase = relayerBaseUrl.trim() val base = if (rawBase.startsWith("http://", ignoreCase = true) || rawBase.startsWith("https://", ignoreCase = true)) { rawBase } else { "https://$rawBase" } - val relayerUrl = when { - base.endsWith("?url=") -> "$base$b64" - base.endsWith("&url=") -> "$base$b64" - base.contains("?") -> "${base}&url=$b64" - else -> "${base.trimEnd('/')}/?url=$b64" + val targetHttpUrl = base.toHttpUrlOrNull() + val relayerUrl: String = if (targetHttpUrl != null) { + targetHttpUrl.newBuilder() + .setQueryParameter("url", originalUrl) + .build() + .toString() + } else { + val sep = if (base.contains("?")) "&" else "?" + val encoded = java.net.URLEncoder.encode(originalUrl, "UTF-8") + "$base${sep}url=$encoded" } return originalRequest.newBuilder() .url(relayerUrl) diff --git a/app/src/main/java/com/vauth/foxyvpn/data/SettingsStore.kt b/app/src/main/java/com/vauth/foxyvpn/data/SettingsStore.kt index 1ebde001..85107c0d 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/SettingsStore.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/SettingsStore.kt @@ -70,7 +70,7 @@ class SettingsStore(context: Context) { } var automaticRecovery: Boolean - get() = prefs.getBoolean("automatic_recovery", false) + get() = prefs.getBoolean("automatic_recovery", true) set(value) { prefs.edit().putBoolean("automatic_recovery", value).apply() } @@ -657,7 +657,6 @@ class SettingsStore(context: Context) { const val RELAYER_AUTOMATIC = "AUTOMATIC" const val RELAYER_DIRECT = "DIRECT" const val RELAYER_CUSTOM = "CUSTOM" - val DEFAULT_RELAYED_ENDPOINTS = setOf("guardian") private const val KEY_RELAYER_PROVIDER = "relayer_provider" private const val KEY_CUSTOM_RELAYER_URL = "custom_relayer_url" private const val KEY_RELAYED_ENDPOINTS = "relayed_endpoints" diff --git a/app/src/main/java/com/vauth/foxyvpn/data/TokenStore.kt b/app/src/main/java/com/vauth/foxyvpn/data/TokenStore.kt index e3fa8ae5..750627a8 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/TokenStore.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/TokenStore.kt @@ -61,13 +61,13 @@ class TokenStore(context: Context) { synchronized(sessionLock) { runCatching { val access = prefs.getString(KEY_ACCESS_TOKEN, null)?.takeIf { it.isNotBlank() } - mutableStorageError.value = null - if (access == null) return@runCatching null val refresh = prefs.getString(KEY_REFRESH_TOKEN, null)?.takeIf { it.isNotBlank() } + mutableStorageError.value = null + if (access == null && refresh == null) return@runCatching null val expiresAt = prefs.getLong(KEY_EXPIRES_AT, 0L) mutableStorageError.value = null - RuntimeAuth(access, refresh, expiresAt) + RuntimeAuth(access ?: "", refresh, expiresAt) } .onFailure { storageFailure( @@ -80,7 +80,7 @@ class TokenStore(context: Context) { fun hasValidAccessToken(): Boolean { val auth = loadAuth() ?: return false - if (auth.expiresAtEpochSeconds <= 0L) return false + if (auth.accessToken.isBlank() || auth.expiresAtEpochSeconds <= 0L) return false val nowSeconds = System.currentTimeMillis() / 1000 return auth.expiresAtEpochSeconds - nowSeconds > CLOCK_SKEW_TOLERANCE_SECONDS } diff --git a/app/src/main/java/com/vauth/foxyvpn/data/TunnelSettings.kt b/app/src/main/java/com/vauth/foxyvpn/data/TunnelSettings.kt index 9313f624..3e48dd59 100644 --- a/app/src/main/java/com/vauth/foxyvpn/data/TunnelSettings.kt +++ b/app/src/main/java/com/vauth/foxyvpn/data/TunnelSettings.kt @@ -13,7 +13,6 @@ data class TunnelSettings( val fragmentFallbackDelay: Int, val httpVersion: SettingsStore.HttpVersion, val ipMode: SettingsStore.IpMode = SettingsStore.IpMode.DUAL_STACK, - val ipv6Enabled: Boolean = ipMode.hasIpv6, val maxConcurrentStreams: Int, val mtu: Int, val localProxyAuthEnabled: Boolean, @@ -55,7 +54,6 @@ fun SettingsStore.tunnelSnapshot(): TunnelSettings = fragmentFallbackDelay = fragmentFallbackDelay, httpVersion = httpVersion, ipMode = ipMode, - ipv6Enabled = ipMode.hasIpv6, maxConcurrentStreams = maxConcurrentStreams, mtu = mtu, localProxyAuthEnabled = localProxyAuthEnabled, diff --git a/app/src/main/java/com/vauth/foxyvpn/ui/HomeViewModel.kt b/app/src/main/java/com/vauth/foxyvpn/ui/HomeViewModel.kt index 3e906dfc..7f505e14 100644 --- a/app/src/main/java/com/vauth/foxyvpn/ui/HomeViewModel.kt +++ b/app/src/main/java/com/vauth/foxyvpn/ui/HomeViewModel.kt @@ -52,7 +52,7 @@ class HomeViewModel( network: Network, capabilities: NetworkCapabilities, ) { - if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { + if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) { refreshAddress() refreshAccount() } diff --git a/app/src/main/java/com/vauth/foxyvpn/ui/LoginViewModel.kt b/app/src/main/java/com/vauth/foxyvpn/ui/LoginViewModel.kt index 6127cd58..0adb386f 100644 --- a/app/src/main/java/com/vauth/foxyvpn/ui/LoginViewModel.kt +++ b/app/src/main/java/com/vauth/foxyvpn/ui/LoginViewModel.kt @@ -47,48 +47,6 @@ class LoginViewModel(private val repository: FxaAuthRepository) : ViewModel() { _uiState.value = LoginUiState() } - fun completeBrowserLoginWithTokens( - accessToken: String, - refreshToken: String?, - expiresInSeconds: Long, - ) { - if (operation?.isActive == true || _uiState.value.isLoading || _uiState.value.signedIn || _uiState.value.browserStartUrl == null) return - val requestGeneration = ++generation - _uiState.update { it.copy(isLoading = true, errorMessage = null) } - operation = - viewModelScope.launch { - try { - val result = - withTimeout(120_000L) { - repository.completeBrowserLoginWithTokens( - accessToken, - refreshToken, - expiresInSeconds, - ) - } - if (generation != requestGeneration) return@launch - result - .onSuccess { - _uiState.update { it.copy(browserStartUrl = null, signedIn = true) } - } - .onFailure { - _uiState.update { s -> s.copy(errorMessage = it.message ?: "Browser sign-in failed. Please try again.") } - } - } catch (_: TimeoutCancellationException) { - if (generation == requestGeneration) - _uiState.update { it.copy(errorMessage = "Sign-in timed out. Try again.") } - } catch (cancelled: CancellationException) { - throw cancelled - } catch (_: Exception) { - if (generation == requestGeneration) - _uiState.update { it.copy(errorMessage = "Sign-in failed. Try again.") } - } finally { - if (generation == requestGeneration) - _uiState.update { it.copy(isLoading = false) } - } - } - } - fun completeBrowserLogin(sessionToken: String) { if (operation?.isActive == true || _uiState.value.isLoading || _uiState.value.signedIn || _uiState.value.browserStartUrl == null) return val requestGeneration = ++generation diff --git a/app/src/main/java/com/vauth/foxyvpn/ui/screens/HomeScreen.kt b/app/src/main/java/com/vauth/foxyvpn/ui/screens/HomeScreen.kt index 66021a6c..313d3fde 100644 --- a/app/src/main/java/com/vauth/foxyvpn/ui/screens/HomeScreen.kt +++ b/app/src/main/java/com/vauth/foxyvpn/ui/screens/HomeScreen.kt @@ -246,8 +246,8 @@ fun HomeScreen( Icon( imageVector = Icons.Filled.Power, contentDescription = - if (state == ConnectionState.DISCONNECTED) "Connect" - else "Disconnect", + if (state == ConnectionState.DISCONNECTED) stringResource(R.string.home_connect) + else stringResource(R.string.home_disconnect), tint = ringColor, modifier = Modifier.size(56.dp), ) @@ -259,9 +259,9 @@ fun HomeScreen( Text( text = when (state) { - ConnectionState.CONNECTED -> "Connected" - ConnectionState.CONNECTING -> "Connecting\u2026" - ConnectionState.DISCONNECTED -> "Disconnected" + ConnectionState.CONNECTED -> stringResource(R.string.home_state_connected) + ConnectionState.CONNECTING -> stringResource(R.string.home_state_connecting) + ConnectionState.DISCONNECTED -> stringResource(R.string.home_state_disconnected) }, style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold), @@ -271,7 +271,8 @@ fun HomeScreen( if (state == ConnectionState.CONNECTING) { Text( - if (lastError != null) "Retrying connection\u2026 Tap to cancel" else "Tap to cancel", + if (lastError != null) stringResource(R.string.home_retrying_tap_to_cancel) + else stringResource(R.string.home_tap_to_cancel), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -311,7 +312,7 @@ fun HomeScreen( ) { Column(Modifier.padding(16.dp)) { Text( - "Location", + stringResource(R.string.home_location), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -380,7 +381,7 @@ fun HomeScreen( ) { Column(modifier = Modifier.weight(1f)) { Text( - "Current IP", + stringResource(R.string.home_current_ip), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -407,8 +408,8 @@ fun HomeScreen( ) { Text( if (isConnected) { - if (proxyOnlyActive) "Proxy active" else "Protected" - } else "Exposed", + if (proxyOnlyActive) stringResource(R.string.home_proxy_active) else stringResource(R.string.home_protected) + } else stringResource(R.string.home_exposed), style = MaterialTheme.typography.labelSmall.copy( fontWeight = FontWeight.Bold @@ -441,7 +442,7 @@ fun HomeScreen( ) { Column(modifier = Modifier.weight(1f)) { Text( - "Data Used", + stringResource(R.string.home_data_used), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -503,7 +504,7 @@ fun HomeScreen( verticalAlignment = Alignment.CenterVertically, ) { Text( - "Monthly Quota Remaining", + stringResource(R.string.home_monthly_quota_remaining), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), @@ -514,8 +515,8 @@ fun HomeScreen( remaining != null && max != null -> "${formatBytes(remaining)} / ${formatBytes(max)}" remaining != null -> formatBytes(remaining) - isUnlimited -> "Unlimited" - max != null -> "Limited to ${formatBytes(max)}" + isUnlimited -> stringResource(R.string.home_unlimited) + max != null -> stringResource(R.string.home_limited_to, formatBytes(max)) else -> "\u2014" } Text( diff --git a/app/src/main/java/com/vauth/foxyvpn/ui/screens/ServerListScreen.kt b/app/src/main/java/com/vauth/foxyvpn/ui/screens/ServerListScreen.kt index 0be5cf7f..6dd9cb5c 100644 --- a/app/src/main/java/com/vauth/foxyvpn/ui/screens/ServerListScreen.kt +++ b/app/src/main/java/com/vauth/foxyvpn/ui/screens/ServerListScreen.kt @@ -36,7 +36,6 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel import com.vauth.foxyvpn.R import com.vauth.foxyvpn.data.ProxyStateStore import com.vauth.foxyvpn.data.RECOMMENDED_COUNTRY_CODE @@ -54,23 +53,6 @@ private sealed class LocationRow { data class CityRow(val country: VpnCountry, val cityIndex: Int) : LocationRow() } -@Composable -fun ServerListScreen( - serverListClient: ServerListClient, - proxyStateStore: ProxyStateStore, - onServerSelected: () -> Unit, - onBack: () -> Unit, - viewModel: ServerListViewModel = - viewModel(factory = ServerListViewModel.factory(serverListClient, proxyStateStore)), -) { - ServerListScreen( - viewModel = viewModel, - proxyStateStore = proxyStateStore, - onServerSelected = onServerSelected, - onBack = onBack, - ) -} - @Composable fun ServerListScreen( viewModel: ServerListViewModel, diff --git a/app/src/main/java/com/vauth/foxyvpn/ui/screens/SplashScreen.kt b/app/src/main/java/com/vauth/foxyvpn/ui/screens/SplashScreen.kt index a8245160..9ddf250f 100644 --- a/app/src/main/java/com/vauth/foxyvpn/ui/screens/SplashScreen.kt +++ b/app/src/main/java/com/vauth/foxyvpn/ui/screens/SplashScreen.kt @@ -26,7 +26,7 @@ import com.vauth.foxyvpn.data.SessionStatus import kotlinx.coroutines.delay import kotlinx.coroutines.withTimeoutOrNull -private const val SESSION_RESTORE_TIMEOUT_MS = 8_000L +private const val SESSION_RESTORE_TIMEOUT_MS = 15_000L @Composable fun SplashScreen( diff --git a/app/src/main/java/com/vauth/foxyvpn/ui/settings/RelayerDialogs.kt b/app/src/main/java/com/vauth/foxyvpn/ui/settings/RelayerDialogs.kt index e4f45e54..17a80682 100644 --- a/app/src/main/java/com/vauth/foxyvpn/ui/settings/RelayerDialogs.kt +++ b/app/src/main/java/com/vauth/foxyvpn/ui/settings/RelayerDialogs.kt @@ -1,6 +1,5 @@ package com.vauth.foxyvpn.ui.settings -import android.util.Base64 import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -49,6 +48,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request private const val MAX_SAVED_RELAYER_DRAFT_CHARS = 4096 @@ -77,38 +77,71 @@ private suspend fun probeRelayerEndpoint(targetRelayerUrl: String?): RelayerProb .callTimeout(4, TimeUnit.SECONDS) .build() try { - val probeTarget = FoxyRemoteConfig.current.endpoints.latencyProbe.ifBlank { "https://1.1.1.1" } - val requestUrl = if (targetRelayerUrl != null) { - val b64 = Base64.encodeToString( - probeTarget.toByteArray(Charsets.UTF_8), - Base64.URL_SAFE or Base64.NO_WRAP, - ).trim() + val start = System.nanoTime() + if (targetRelayerUrl != null) { val rawBase = targetRelayerUrl.trim() val base = if (rawBase.startsWith("http://", ignoreCase = true) || rawBase.startsWith("https://", ignoreCase = true)) { rawBase } else { "https://$rawBase" } - when { - base.endsWith("?url=") -> "$base$b64" - base.endsWith("&url=") -> "$base$b64" - base.contains("?") -> "${base}&url=$b64" - else -> "${base.trimEnd('/')}/?url=$b64" + val httpUrl = base.toHttpUrlOrNull() + val probeUrl: String = if (httpUrl != null) { + httpUrl.newBuilder() + .setQueryParameter("health", "1") + .build() + .toString() + } else { + val sep = if (base.contains("?")) "&" else "?" + "$base${sep}health=1" } + val request = Request.Builder() + .url(probeUrl) + .header("Accept", "application/json") + .header("Cache-Control", "no-cache, no-store") + .build() + client.newCall(request).execute().use { response -> + if (response.code in 200..299 && response.header("X-Relay-Error") == null) { + val ms = ((System.nanoTime() - start) / 1_000_000L).coerceAtLeast(1L).toInt() + return@withContext RelayerProbeState.Success(ms) + } else if (response.code == 404) { + val allowedTarget = FoxyRemoteConfig.current.endpoints.serverList + val fallbackUrl: String = if (httpUrl != null) { + httpUrl.newBuilder() + .setQueryParameter("url", allowedTarget) + .build() + .toString() + } else { + val sep = if (base.contains("?")) "&" else "?" + val encoded = java.net.URLEncoder.encode(allowedTarget, "UTF-8") + "$base${sep}url=$encoded" + } + val fbReq = Request.Builder() + .url(fallbackUrl) + .header("Cache-Control", "no-cache, no-store") + .build() + client.newCall(fbReq).execute().use { fbResp -> + if (fbResp.code in 200..499 && fbResp.header("X-Relay-Error") == null) { + val ms = ((System.nanoTime() - start) / 1_000_000L).coerceAtLeast(1L).toInt() + return@withContext RelayerProbeState.Success(ms) + } + } + } + } + RelayerProbeState.Failed } else { - probeTarget - } - val request = Request.Builder() - .url(requestUrl) - .header("Cache-Control", "no-cache, no-store") - .build() - val start = System.nanoTime() - client.newCall(request).execute().use { response -> - if (response.code in 200..499) { - val ms = ((System.nanoTime() - start) / 1_000_000L).coerceAtLeast(1L).toInt() - RelayerProbeState.Success(ms) - } else { - RelayerProbeState.Failed + val probeTarget = FoxyRemoteConfig.current.endpoints.latencyProbe.ifBlank { "https://1.1.1.1" } + val request = Request.Builder() + .url(probeTarget) + .header("Cache-Control", "no-cache, no-store") + .build() + client.newCall(request).execute().use { response -> + if (response.code in 200..499) { + val ms = ((System.nanoTime() - start) / 1_000_000L).coerceAtLeast(1L).toInt() + RelayerProbeState.Success(ms) + } else { + RelayerProbeState.Failed + } } } } catch (_: Exception) { diff --git a/app/src/main/java/com/vauth/foxyvpn/vpn/CredentialDeadline.kt b/app/src/main/java/com/vauth/foxyvpn/vpn/CredentialDeadline.kt index e2f046ee..1d06296b 100644 --- a/app/src/main/java/com/vauth/foxyvpn/vpn/CredentialDeadline.kt +++ b/app/src/main/java/com/vauth/foxyvpn/vpn/CredentialDeadline.kt @@ -5,7 +5,8 @@ internal fun credentialDeadlineMillis( nowWallMillis: Long, nowElapsedMillis: Long, ): Long { - val maximumAge = 5 * 60_000L + val defaultLifetime = 10 * 60_000L + val maximumAge = 24 * 60 * 60_000L val expiryMillis = expirySeconds?.let { seconds -> when { @@ -15,9 +16,9 @@ internal fun credentialDeadlineMillis( } } val lifetime = - if (expiryMillis == null) maximumAge + if (expiryMillis == null) defaultLifetime else if (expiryMillis <= nowWallMillis) 0L - else (expiryMillis - nowWallMillis - 30_000L).coerceIn(0L, maximumAge) + else (expiryMillis - nowWallMillis).coerceIn(0L, maximumAge) return if (nowElapsedMillis > Long.MAX_VALUE - lifetime) Long.MAX_VALUE else nowElapsedMillis + lifetime } diff --git a/app/src/main/java/com/vauth/foxyvpn/vpn/ExitCheck.kt b/app/src/main/java/com/vauth/foxyvpn/vpn/ExitCheck.kt index 46a17a95..9127f9e3 100644 --- a/app/src/main/java/com/vauth/foxyvpn/vpn/ExitCheck.kt +++ b/app/src/main/java/com/vauth/foxyvpn/vpn/ExitCheck.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.Request +import org.json.JSONObject private const val EXIT_CHECK_TIMEOUT_SECONDS = 15L @@ -65,6 +66,21 @@ class ExitCheck { loc = line.removePrefix("loc=").trim() } } + if (ip.isBlank() || loc.isBlank()) { + runCatching { + val json = JSONObject(body) + if (ip.isBlank()) { + ip = json.optString("ip").ifBlank { json.optString("query") }.trim() + } + if (loc.isBlank()) { + loc = + json.optString("country_code") + .ifBlank { json.optString("countryCode") } + .ifBlank { json.optString("loc") } + .trim() + } + } + } if (!SettingsStore.isValidIpAddress(ip)) { error("Trace response did not contain a valid IP address") } diff --git a/app/src/main/java/com/vauth/foxyvpn/vpn/FoxyVpnService.kt b/app/src/main/java/com/vauth/foxyvpn/vpn/FoxyVpnService.kt index 39d49fec..b9cc0b68 100644 --- a/app/src/main/java/com/vauth/foxyvpn/vpn/FoxyVpnService.kt +++ b/app/src/main/java/com/vauth/foxyvpn/vpn/FoxyVpnService.kt @@ -35,7 +35,6 @@ import com.vauth.foxyvpn.data.ServerListClient import com.vauth.foxyvpn.data.SettingsStore import com.vauth.foxyvpn.data.TokenInvalidError import com.vauth.foxyvpn.data.TunnelSettings -import com.vauth.foxyvpn.data.awaitResponse import com.vauth.foxyvpn.data.formatBytesPerSecond import com.vauth.foxyvpn.data.model.ConnectionState import com.vauth.foxyvpn.data.model.ProxyCandidate @@ -63,9 +62,11 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull data class VpnLiveStats( val txRateBytesPerSec: Long = 0L, @@ -75,7 +76,8 @@ data class VpnLiveStats( private const val TAG = "FoxyVpnService" private const val SERVER_LIST_FETCH_TIMEOUT_MS = 15_000L -private const val PROXY_PASS_FETCH_BUDGET_MS = 60_000L +private const val PROXY_PASS_FETCH_BUDGET_MS = 120_000L +private const val CREDENTIAL_EXPIRY_GRACE_MS = 60_000L private const val PROXY_PASS_RETRY_MS = 5_000L private const val WAKE_LOCK_TAG = "com.vauth.foxyvpn:vpn-cpu" private const val WIFI_LOCK_TAG = "com.vauth.foxyvpn:vpn-wifi" @@ -264,14 +266,13 @@ class FoxyVpnService : VpnService() { stopMonitoring() releaseWakeLocks() val server = commandServer - CoroutineScope(Dispatchers.IO).launch { - try { + runBlocking(Dispatchers.IO) { + withTimeoutOrNull(2500L) { interruptNativeStart(server) opMutex.withLock { teardown() } - } finally { - scope.cancel() } } + scope.cancel() (applicationContext as FoxyVpnApp) .tokenStore .clearSessionInvalidationListener(sessionInvalidationListener) @@ -482,9 +483,9 @@ class FoxyVpnService : VpnService() { } } deadline = installedCredentialDeadline.get() - nextDelay = - (deadline - SystemClock.elapsedRealtime() - PROXY_PASS_FETCH_BUDGET_MS) - .coerceAtLeast(0L) + val computedDelay = + deadline - SystemClock.elapsedRealtime() - PROXY_PASS_FETCH_BUDGET_MS + nextDelay = if (computedDelay > 0L) computedDelay else 10_000L AppLogger.i(TAG, "proxy pass replaced through the scoped core API") } catch (error: Exception) { if ( @@ -502,12 +503,9 @@ class FoxyVpnService : VpnService() { error, ) nextDelay = - minOf( - maxOf( - PROXY_PASS_RETRY_MS, - (error as? GuardianHttpError)?.retryAfterMs ?: 0L, - ), - (deadline - SystemClock.elapsedRealtime()).coerceAtLeast(0L), + maxOf( + PROXY_PASS_RETRY_MS, + (error as? GuardianHttpError)?.retryAfterMs ?: 0L, ) } } @@ -520,7 +518,8 @@ class FoxyVpnService : VpnService() { scope.launch { while (isActive) { val remaining = - installedCredentialDeadline.get() - SystemClock.elapsedRealtime() + installedCredentialDeadline.get() + CREDENTIAL_EXPIRY_GRACE_MS - + SystemClock.elapsedRealtime() if (remaining > 0L) { delay(remaining) continue @@ -533,7 +532,10 @@ class FoxyVpnService : VpnService() { ) return@launch - if (SystemClock.elapsedRealtime() >= installedCredentialDeadline.get()) { + if ( + SystemClock.elapsedRealtime() >= + installedCredentialDeadline.get() + CREDENTIAL_EXPIRY_GRACE_MS + ) { _lastError.value = "Proxy credentials expired. Reconnect to retry." requestDisconnect("installed credential deadline reached") return@launch @@ -1082,7 +1084,7 @@ class FoxyVpnService : VpnService() { ?.getNetworkCapabilities(it) } if ( - capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) != + capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) != true ) { synchronized(credentialCommitLock) { @@ -1113,21 +1115,9 @@ class FoxyVpnService : VpnService() { settings.effectiveCustomEdgeAddress == null ) { - val directWorks = - urls.all { url -> - try { - val request = okhttp3.Request.Builder().url(url).build() - ControlPlaneHttp.client.newCall(request).awaitResponse().use { - it.isSuccessful - } - } catch (cancelled: CancellationException) { - throw cancelled - } catch (_: Exception) { - false - } - } + val networkAvailable = firstUsableNetwork() != null if ( - directWorks && + networkAvailable && current() && firstUsableNetwork() == network && recoveryBudget.tryAcquire(SystemClock.elapsedRealtime()) diff --git a/app/src/main/java/com/vauth/foxyvpn/vpn/ListenerAvailability.kt b/app/src/main/java/com/vauth/foxyvpn/vpn/ListenerAvailability.kt index 933e1917..bf1b981e 100644 --- a/app/src/main/java/com/vauth/foxyvpn/vpn/ListenerAvailability.kt +++ b/app/src/main/java/com/vauth/foxyvpn/vpn/ListenerAvailability.kt @@ -53,15 +53,4 @@ internal object ListenerAvailability { ) } } - - suspend fun requireAvailable( - ports: List, - bindAddress: String = "127.0.0.1", - maxAttempts: Int = 5, - delayMs: Long = 200L, - ) = requireAvailable( - listeners = ports.map { bindAddress to it }, - maxAttempts = maxAttempts, - delayMs = delayMs, - ) } diff --git a/app/src/main/java/com/vauth/foxyvpn/vpn/SingBoxConfigBuilder.kt b/app/src/main/java/com/vauth/foxyvpn/vpn/SingBoxConfigBuilder.kt index 8bbc8f4a..c788b91c 100644 --- a/app/src/main/java/com/vauth/foxyvpn/vpn/SingBoxConfigBuilder.kt +++ b/app/src/main/java/com/vauth/foxyvpn/vpn/SingBoxConfigBuilder.kt @@ -487,6 +487,15 @@ object SingBoxConfigBuilder { ) put( JSONObject().apply { + put( + "domain_suffix", + JSONArray().apply { + put("google.com") + put("googleapis.com") + put("gstatic.com") + put("android.com") + }, + ) put( "port", JSONArray().apply { diff --git a/app/src/main/java/com/vauth/foxyvpn/widget/QuickConnectWidgetProvider.kt b/app/src/main/java/com/vauth/foxyvpn/widget/QuickConnectWidgetProvider.kt index 3f182c0e..9ec1557a 100644 --- a/app/src/main/java/com/vauth/foxyvpn/widget/QuickConnectWidgetProvider.kt +++ b/app/src/main/java/com/vauth/foxyvpn/widget/QuickConnectWidgetProvider.kt @@ -3,6 +3,7 @@ package com.vauth.foxyvpn.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider +import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Intent @@ -34,9 +35,9 @@ class QuickConnectWidgetProvider : AppWidgetProvider() { } } - override fun onReceive(context: Context, intent: Intent) { - super.onReceive(context, intent) - if (intent.action == ACTION_TOGGLE_VPN) { + class ToggleReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != ACTION_TOGGLE_VPN) return if (FoxyVpnService.state.value != ConnectionState.DISCONNECTED) { FoxyVpnService.stop(context) return @@ -64,43 +65,43 @@ class QuickConnectWidgetProvider : AppWidgetProvider() { } } - private fun handleToggle(context: Context, signedIn: Boolean) { - when (FoxyVpnService.state.value) { - ConnectionState.CONNECTED, - ConnectionState.CONNECTING -> return - ConnectionState.DISCONNECTED -> { - val app = context.applicationContext as? FoxyVpnApp - if (!signedIn) { - launchMainActivity(context) - return - } - - val settingsStore = app?.settingsStore ?: SettingsStore(context) - if (settingsStore.proxyOnlyMode) { - FoxyVpnService.start(context) - return - } + companion object { + const val ACTION_TOGGLE_VPN = "com.vauth.foxyvpn.action.TOGGLE_VPN" - val prepareIntent = VpnService.prepare(context) - if (prepareIntent != null) { - launchMainActivity(context) - } else { - FoxyVpnService.start(context) + private fun handleToggle(context: Context, signedIn: Boolean) { + when (FoxyVpnService.state.value) { + ConnectionState.CONNECTED, + ConnectionState.CONNECTING -> return + ConnectionState.DISCONNECTED -> { + val app = context.applicationContext as? FoxyVpnApp + if (!signedIn) { + launchMainActivity(context) + return + } + + val settingsStore = app?.settingsStore ?: SettingsStore(context) + if (settingsStore.proxyOnlyMode) { + FoxyVpnService.start(context) + return + } + + val prepareIntent = VpnService.prepare(context) + if (prepareIntent != null) { + launchMainActivity(context) + } else { + FoxyVpnService.start(context) + } } } } - } - private fun launchMainActivity(context: Context) { - val intent = - Intent(context, MainActivity::class.java).apply { - addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) - } - context.startActivity(intent) - } - - companion object { - const val ACTION_TOGGLE_VPN = "com.vauth.foxyvpn.action.TOGGLE_VPN" + private fun launchMainActivity(context: Context) { + val intent = + Intent(context, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + } + context.startActivity(intent) + } fun updateAll(context: Context, state: ConnectionState) { val appWidgetManager = AppWidgetManager.getInstance(context) ?: return @@ -123,7 +124,7 @@ class QuickConnectWidgetProvider : AppWidgetProvider() { val views = RemoteViews(context.packageName, R.layout.widget_quick_connect) val toggleIntent = - Intent(context, QuickConnectWidgetProvider::class.java).apply { + Intent(context, ToggleReceiver::class.java).apply { action = ACTION_TOGGLE_VPN } val pendingIntent = diff --git a/app/src/main/res/drawable/ic_power.xml b/app/src/main/res/drawable/ic_power.xml index 8b136cd6..c5fe7b55 100644 --- a/app/src/main/res/drawable/ic_power.xml +++ b/app/src/main/res/drawable/ic_power.xml @@ -1,5 +1,4 @@ - diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 54859e7e..3b3a9032 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -112,6 +112,22 @@ Latency Pinging… Recommended + Connect + Disconnect + Connected + Connecting\u2026 + Disconnected + Retrying connection\u2026 Tap to cancel + Tap to cancel + Location + Current IP + Protected + Exposed + Proxy active + Data Used + Monthly Quota Remaining + Unlimited + Limited to %1$s Back Connection DNS