Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ jobs:
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' }}

# Robolectric downloads its android-all runtime from Maven Central on first use. That
# fetch is the one flaky part of this job, so the jars are cached across runs.
- name: Cache Robolectric runtime
uses: actions/cache@v4
with:
path: ~/.m2/repository/org/robolectric
key: robolectric-${{ runner.os }}-${{ hashFiles('app/src/test/resources/robolectric.properties') }}
restore-keys: robolectric-${{ runner.os }}-

- name: Unit tests
run: |
set -o pipefail
Expand Down
49 changes: 49 additions & 0 deletions app/src/main/java/com/bansify/browser/browser/UserAgentUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.bansify.browser.browser

/**
* User-agent handling for a real browser built on Android WebView.
*
* WebView's stock UA carries two tokens that bot checks (Cloudflare Turnstile, reCAPTCHA,
* hCaptcha) treat as "this is an embedded app view, not a browser":
*
* `...; wv) AppleWebKit/... Version/4.0 Chrome/120.0.0.0 Mobile Safari/537.36`
* ^^ ^^^^^^^^^^^^
*
* Stripping them makes the browser present itself the way Chrome on Android does, which is
* exactly what it is: a real browser the user drives by hand. Everything else (engine
* version, platform, mobile token) is kept, so the UA still matches the engine that is
* actually rendering the page — an inconsistent UA is itself a bot signal.
*/
object UserAgentUtils {

/**
* Removes the WebView-only markers while keeping the real engine version.
* Safe to call twice; returns the input unchanged if it carries neither marker.
*/
fun normalize(rawUserAgent: String): String {
var ua = rawUserAgent
// `; wv` sits inside the platform parentheses: "(Linux; Android 13; Pixel 7; wv)".
ua = ua.replace("; wv)", ")")
ua = ua.replace("; wv;", ";")
ua = ua.replace(" wv)", ")")
// Legacy Chromium token that only WebView emits.
ua = ua.replace("Version/4.0 ", "")
return ua.trim()
}

/**
* Builds a desktop UA from the device's own UA so the engine version always matches.
* Returns [mobileUserAgent] unchanged when it cannot find the platform section.
*/
fun toDesktop(mobileUserAgent: String): String {
val versionPart = mobileUserAgent.substringAfter("(KHTML, like Gecko)", "")
.trim()
.replace(" Mobile", "")
if (versionPart.isBlank()) return mobileUserAgent
return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) $versionPart"
}

