From fd3b890a6a4b660afabfa8e2c91ef2dd99122cd9 Mon Sep 17 00:00:00 2001 From: Gothwad Tech Date: Sat, 28 Nov 2026 12:05:14 +0000 Subject: [PATCH 1/2] fix: bot verification and captcha loops Cloudflare Turnstile failed and Google kept asking for a captcha. Three causes: 1. CookieManager.setAcceptCookie is process-wide, but it was set from the current tab: "cookiesEnabled && !tab.isIncognito". Opening an incognito tab therefore disabled cookies for every tab, so challenge cookies never stuck. It is now set from the user's cookie preference only. 2. WebView's stock UA carries "; wv)" and "Version/4.0", the tokens bot checks read as "embedded app view". UserAgentUtils.normalize() strips exactly those and keeps the real engine version; the desktop UA is derived from the device UA instead of the hardcoded Chrome/128 (a version that never matched the engine). 3. A mobile UA with useWideViewPort/loadWithOverviewMode on reports a 980px viewport, an inconsistency challenge scripts flag. Both are now desktop-mode only. Also: cookies are flushed after each page so a passed challenge survives a restart. Adds UserAgentUtils + 5 unit tests, and a docs note on why each of these matters. --- .../bansify/browser/browser/UserAgentUtils.kt | 49 +++++++++++++++++++ .../bansify/browser/browser/WebViewPool.kt | 41 +++++++++++----- .../com/bansify/browser/UserAgentUtilsTest.kt | 48 ++++++++++++++++++ docs/ARCHITECTURE.md | 20 ++++++++ 4 files changed, 147 insertions(+), 11 deletions(-) create mode 100644 app/src/main/java/com/bansify/browser/browser/UserAgentUtils.kt create mode 100644 app/src/test/java/com/bansify/browser/UserAgentUtilsTest.kt diff --git a/app/src/main/java/com/bansify/browser/browser/UserAgentUtils.kt b/app/src/main/java/com/bansify/browser/browser/UserAgentUtils.kt new file mode 100644 index 0000000..f475b60 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/browser/UserAgentUtils.kt @@ -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") +} diff --git a/app/src/main/java/com/bansify/browser/browser/WebViewPool.kt b/app/src/main/java/com/bansify/browser/browser/WebViewPool.kt index 352584e..b437544 100644 --- a/app/src/main/java/com/bansify/browser/browser/WebViewPool.kt +++ b/app/src/main/java/com/bansify/browser/browser/WebViewPool.kt @@ -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 { @@ -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() } @@ -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, _ -> @@ -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) } @@ -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) @@ -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 diff --git a/app/src/test/java/com/bansify/browser/UserAgentUtilsTest.kt b/app/src/test/java/com/bansify/browser/UserAgentUtilsTest.kt new file mode 100644 index 0000000..e8bf4e8 --- /dev/null +++ b/app/src/test/java/com/bansify/browser/UserAgentUtilsTest.kt @@ -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")) + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9e2a4ba..54f4902 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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. From 452b7a9f95e662e4af84c853ee8e5f09c8b87816 Mon Sep 17 00:00:00 2001 From: Gothwad Tech Date: Sat, 28 Nov 2026 12:09:17 +0000 Subject: [PATCH 2/2] ci: cache Robolectric's android-all runtime MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unit-test job failed twice in a row on 'AssertionError at MavenArtifactFetcher.java:129 ... IOException' — Robolectric could not fetch its android-all jar from Maven Central. Cache ~/.m2/repository/org/robolectric across runs so one bad network moment cannot block a pull request. --- .github/workflows/quality.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 685ae18..ab30297 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -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