/** True when the UA still looks like an embedded WebView. */
fun looksLikeWebView(userAgent: String): Boolean =
userAgent.contains("; wv)") || userAgent.contains("Version/4.0")
}
41 changes: 30 additions & 11 deletions app/src/main/java/com/bansify/browser/browser/WebViewPool.kt
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,9 @@ class WebViewPool(
@Volatile
var pendingState: Bundle? = null

/** Fallback only; the real desktop UA is derived from the device UA (see UserAgentUtils). */
private const val DESKTOP_USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

fun getOrCreateWebView(tab: BrowserTab, settings: BrowserSettings): WebView {
Expand Down Expand Up @@ -280,10 +281,15 @@ class WebViewPool(

fun setDesktopSite(tab: BrowserTab, enabled: Boolean) {
val wv = webViews[tab.id] ?: return
val defaultUa = defaultUserAgents[tab.id] ?: wv.settings.userAgentString
wv.settings.userAgentString = if (enabled) DESKTOP_USER_AGENT else defaultUa
wv.settings.useWideViewPort = true
wv.settings.loadWithOverviewMode = true
val deviceUa = defaultUserAgents[tab.id]
?: UserAgentUtils.normalize(wv.settings.userAgentString)
wv.settings.userAgentString = if (enabled) {
UserAgentUtils.toDesktop(deviceUa).takeIf { it != deviceUa } ?: DESKTOP_USER_AGENT
} else {
deviceUa
}
wv.settings.useWideViewPort = enabled
wv.settings.loadWithOverviewMode = enabled
if (!tab.isNewTab) {
wv.reload()
}
Expand Down Expand Up @@ -440,7 +446,7 @@ class WebViewPool(
isFocusableInTouchMode = true
}

defaultUserAgents[tab.id] = webView.settings.userAgentString
defaultUserAgents[tab.id] = UserAgentUtils.normalize(webView.settings.userAgentString)
applySettingsToWebView(webView, tab, settings)

webView.setFindListener { activeMatchOrdinal, numberOfMatches, _ ->
Expand Down Expand Up @@ -527,6 +533,9 @@ class WebViewPool(
canGoBack = wv.canGoBack(),
canGoForward = wv.canGoForward()
)
// Challenge cookies (Cloudflare, Google) must survive a restart or the user is
// asked again on the next launch.
runCatching { CookieManager.getInstance().flush() }
wv.postDelayed({ captureThumbnail(tab.id) }, 250L)
}

Expand Down Expand Up @@ -788,8 +797,6 @@ class WebViewPool(
ws.javaScriptCanOpenWindowsAutomatically = settings.popupsAllowed
ws.mediaPlaybackRequiresUserGesture = !settings.mediaAutoplayEnabled
ws.textZoom = settings.textZoomPercent.coerceIn(50, 200)
ws.useWideViewPort = true
ws.loadWithOverviewMode = true
ws.builtInZoomControls = true
ws.displayZoomControls = false
ws.setSupportZoom(true)
Expand All @@ -807,15 +814,27 @@ class WebViewPool(
ws.safeBrowsingEnabled = settings.safeBrowsingLevel != SafeBrowsingLevel.NONE
}

val defaultUa = defaultUserAgents[tab.id] ?: ws.userAgentString
val deviceUa = defaultUserAgents[tab.id]
?: UserAgentUtils.normalize(ws.userAgentString)
val wantDesktop = tab.isDesktopSite || settings.defaultDesktopSite
val desiredUa = if (wantDesktop) DESKTOP_USER_AGENT else defaultUa
val desiredUa = if (wantDesktop) {
UserAgentUtils.toDesktop(deviceUa).takeIf { it != deviceUa } ?: DESKTOP_USER_AGENT
} else {
deviceUa
}
if (ws.userAgentString != desiredUa) {
ws.userAgentString = desiredUa
}
// A mobile UA with a 980px overview viewport is an inconsistency bot checks flag, so the
// wide viewport only applies in desktop mode.
ws.useWideViewPort = wantDesktop
ws.loadWithOverviewMode = wantDesktop

val cookieManager = CookieManager.getInstance()
cookieManager.setAcceptCookie(settings.cookiesEnabled && !tab.isIncognito)
// CookieManager.setAcceptCookie is process-wide. Driving it from the current tab meant an
// incognito tab turned cookies off for every tab, which made reCAPTCHA and Cloudflare
// Turnstile loop forever. The user's setting decides; incognito is handled below.
cookieManager.setAcceptCookie(settings.cookiesEnabled)
val allowThirdParty = when {
!settings.cookiesEnabled -> false
settings.thirdPartyCookiePolicy == ThirdPartyCookiePolicy.BLOCK_ALL -> false
Expand Down
48 changes: 48 additions & 0 deletions app/src/test/java/com/bansify/browser/UserAgentUtilsTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.bansify.browser

import com.bansify.browser.browser.UserAgentUtils
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class UserAgentUtilsTest {

private val webViewUa =
"Mozilla/5.0 (Linux; Android 13; Pixel 7; wv) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Version/4.0 Chrome/120.0.6099.144 Mobile Safari/537.36"

private val chromeUa =
"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/120.0.6099.144 Mobile Safari/537.36"

@Test
fun `webview markers are removed`() {
assertEquals(chromeUa, UserAgentUtils.normalize(webViewUa))
assertFalse(UserAgentUtils.looksLikeWebView(UserAgentUtils.normalize(webViewUa)))
}

@Test
fun `normalising twice changes nothing`() {
val once = UserAgentUtils.normalize(webViewUa)
assertEquals(once, UserAgentUtils.normalize(once))
}

@Test
fun `a normal chrome ua is left alone`() {
assertEquals(chromeUa, UserAgentUtils.normalize(chromeUa))
}

@Test
fun `desktop ua keeps the engine version and drops mobile`() {
val desktop = UserAgentUtils.toDesktop(chromeUa)
assertTrue(desktop.startsWith("Mozilla/5.0 (X11; Linux x86_64)"))
assertTrue(desktop.contains("Chrome/120.0.6099.144"))
assertFalse(desktop.contains("Mobile"))
}

@Test
fun `desktop conversion falls back when the ua has no platform section`() {
assertEquals("garbage", UserAgentUtils.toDesktop("garbage"))
}
}
20 changes: 20 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,23 @@ Gothwad Accounts service and it does not sync anything yet. Real SSO is tracked
- The ViewModel never touches `Context` beyond what it is given at construction.
- Anything that must survive process death goes to Room or DataStore, never to a field.
- No network client of its own: pages are rendered by the platform `WebView`.

## Bot verification, cookies and the user agent

Three details decide whether Cloudflare Turnstile, reCAPTCHA and hCaptcha let a visitor
through. All three were wrong once, and the symptoms were "verification failed" and endless
captcha prompts.

1. **The user agent must look like a browser.** WebView's stock UA carries `; wv)` and
`Version/4.0`, both of which mark an embedded app view. `UserAgentUtils.normalize()`
removes exactly those two tokens and keeps the real engine version, so the UA still
matches what is actually rendering the page. Desktop mode is derived from the same UA
(`toDesktop()`), never hardcoded, for the same reason.
2. **`CookieManager.setAcceptCookie` is process-wide.** It is set from the user's cookie
preference only — never from a single tab. Driving it from the current tab meant opening
an incognito tab silently disabled cookies for every tab, and every challenge then failed.
3. **The viewport must agree with the UA.** A mobile UA with a 980 px overview viewport is an
inconsistency challenge scripts flag, so `useWideViewPort`/`loadWithOverviewMode` are only
on in desktop mode.

Cookies are flushed after each page finishes so a passed challenge survives the next launch.
Loading