Modern Apps git

← Modern-Apps.git

web: added brave shields content blocking

Commit
d7dd7037e077d34a9aa6d7ab72c718493f2984c5
Author
Vayun Mathur <[email protected]>
When
2026-08-06 02:29 UTC (4 months ago)
Parents
5dc703f

Diff

BRAVE_SHIELDS_PLAN.plan.md
diff --git a/BRAVE_SHIELDS_PLAN.plan.md b/BRAVE_SHIELDS_PLAN.plan.mdnew file mode 100644index 0000000000..375b7ac423--- /dev/null+++ b/BRAVE_SHIELDS_PLAN.plan.md@@ -0,0 +1,177 @@+# Brave Shields for `:web`++Port Brave's four protection subsystems into the existing WebView browser at+`/Users/vayun/Documents/Modern-Apps/web`, keeping the `AndroidView` + `android.webkit.WebView`+architecture exactly as it is.++**Decisions locked in:** Brave's real `adblock-rust` engine via JNI · bundle-only filter lists ·+global toggles + per-site shields panel with allowlist and block counter · **Aggressive** defaults.++---++## Goal++Replace the current 10-entry hardcoded blocklist+(`web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt:159-171`) with the actual Brave+Shields stack:++| Shield | Mechanism in a WebView |+|---|---|+| Network ad/tracker blocking | `adblock` crate in `shouldInterceptRequest` |+| Cosmetic filtering | `url_cosmetic_resources` + `hidden_class_id_selectors`, injected at document start |+| Fingerprinting protection | Farbling JS injected at document start, per-session × per-eTLD+1 seed |+| URL cleaning + HTTPS upgrade | `shouldOverrideUrlLoading` + adblock `$removeparam` rewrites |++---++## Feasibility already verified++- `adblock` **v0.13.2** resolves and **compiles clean for `aarch64-linux-android` in 24s**+  (61 crates, `default-features = false`, features `embedded-domain-resolver` + `full-regex-handling`).+- Required API confirmed present in the crate source: `Engine::new_with_list_text`,+  `use_resources`, `check_network_request(&Request) -> BlockerResult`,+  `url_cosmetic_resources(url) -> UrlSpecificResources`, `hidden_class_id_selectors`,+  `serialize`/`deserialize`.+- `rustNativeLib(crate)` in `build-logic/src/main/kotlin/RustNative.kt` makes wiring a one-liner;+  `pdf/build.gradle.kts:18-32` is the copy-paste precedent.+- ⚠️ **Pre-existing, unrelated env bug:** plain `cargo build --target aarch64-linux-android` fails+  with `can't find crate for core` for **every** Rust module in this repo (verified against+  `library/jni-http`). Setting `RUSTC=$HOME/.cargo/bin/rustc` fixes it. Will add that one line to+  `RustNative.kt` so all 15 native modules build again.++---++## Phase 1 — Filter list assets++Bundle-only, following the repo's established "generator script in `scripts/` + brotli asset"+convention (`scripts/wordmaker/generate_dictionary_assets.py`, `libs.brotli.dec` is already in the+version catalog at `gradle/libs.versions.toml:223`).++- **New** `scripts/generate_shields_lists.py` — developer-run, offline. Fetches EasyList,+  EasyPrivacy, Brave's default + unbreak lists and uBO's `resources.json` (scriptlet/redirect+  bodies), strips comments, concatenates, brotli-compresses.+- **New assets** (checked in):+  - `web/src/main/assets/shields/filters.txt.br` (~700 KB from ~4.5 MB raw)+  - `web/src/main/assets/shields/resources.json.br`+  - `web/src/main/assets/shields/farble.js` (Phase 5, hand-written)++## Phase 2 — Rust engine crate++- **New** `web/src/main/rust/` → crate `web_shields`, `crate-type = ["cdylib"]`.+  Deps: `jni.workspace`, `serde_json.workspace`, `adblock 0.13.2` (features as verified above).+- Register in root `Cargo.toml` `[workspace] members` + add `adblock` to `[workspace.dependencies]`.+- `src/lib.rs` JNI surface (handle = `Box::into_raw` of `Engine`, which is `Sync`):+  - `nativeCreate(filters, resourcesJson) -> jlong`+  - `nativeCreateFromCache(bytes) -> jlong` / `nativeSerialize(handle) -> ByteArray`+  - `nativeCheck(handle, url, sourceUrl, requestType) -> String` (JSON: matched / important /+    exception / redirect body / rewritten_url) — one JNI hop per request+  - `nativeCosmeticResources(handle, url) -> String`+  - `nativeHiddenClassIdSelectors(handle, classes, ids, exceptions) -> String`+  - `nativeDestroy(handle)`+- `web/build.gradle.kts`: add `rustNativeLib("web_shields")`, the `androidComponents` jniLibs block+  (mirroring `pdf`), and `implementation(libs.brotli.dec)`.++## Phase 3 — Kotlin bridge++- **New** `web/src/main/java/com/vayunmathur/web/shields/ShieldsEngine.kt` — process singleton.+  `load(context)` on `Dispatchers.IO`: deserialize `filesDir/shields/engine.dat` if its version tag+  matches the bundled asset, else parse the brotli assets and write the serialized cache.+  Exposes `check(...)`, `cosmetic(url)`, and a `ready` flag.+- Fail-open while not ready — `shouldInterceptRequest` must never block the render thread.++## Phase 4 — Network shield++- **New** `web/src/main/java/com/vayunmathur/web/shields/ShieldsWebViewClient.kt`, an open+  `WebViewClient` subclass that tracks the current main-frame URL (needed because+  `WebResourceRequest` carries no initiator) and implements `shouldInterceptRequest`:+  resource type from `Sec-Fetch-Dest` → `Accept` → extension; per-site allowlist check; blocked →+  empty response with a *type-appropriate* MIME (empty JS, 1×1 GIF for images — `text/plain` for+  everything, as today, itself breaks pages); `$redirect` → serve the uBO resource body;+  increment the per-tab counter.+- Wire into **both** `WebViewBrowser.kt` *and* `PwaActivity.kt` (which has **no**+  `shouldInterceptRequest` today).+- Delete the `adHosts` set and the dead `WebViewModel.adBlockEnabled` (`WebViewModel.kt:93-94`),+  which the interceptor never consulted.++## Phase 5 — Cosmetic filtering++- Inject via `WebViewCompat.addDocumentStartJavaScript` when+  `WebViewFeature.DOCUMENT_START_SCRIPT` is supported, else fall back to `onPageStarted` ++  `evaluateJavascript`.+- Pass 1: URL-specific hide selectors → `<style>` + Brave's `injected_script`.+- Pass 2 (Brave's model): a `MutationObserver` collects new class/id attributes and reports them+  through `WebViewCompat.addWebMessageListener` → `hidden_class_id_selectors` → inject more CSS.++## Phase 6 — Fingerprinting protection (Aggressive)++`web/src/main/assets/shields/farble.js`, prefixed at injection with a per-session × per-eTLD+1+seed so values are stable within a page but differ across sites and restarts. Farbles canvas+(`toDataURL`/`getImageData`/`toBlob` LSBs), WebGL (`getParameter` unmasked vendor/renderer,+`readPixels`), AudioContext, `measureText` font metrics, `hardwareConcurrency`, `deviceMemory`,+empty `plugins`/`mimeTypes`, `navigator.languages`. Aggressive additionally forces UTC+`getTimezoneOffset`/`Intl` and disables `RTCPeerConnection` (local-IP leak).++## Phase 7 — URL cleaning + HTTPS upgrade++- **New** `web/src/main/java/com/vayunmathur/web/shields/UrlCleaner.kt` — pure Kotlin, no+  `android.net.Uri`, so it unit-tests on the JVM. Strips Brave's tracking-param list+  (`utm_*`, `fbclid`, `gclid`, `msclkid`, `igshid`, `twclid`, `yclid`, `dclid`, `mc_eid`, …);+  adblock `$removeparam` rules supply the rest via `rewritten_url`.+- HTTPS upgrade in `shouldOverrideUrlLoading`; Aggressive = HTTPS-only (block rather than+  silently downgrade) + `mixedContentMode = MIXED_CONTENT_NEVER_ALLOW`.++## Phase 8 — Settings, state, persistence++- `ShieldLevel` enum (`OFF` / `STANDARD` / `AGGRESSIVE`) + `ShieldsSettings` in `web/util/`.+- Globals in `WebViewModel` through the existing `web_prefs` / `persistPrefs()` pattern+  (`WebViewModel.kt:38-44, 675-688`); incognito windows persist nothing.+- Per-site overrides: new Room entity `ShieldSetting(host, …)` + `MIGRATION_2_3` in+  `web/src/main/java/com/vayunmathur/web/data/WebDatabase.kt` (currently `version = 2`).+- Per-tab blocked counters in the VM, reset on main-frame navigation.++## Phase 9 — UI++- Add `IconShield()` to `library/ui/.../Icons.kt` — CONTRIBUTING.md forbids `Icon()` /+  `painterResource` / direct `androidx.compose.material.icons` imports in app modules.+- Shield button with blocked count in `BrowserChrome` actions (`BrowserPage.kt:575`), using the+  existing `Surface`+`Text` chip idiom since `:library:ui` exports `BadgedBox` but **not** `Badge`.+- **New** `ShieldsPanel` as a `ModalBottomSheet` (exported by `:library:ui`): per-site master+  toggle, per-shield switches, blocked breakdown, reload-to-apply.+- `SettingsPage.kt:124-129`: replace the dead "Ad-tracker blocking — Always on" row with a real+  Shields section + a `Route.Shields` page for per-site exceptions.+- All copy into `web/src/main/res/values/strings.xml` via `stringResource`.++## Phase 10 — Tests++`web/src/test/` does not exist yet; `kotlin.test` + JUnit4 are already wired for every app module+by `common-conventions-app.gradle.kts:195-196`, so **no Gradle change is needed**.++- `UrlCleanerTest.kt` — param stripping, HTTPS upgrade decisions+- `ResourceTypeTest.kt` — `Sec-Fetch-Dest`/`Accept`/extension → adblock `RequestType`+- `ShieldsSettingsTest.kt` — level → effective-shield resolution, per-site override precedence++---++## Risks++1. **`shouldInterceptRequest` is hot and off-thread.** Engine calls must be lock-free on the read+   path and fail-open before load completes.+2. **Aggressive farbling breaks sites.** The per-site shields panel is the escape hatch; that is+   why Phase 9 is not optional.+3. **Two WebView hosts drift.** `WebViewBrowser.kt` and `PwaActivity.kt` already have divergent+   copies of `applySettings`; Phase 4 extracts the shared client so shields can't be wired to only one.+4. **Cargo env bug** must be fixed in `RustNative.kt` first or nothing native builds.++## Files touched++**New:** `web/src/main/rust/{Cargo.toml,src/lib.rs}` · `web/src/main/assets/shields/*` ·+`web/src/main/java/com/vayunmathur/web/shields/{ShieldsEngine,ShieldsWebViewClient,UrlCleaner,ShieldsSettings}.kt` ·+`web/src/main/java/com/vayunmathur/web/ui/ShieldsPanel.kt` · `web/src/test/...` ·+`scripts/generate_shields_lists.py`++**Modified:** `Cargo.toml` · `build-logic/src/main/kotlin/RustNative.kt` · `web/build.gradle.kts` ·+`web/src/main/java/com/vayunmathur/web/ui/{WebViewBrowser,BrowserPage,SettingsPage}.kt` ·+`web/src/main/java/com/vayunmathur/web/PwaActivity.kt` ·+`web/src/main/java/com/vayunmathur/web/util/WebViewModel.kt` ·+`web/src/main/java/com/vayunmathur/web/data/WebDatabase.kt` · `web/src/main/MainActivity.kt` (route) ·+`web/src/main/res/values/strings.xml` · `library/ui/.../Icons.kt`
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 59a9698ff9..00f587ddab 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,41 @@ # It is not intended for manual editing. version = 4 +[[package]]+name = "adblock"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77420e48225975c472eaea1b7c767af6caebea02d910043b0af7a1271d47ec9c"+dependencies = [+ "addr",+ "arrayvec",+ "base64",+ "bitflags 2.13.1",+ "flatbuffers",+ "idna",+ "itertools",+ "memchr",+ "percent-encoding",+ "precomputed-hash",+ "regex",+ "rustc-hash",+ "seahash",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+ "url",+]++[[package]]+name = "addr"+version = "0.15.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a93b8a41dbe230ad5087cc721f8d41611de654542180586b315d9f4cf6b72bef"+dependencies = [+ "psl",+ "psl-types",+]+ [[package]] name = "adler2" version = "2.0.1"@@ -40,6 +75,15 @@ dependencies = [  "cpufeatures 0.3.0", ] +[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]+ [[package]] name = "android_system_properties" version = "0.1.5"@@ -102,6 +146,9 @@ name = "bitflags" version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"+dependencies = [+ "serde_core",+]  [[package]] name = "blake2"@@ -478,6 +525,17 @@ dependencies = [  "ctutils", ] +[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]+ [[package]] name = "duplicate" version = "2.0.1"@@ -582,6 +640,16 @@ dependencies = [  "zeroize", ] +[[package]]+name = "flatbuffers"+version = "25.12.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3"+dependencies = [+ "bitflags 2.13.1",+ "rustc_version",+]+ [[package]] name = "flate2" version = "1.1.9"@@ -592,6 +660,15 @@ dependencies = [  "miniz_oxide", ] +[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]+ [[package]] name = "futures-core" version = "0.3.33"@@ -752,6 +829,109 @@ dependencies = [  "cc", ] +[[package]]+name = "icu_collections"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"++[[package]]+name = "icu_properties"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"++[[package]]+name = "icu_provider"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]+ [[package]] name = "indenter" version = "0.3.4"@@ -790,6 +970,15 @@ dependencies = [  "hybrid-array", ] +[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]+ [[package]] name = "itoa" version = "1.0.18"@@ -929,6 +1118,12 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]]+name = "litemap"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"+ [[package]] name = "lock_api" version = "0.4.14"@@ -1140,6 +1335,12 @@ dependencies = [  "ttf-parser", ] +[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+ [[package]] name = "photos_fx" version = "0.1.0"@@ -1164,6 +1365,15 @@ dependencies = [  "universal-hash", ] +[[package]]+name = "potential_utf"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"+dependencies = [+ "zerovec",+]+ [[package]] name = "ppv-lite86" version = "0.2.21"@@ -1173,6 +1383,12 @@ dependencies = [  "zerocopy", ] +[[package]]+name = "precomputed-hash"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"+ [[package]] name = "proc-macro2" version = "1.0.107"@@ -1194,6 +1410,21 @@ dependencies = [  "version_check", ] +[[package]]+name = "psl"+version = "2.1.223"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0dedad316e05de220cbf3fd8bfb69f3df8755dde2d7d479211827b595168a93"+dependencies = [+ "psl-types",+]++[[package]]+name = "psl-types"+version = "2.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"+ [[package]] name = "quick-xml" version = "0.37.5"@@ -1308,6 +1539,35 @@ dependencies = [  "bitflags 2.13.1", ] +[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"+ [[package]] name = "rust-argon2" version = "3.0.0"@@ -1320,6 +1580,12 @@ dependencies = [  "crossbeam-utils", ] +[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"+ [[package]] name = "rustc_version" version = "0.4.1"@@ -1360,6 +1626,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]]+name = "seahash"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"+ [[package]] name = "secrecy" version = "0.10.3"@@ -1480,6 +1752,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c0cdea5a20a06e7c57f627094e7b1618e5665592cd88f2d45fa4014e348db58" +[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+ [[package]] name = "stringprep" version = "0.1.5"@@ -1519,6 +1797,17 @@ dependencies = [  "unicode-ident", ] +[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "thiserror" version = "1.0.69"@@ -1559,6 +1848,16 @@ dependencies = [  "syn 3.0.3", ] +[[package]]+name = "tinystr"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"+dependencies = [+ "displaydoc",+ "zerovec",+]+ [[package]] name = "tinyvec" version = "1.12.0"@@ -1671,6 +1970,24 @@ dependencies = [  "subtle", ] +[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+ [[package]] name = "uuid" version = "1.24.0"@@ -1804,6 +2121,15 @@ dependencies = [  "om-file-format-sys", ] +[[package]]+name = "web_shields"+version = "0.1.0"+dependencies = [+ "adblock",+ "jni",+ "serde_json",+]+ [[package]] name = "weezl" version = "0.1.12"@@ -1973,6 +2299,12 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]]+name = "writeable"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"+ [[package]] name = "x25519-dalek" version = "2.0.1"@@ -1985,6 +2317,29 @@ dependencies = [  "zeroize", ] +[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "synstructure",+]+ [[package]] name = "youpipe_extractor" version = "0.1.0"@@ -2015,6 +2370,27 @@ dependencies = [  "syn 2.0.119", ] +[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "synstructure",+]+ [[package]] name = "zeroize" version = "1.9.0"@@ -2035,6 +2411,39 @@ dependencies = [  "syn 2.0.119", ] +[[package]]+name = "zerotrie"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "zmij" version = "1.0.23"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 00196d5023..4404e6e24a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -15,6 +15,7 @@ members = [   "measure/src/main/rust",   "messages/src/main/rust",   "youpipe/src/main/rust",+  "web/src/main/rust",   "third_party/om-file-format-sys", ] resolver = "2"@@ -54,6 +55,10 @@ memchr = "2.8.3" quick-xml = { version = "0.37", default-features = false } serde_json = "1.0.149" +# Brave Shields engine (:web). default-features off drops `single-thread` so `Engine` is+# Send + Sync, which the WebView render thread requires.+adblock = { version = "0.13.2", default-features = false, features = ["embedded-domain-resolver", "full-regex-handling"] }+ # Imaging – image crate 0.25->moxcms/pxfm removed, use tiny jpeg-encoder/decoder (1 function per your rule) jpeg-decoder = { version = "0.3.2", default-features = false } jpeg-encoder = { version = "0.6.1", default-features = false }
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktindex 92e52e7463..96b78daade 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -95,6 +95,10 @@ fun Project.rustNativeLib(crate: String, remapLabel: String = crate) {             val rustSrc = file("src/main/rust").absolutePath              environment("PATH", "$cargoBin:${System.getenv("PATH")}")+            // A non-rustup rustc earlier on PATH (e.g. Homebrew's) has no+            // aarch64-linux-android std, so cargo fails with "can't find crate for core".+            // Pin the rustup shim explicitly.+            environment("RUSTC", "$cargoBin/rustc")             // The per-API NDK clang wrapper bakes in --target and the sysroot.             environment("CC", clang)             environment("AR", "$ndkBin/llvm-ar")
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 8e88782e96..35f2b01176 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -184,6 +184,7 @@ import androidx.compose.material.icons.filled.Save import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings+import androidx.compose.material.icons.filled.Shield import androidx.compose.material.icons.filled.SettingsBackupRestore import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Shuffle@@ -1246,6 +1247,11 @@ fun IconArea(modifier: Modifier = Modifier, tint: Color = LocalContentColor.curr fun IconHealth(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.Filled.HealthAndSafety, "Health", modifier, tint) +/** Plain shield — browser content blocking and tracking protection. */+@Composable+fun IconShield(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.Shield, "Shields", modifier, tint)+ /** Pill bottle — prescriptions and pharmacy. */ @Composable fun IconMedication(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =
scripts/generate_shields_lists.py
diff --git a/scripts/generate_shields_lists.py b/scripts/generate_shields_lists.pynew file mode 100644index 0000000000..834ad57e74--- /dev/null+++ b/scripts/generate_shields_lists.py@@ -0,0 +1,311 @@+#!/usr/bin/env python3+"""Offline generator: Brave Shields filter lists -> web/src/main/assets/shields/++Developer-run, not part of the Gradle build. Fetches Brave's own default filter+lists and the resource bodies used by `$redirect` rules, then writes three assets+that `ShieldsEngine.kt` loads at runtime:++  filters.txt.br     Every default-enabled list from Brave's list_catalog.json,+                     comments stripped and concatenated. Brotli-compressed.+  resources.json.br  A `Vec<Resource>` (adblock-rust's own serde format) holding+                     the bodies served for `$redirect` / `$redirect-rule` rules.+                     Brotli-compressed.+  version.txt        SHA-256 of the two payloads above. `ShieldsEngine` compares+                     it against the tag stored beside its serialized engine cache+                     and reparses the lists when they differ.++The list set is read from Brave's catalog rather than hardcoded, so re-running+this script picks up upstream changes to what Brave enables by default. The+iOS-specific component is the only default-enabled entry that is skipped.++Scriptlet coverage: the `$redirect` bodies come from uBlock Origin's+`web_accessible_resources/`, indexed by its `redirect-resources.js` map — the+same two inputs adblock-rust's own `resource-assembler` reads. uBO's `##+js(...)`+scriptlets are ES modules since 1.53, so they are enumerated the way Brave does+it: node imports `resources/scriptlets.js` and dumps the `builtinScriptlets`+registry. Scriptlets marked `requiresTrust` are given a non-default permission+mask, which makes adblock-rust refuse to inject them — none of the bundled lists+are trusted sources.++Usage:  python3 scripts/generate_shields_lists.py+Requires: `brotli` and `node` on PATH.+"""++import base64+import hashlib+import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+import urllib.request+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parent.parent+ASSET_DIR = REPO_ROOT / "web" / "src" / "main" / "assets" / "shields"++BRAVE_RESOURCES = "https://raw.githubusercontent.com/brave/adblock-resources/master"+LIST_CATALOG = f"{BRAVE_RESOURCES}/filter_lists/list_catalog.json"+BRAVE_SCRIPTLETS = f"{BRAVE_RESOURCES}/dist/resources.json"++UBO = "https://raw.githubusercontent.com/gorhill/uBlock/master/src"+UBO_REDIRECT_MAP = f"{UBO}/js/redirect-resources.js"+UBO_WEB_ACCESSIBLE = f"{UBO}/web_accessible_resources"+UBO_WEB_ACCESSIBLE_API = (+    "https://api.github.com/repos/gorhill/uBlock/contents/src/web_accessible_resources"+)+UBO_SCRIPTLET_DIR = f"{UBO}/js/resources"+UBO_SCRIPTLET_API = (+    "https://api.github.com/repos/gorhill/uBlock/contents/src/js/resources"+)+# Imported by files under js/resources/ but living one directory up.+UBO_SCRIPTLET_SIBLINGS = ("urlskip.js", "arglist-parser.js", "jsonpath.js")++# adblock-rust refuses to inject a resource whose permission mask is not a subset of the+# filter's. Filters from untrusted lists carry mask 0, so any non-zero value here means+# "never injected" — which is what we want for uBO's trusted-* scriptlets.+TRUSTED_PERMISSION = 1++# Brave enables this for iOS only; every other default-enabled component applies.+SKIP_LIST_TITLES = {"Brave IOS-Specific Filters"}++# adblock-rust's MimeType::from_extension.+MIME_BY_EXTENSION = {+    ".css": "text/css",+    ".gif": "image/gif",+    ".html": "text/html",+    ".js": "application/javascript",+    ".json": "application/json",+    ".mp3": "audio/mp3",+    ".mp4": "video/mp4",+    ".png": "image/png",+    ".txt": "text/plain",+    ".xml": "text/xml",+}+++def fetch(url: str) -> bytes:+    request = urllib.request.Request(url, headers={"User-Agent": "modern-apps-shields"})+    with urllib.request.urlopen(request, timeout=120) as response:+        return response.read()+++def fetch_text(url: str) -> str:+    return fetch(url).decode("utf-8", errors="replace")+++# ---------------------------------------------------------------------------+# filters.txt+# ---------------------------------------------------------------------------+def default_list_urls() -> list[str]:+    catalog = json.loads(fetch_text(LIST_CATALOG))+    urls = []+    for component in catalog:+        if not component.get("default_enabled"):+            continue+        if component.get("title") in SKIP_LIST_TITLES:+            continue+        for source in component.get("sources", []):+            url = source.get("url")+            if url and url not in urls:+                urls.append(url)+    return urls+++def strip_comments(list_text: str) -> str:+    """Drops comment and metadata lines. `#` alone never starts a filter comment —+    `##selector` is a cosmetic rule — so only `!` and `[Adblock...]` are removed."""+    kept = []+    for line in list_text.splitlines():+        line = line.strip()+        if not line or line.startswith("!"):+            continue+        if line.startswith("[") and line.lower().startswith("[adblock"):+            continue+        kept.append(line)+    return "\n".join(kept)+++def build_filters() -> bytes:+    chunks = []+    for url in default_list_urls():+        print(f"  {url}")+        chunks.append(strip_comments(fetch_text(url)))+    return ("\n".join(chunks) + "\n").encode("utf-8")+++# ---------------------------------------------------------------------------+# resources.json+# ---------------------------------------------------------------------------+MAP_DECLARATION = "export default new Map(["+++def parse_redirect_map(mapfile: str) -> list[dict]:+    """Ports adblock-rust's `read_redirectable_resource_mapping`: coerce the JS+    `Map` literal in redirect-resources.js into JSON and parse it strictly."""+    lines = mapfile.splitlines()+    start = lines.index(MAP_DECLARATION)+    body = []+    for line in lines[start:]:+        if re.match(r"^\s*\]\s*\)", line):+            break+        line = line.split("//")[0]+        line = re.sub(r"\s*/\*[^'\"]*\*/\s*$", "", line)+        body.append(line)++    text = "".join(body)+    text += "]"+    text = text[len(MAP_DECLARATION) - 1 :].replace("'", '"')+    text = "".join(text.split())+    text = re.sub(r",([\],\}])", r"\1", text)+    text = re.sub(r"([\{,])([a-zA-Z][a-zA-Z0-9_]*):", r'\1"\2":', text)++    entries = []+    for name, props in json.loads(text):+        # adblock-rust ignores parameterised resources; they need a JS engine.+        if props.get("params") is not None:+            continue+        alias = props.get("alias")+        if alias is None:+            aliases = []+        elif isinstance(alias, str):+            aliases = [alias]+        else:+            aliases = list(alias)+        entries.append({"name": name, "aliases": aliases})+    return entries+++DUMP_SCRIPTLETS_MJS = """\+import { builtinScriptlets } from './resources/scriptlets.js';+const out = [];+for (const entry of builtinScriptlets) {+    if (typeof entry.fn !== 'function') continue;+    const resource = {+        name: entry.name,+        aliases: entry.aliases ?? [],+        kind: { mime: entry.name.endsWith('.fn') ? 'fn/javascript' : 'application/javascript' },+        content: Buffer.from(entry.fn.toString(), 'utf8').toString('base64'),+        dependencies: entry.dependencies ?? [],+    };+    if (entry.requiresTrust === true) resource.permission = %d;+    out.push(resource);+}+process.stdout.write(JSON.stringify(out));+""" % TRUSTED_PERMISSION+++def build_scriptlets() -> list[dict]:+    """Enumerates uBO's `##+js(...)` scriptlets by importing their ES modules in node.++    Each entry becomes a `Resource` whose content is the raw `function name(...) {...}`+    source; adblock-rust detects the name and calls it with the filter's arguments,+    emitting any `.fn` dependencies alongside it."""+    names = [+        item["name"]+        for item in json.loads(fetch_text(UBO_SCRIPTLET_API))+        if item["type"] == "file"+    ]++    with tempfile.TemporaryDirectory() as tmp:+        root = Path(tmp)+        (root / "resources").mkdir()+        (root / "package.json").write_text('{"type":"module"}')+        (root / "dump.mjs").write_text(DUMP_SCRIPTLETS_MJS)+        for name in names:+            (root / "resources" / name).write_bytes(fetch(f"{UBO_SCRIPTLET_DIR}/{name}"))+        for name in UBO_SCRIPTLET_SIBLINGS:+            (root / name).write_bytes(fetch(f"{UBO}/js/{name}"))++        dumped = subprocess.run(+            ["node", "dump.mjs"],+            cwd=root,+            check=True,+            capture_output=True,+            env={**os.environ, "NODE_OPTIONS": "--no-warnings"},+        ).stdout++    return json.loads(dumped)+++def build_resources() -> bytes:+    print("  redirect-resources.js")+    entries = parse_redirect_map(fetch_text(UBO_REDIRECT_MAP))++    available = {+        item["name"]+        for item in json.loads(fetch_text(UBO_WEB_ACCESSIBLE_API))+        if item["type"] == "file"+    }++    resources = []+    for entry in entries:+        name = entry["name"]+        if name not in available:+            print(f"  ! {name} listed in the map but missing upstream, skipping")+            continue+        raw = fetch(f"{UBO_WEB_ACCESSIBLE}/{name}")+        mime = MIME_BY_EXTENSION.get(Path(name).suffix, "application/octet-stream")+        if mime in ("application/javascript", "text/html", "text/plain"):+            raw = raw.decode("utf-8").replace("\r", "").encode("utf-8")+        resources.append(+            {+                "name": name,+                "aliases": entry["aliases"],+                "kind": {"mime": mime},+                "content": base64.b64encode(raw).decode("ascii"),+            }+        )+    print(f"  {len(resources)} redirect resources")++    scriptlets = build_scriptlets()+    print(f"  {len(scriptlets)} uBO scriptlets")+    resources.extend(scriptlets)++    brave = json.loads(fetch_text(BRAVE_SCRIPTLETS))+    print(f"  {len(brave)} Brave scriptlets")+    resources.extend(brave)++    return json.dumps(resources, separators=(",", ":")).encode("utf-8")+++# ---------------------------------------------------------------------------+def brotli_compress(data: bytes, destination: Path) -> None:+    destination.write_bytes(data)+    subprocess.run(+        ["brotli", "--force", "--quality=11", str(destination)],+        check=True,+    )+    destination.unlink()+++def main() -> int:+    for tool in ("brotli", "node"):+        if shutil.which(tool) is None:+            print(f"{tool} not found on PATH", file=sys.stderr)+            return 1++    ASSET_DIR.mkdir(parents=True, exist_ok=True)++    print("filters:")+    filters = build_filters()+    print("resources:")+    resources = build_resources()++    brotli_compress(filters, ASSET_DIR / "filters.txt")+    brotli_compress(resources, ASSET_DIR / "resources.json")++    digest = hashlib.sha256(filters + resources).hexdigest()+    (ASSET_DIR / "version.txt").write_text(digest + "\n")++    for name in ("filters.txt.br", "resources.json.br", "version.txt"):+        path = ASSET_DIR / name+        print(f"{path.relative_to(REPO_ROOT)}  {path.stat().st_size:,} bytes")+    print(f"raw: filters {len(filters):,}  resources {len(resources):,}")+    return 0+++if __name__ == "__main__":+    sys.exit(main())
web/build.gradle.kts
diff --git a/web/build.gradle.kts b/web/build.gradle.ktsindex 8c38ce9dab..c504d09ff1 100644--- a/web/build.gradle.kts+++ b/web/build.gradle.kts@@ -16,12 +16,23 @@ android {     } } +androidComponents {+    onVariants { variant ->+        val rustDir = layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+        variant.sources.jniLibs?.addStaticSourceDirectory(rustDir)+    }+}++// Brave Shields engine (Rust + adblock-rust). See web/src/main/rust/.+rustNativeLib("web_shields", "shields")+ dependencies {     implementRoom(libs)     implementation(project(":library:room"))     implementation(libs.androidx.webkit)     implementation(libs.androidx.browser)     implementation(libs.androidx.datastore.preferences)+    implementation(libs.brotli.dec) // shields filter lists ship brotli-compressed     implementation(project(":library:image"))     // Browser must allow all certs (any host + corp proxies via user CAs) — SYSTEM permissive, documents intent.     implementation(project(":library:network"))
web/src/main/assets/shields/farble.js
diff --git a/web/src/main/assets/shields/farble.js b/web/src/main/assets/shields/farble.jsnew file mode 100644index 0000000000..3f5176a66c--- /dev/null+++ b/web/src/main/assets/shields/farble.js@@ -0,0 +1,252 @@+// Brave-style fingerprint farbling.+//+// Injected at document start with two globals already defined by the browser:+//   __shieldsSeed        32-bit int, stable per (session, eTLD+1) and different across both+//   __shieldsAggressive  true to also farble timezone and remove WebRTC+//+// The goal is Brave's: make the values a site reads slightly wrong in a way that is+// consistent within the page (so nothing visibly breaks or flickers) but uncorrelated+// across sites and across restarts (so the readings cannot be joined into an identifier).+(function () {+  'use strict';++  var seed = window.__shieldsSeed >>> 0;+  var aggressive = window.__shieldsAggressive === true;+  try {+    delete window.__shieldsSeed;+    delete window.__shieldsAggressive;+  } catch (e) {}++  // mulberry32 — small, fast, and deterministic from the session/origin seed.+  var state = seed;+  function rnd() {+    state |= 0;+    state = (state + 0x6d2b79f5) | 0;+    var t = Math.imul(state ^ (state >>> 15), 1 | state);+    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+  }++  // Farbling must be a pure function of the input, not of how many times it has been+  // called: a page that hashes the same canvas twice has to get the same answer, both+  // because real code does that and because a mismatch would announce that we are here.+  function reseed(extra) {+    state = (seed ^ (extra | 0)) | 0;+  }++  function hashString(s) {+    var h = 0;+    for (var i = 0; i < s.length; i++) h = (Math.imul(h, 31) + s.charCodeAt(i)) | 0;+    return h;+  }++  function define(target, name, value) {+    try {+      Object.defineProperty(target, name, { get: function () { return value; }, configurable: true });+    } catch (e) {}+  }++  function wrap(proto, name, make) {+    try {+      var original = proto[name];+      if (typeof original !== 'function') return;+      var replacement = make(original);+      // Keep toString() looking native so detection scripts do not trip on the wrapper.+      try {+        Object.defineProperty(replacement, 'name', { value: name, configurable: true });+      } catch (e) {}+      replacement.toString = function () { return 'function ' + name + '() { [native code] }'; };+      proto[name] = replacement;+    } catch (e) {}+  }++  // --- Canvas -------------------------------------------------------------+  // Perturb the low bit of a sparse scattering of subpixels. Invisible on screen,+  // but enough to change every hash a canvas fingerprinter computes.+  function farbleImageData(data) {+    reseed(data.length);+    var step = audioAndPixelStep(data.length);+    for (var i = 0; i < data.length; i += step) {+      data[i] = data[i] ^ (rnd() < 0.5 ? 0 : 1);+    }+  }++  function audioAndPixelStep(length) {+    return Math.max(4, ((length / 512) | 0) * 4 || 4);+  }++  wrap(CanvasRenderingContext2D.prototype, 'getImageData', function (original) {+    return function () {+      var result = original.apply(this, arguments);+      try { farbleImageData(result.data); } catch (e) {}+      return result;+    };+  });++  function farbleCanvas(canvas) {+    try {+      var ctx = canvas.getContext('2d');+      if (!ctx || canvas.width === 0 || canvas.height === 0) return;+      var image = ctx.getImageData(0, 0, canvas.width, canvas.height);+      ctx.putImageData(image, 0, 0);+    } catch (e) {}+  }++  wrap(HTMLCanvasElement.prototype, 'toDataURL', function (original) {+    return function () {+      farbleCanvas(this);+      return original.apply(this, arguments);+    };+  });++  wrap(HTMLCanvasElement.prototype, 'toBlob', function (original) {+    return function () {+      farbleCanvas(this);+      return original.apply(this, arguments);+    };+  });++  // --- WebGL --------------------------------------------------------------+  // The GPU strings are the highest-entropy bits available, so report the generic+  // values Brave reports rather than noise, and add noise to pixel readback.+  var UNMASKED_VENDOR = 0x9245;+  var UNMASKED_RENDERER = 0x9246;++  ['WebGLRenderingContext', 'WebGL2RenderingContext'].forEach(function (name) {+    var ctor = window[name];+    if (!ctor) return;+    wrap(ctor.prototype, 'getParameter', function (original) {+      return function (parameter) {+        if (parameter === UNMASKED_VENDOR) return 'Google Inc.';+        if (parameter === UNMASKED_RENDERER) return 'ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device))';+        return original.apply(this, arguments);+      };+    });+    wrap(ctor.prototype, 'readPixels', function (original) {+      return function () {+        var result = original.apply(this, arguments);+        try {+          var pixels = arguments[6];+          if (pixels && pixels.length) farbleImageData(pixels);+        } catch (e) {}+        return result;+      };+    });+    wrap(ctor.prototype, 'getSupportedExtensions', function (original) {+      return function () {+        var extensions = original.apply(this, arguments);+        try {+          // Drop one extension so the reported set is not a stable signature. Chosen from+          // the seed alone so every call in this page returns the same list.+          if (extensions && extensions.length > 1) {+            reseed(extensions.length);+            extensions.splice((rnd() * extensions.length) | 0, 1);+          }+        } catch (e) {}+        return extensions;+      };+    });+  });++  // --- Audio --------------------------------------------------------------+  // A fixed oscillator rendered offline produces an identical buffer on identical+  // hardware; scaling each sample by ~1e-7 defeats the hash without being audible.+  function farbleSamples(samples) {+    reseed(samples.length);+    var step = Math.max(1, (samples.length / 256) | 0);+    for (var i = 0; i < samples.length; i += step) {+      samples[i] = samples[i] * (1 + (rnd() - 0.5) * 1e-6);+    }+  }++  if (window.AnalyserNode) {+    ['getFloatFrequencyData', 'getByteFrequencyData', 'getFloatTimeDomainData'].forEach(function (name) {+      wrap(AnalyserNode.prototype, name, function (original) {+        return function (array) {+          original.apply(this, arguments);+          try { farbleSamples(array); } catch (e) {}+        };+      });+    });+  }++  if (window.AudioBuffer) {+    wrap(AudioBuffer.prototype, 'getChannelData', function (original) {+      return function () {+        var data = original.apply(this, arguments);+        try { farbleSamples(data); } catch (e) {}+        return data;+      };+    });+  }++  // --- Fonts --------------------------------------------------------------+  // Font enumeration works by measuring text width per family. Perturbing by a factor+  // derived from the font and the string keeps every repeat measurement identical while+  // making the set of widths useless for identifying the installed font list.+  if (window.TextMetrics) {+    wrap(CanvasRenderingContext2D.prototype, 'measureText', function (original) {+      return function (text) {+        var metrics = original.apply(this, arguments);+        try {+          reseed(hashString(String(this.font) + '|' + String(text)));+          define(metrics, 'width', metrics.width * (1 + (rnd() - 0.5) * 1e-4));+        } catch (e) {}+        return metrics;+      };+    });+  }++  // --- navigator ----------------------------------------------------------+  // Brave reports a plausible-but-quantised core count and no plugins at all.+  reseed(0);+  define(navigator, 'hardwareConcurrency', 2 + (((rnd() * 3) | 0) * 2));+  define(navigator, 'deviceMemory', [2, 4, 8][(rnd() * 3) | 0]);+  define(navigator, 'languages', Object.freeze(['en-US', 'en']));+  try {+    var emptyPlugins = Object.create(PluginArray.prototype);+    define(emptyPlugins, 'length', 0);+    define(navigator, 'plugins', emptyPlugins);+    var emptyMimeTypes = Object.create(MimeTypeArray.prototype);+    define(emptyMimeTypes, 'length', 0);+    define(navigator, 'mimeTypes', emptyMimeTypes);+  } catch (e) {}++  // --- Aggressive only ----------------------------------------------------+  if (aggressive) {+    // Timezone is stable, high-entropy and rarely load-bearing outside of calendars.+    // Every reader has to agree, otherwise the disagreement is itself a signal: a page+    // that sees resolvedOptions() say UTC but Date say -0700 knows it is being farbled.+    try {+      var DateTimeFormat = Intl.DateTimeFormat;+      var patched = function (locales, options) {+        options = Object.assign({}, options);+        if (!options.timeZone) options.timeZone = 'UTC';+        return new DateTimeFormat(locales, options);+      };+      patched.prototype = DateTimeFormat.prototype;+      patched.supportedLocalesOf = DateTimeFormat.supportedLocalesOf.bind(DateTimeFormat);+      Intl.DateTimeFormat = patched;++      Date.prototype.getTimezoneOffset = function () { return 0; };+      // Re-point every local-time reader at its UTC twin.+      [+        ['getDate', 'getUTCDate'], ['getDay', 'getUTCDay'],+        ['getFullYear', 'getUTCFullYear'], ['getHours', 'getUTCHours'],+        ['getMilliseconds', 'getUTCMilliseconds'], ['getMinutes', 'getUTCMinutes'],+        ['getMonth', 'getUTCMonth'], ['getSeconds', 'getUTCSeconds'],+        ['toString', 'toUTCString'], ['toDateString', 'toUTCString'],+        ['toTimeString', 'toUTCString'], ['toLocaleString', 'toUTCString'],+        ['toLocaleDateString', 'toUTCString'], ['toLocaleTimeString', 'toUTCString'],+      ].forEach(function (pair) {+        var utc = Date.prototype[pair[1]];+        Date.prototype[pair[0]] = function () { return utc.call(this); };+      });+    } catch (e) {}++    // WebRTC leaks local interface addresses even behind a proxy.+    ['RTCPeerConnection', 'webkitRTCPeerConnection', 'RTCDataChannel'].forEach(function (name) {+      try { delete window[name]; } catch (e) {}+    });+  }+})();
web/src/main/assets/shields/filters.txt.br
diff --git a/web/src/main/assets/shields/filters.txt.br b/web/src/main/assets/shields/filters.txt.brnew file mode 100644index 0000000000..82bc322644Binary files /dev/null and b/web/src/main/assets/shields/filters.txt.br differ
web/src/main/assets/shields/resources.json.br
diff --git a/web/src/main/assets/shields/resources.json.br b/web/src/main/assets/shields/resources.json.brnew file mode 100644index 0000000000..9d614de68bBinary files /dev/null and b/web/src/main/assets/shields/resources.json.br differ
web/src/main/assets/shields/version.txt
diff --git a/web/src/main/assets/shields/version.txt b/web/src/main/assets/shields/version.txtnew file mode 100644index 0000000000..68b5031a66--- /dev/null+++ b/web/src/main/assets/shields/version.txt@@ -0,0 +1 @@+b19081f69c1c837dcb187afbdb89e71b6afa14f6bd76333b533d8488a3bfe377
web/src/main/java/com/vayunmathur/web/MainActivity.kt
diff --git a/web/src/main/java/com/vayunmathur/web/MainActivity.kt b/web/src/main/java/com/vayunmathur/web/MainActivity.ktindex 229fc7d143..2bc78f3b21 100644--- a/web/src/main/java/com/vayunmathur/web/MainActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/MainActivity.kt@@ -25,6 +25,7 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.web.data.DB_NAME import com.vayunmathur.web.data.WebDatabase+import com.vayunmathur.web.shields.ShieldsEngine import com.vayunmathur.web.ui.BookmarksPage import com.vayunmathur.web.ui.BrowserPage import com.vayunmathur.web.ui.HistoryPage@@ -49,6 +50,8 @@ class MainActivity : ComponentActivity() {         // SYSTEM permissive browser: any host + user CAs for MITM debug/corp proxies (per user exception)         NetworkClient.init(this, TrustBundle.SYSTEM)         enableEdgeToEdge()+        // Parses ~8 MB of filter lists off the main thread. Shields fail open until it lands.+        lifecycleScope.launch { ShieldsEngine.load(applicationContext) }          // Each task (window) carries its own window id + incognito flag so it keeps an independent tab set.         val windowId = intent?.getStringExtra(EXTRA_WINDOW_ID) ?: WebViewModel.DEFAULT_WINDOW_ID@@ -66,9 +69,11 @@ class MainActivity : ComponentActivity() {                 storageInfoDao = db.storageInfoDao(),                 downloadDao = db.downloadDao(),                 installedSiteDao = db.installedSiteDao(),+                shieldSettingDao = db.shieldSettingDao(),                 context = applicationContext,                 windowId = windowId,                 incognito = incognito,+                initialShieldSettings = db.shieldSettingDao().all(),             )             withContext(Dispatchers.Main) {                 factoryState = factory@@ -193,6 +198,7 @@ sealed interface Route : NavKey {     @Serializable data object Downloads : Route     @Serializable data object SiteData : Route     @Serializable data object InstalledSites : Route+    @Serializable data object Shields : Route }  @Composable@@ -226,5 +232,6 @@ fun Navigation(viewModel: WebViewModel) {         entry<Route.Downloads> { DownloadsPage(viewModel = viewModel, backStack = backStack) }         entry<Route.SiteData> { SiteDataPage(viewModel = viewModel, backStack = backStack) }         entry<Route.InstalledSites> { com.vayunmathur.web.ui.InstalledSitesPage(viewModel = viewModel, backStack = backStack) }+        entry<Route.Shields> { com.vayunmathur.web.ui.ShieldsPage(viewModel = viewModel, backStack = backStack) }     } }
web/src/main/java/com/vayunmathur/web/PwaActivity.kt
diff --git a/web/src/main/java/com/vayunmathur/web/PwaActivity.kt b/web/src/main/java/com/vayunmathur/web/PwaActivity.ktindex f4e619c39c..568a6ca1d1 100644--- a/web/src/main/java/com/vayunmathur/web/PwaActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/PwaActivity.kt@@ -4,7 +4,6 @@ import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager-import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.view.ViewGroup@@ -16,7 +15,6 @@ import android.webkit.WebChromeClient import android.webkit.WebResourceRequest import android.webkit.WebSettings import android.webkit.WebView-import android.webkit.WebViewClient import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult@@ -34,8 +32,15 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat+import androidx.lifecycle.lifecycleScope+import kotlinx.coroutines.launch import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.web.shields.FarblingConfig+import com.vayunmathur.web.shields.ShieldsEngine+import com.vayunmathur.web.shields.ShieldsWebViewClient import com.vayunmathur.web.ui.applySystemDarkMode+import com.vayunmathur.web.util.EffectiveShields+import com.vayunmathur.web.util.ShieldsSettings  class PwaActivity : ComponentActivity() { @@ -50,6 +55,9 @@ class PwaActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()+        // Installed sites get the same shields as the browser; loading is a no-op if the+        // engine is already up in this process.+        lifecycleScope.launch { ShieldsEngine.load(applicationContext) }         handleIntent(intent)         setContent {             DynamicTheme {@@ -242,7 +250,12 @@ private fun PwaBrowser(                         }                     }) -                    webViewClient = object : android.webkit.WebViewClient() {+                    webViewClient = object : ShieldsWebViewClient(+                        context = ctx,+                        // Installed sites have no shields panel, so they always run the+                        // aggressive preset the browser ships with.+                        shieldsFor = { EffectiveShields.resolve(ShieldsSettings.AGGRESSIVE_DEFAULTS) },+                    ) {                         override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {                             val scheme = request.url.scheme ?: return false                             if (scheme !in setOf("http", "https", "about", "data", "blob", "javascript")) {@@ -255,11 +268,7 @@ private fun PwaBrowser(                                 } catch (_: Exception) { false }                             }                             // For PWA: stay inside same origin; external origins still load but that is okay.-                            return false-                        }--                        override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {-                            // no-op+                            return super.shouldOverrideUrlLoading(view, request)                         }                          override fun onPageFinished(view: WebView, url: String?) {@@ -351,6 +360,9 @@ private fun PwaBrowser(                         }                     } +                    // Before the first load: document-start scripts do not apply retroactively.+                    (webViewClient as ShieldsWebViewClient)+                        .installFarbling(this, FarblingConfig.of(ShieldsSettings.AGGRESSIVE_DEFAULTS, emptyMap()))                     loadUrl(initialUrl)                 }.also {                     webViewRef = it
web/src/main/java/com/vayunmathur/web/data/ShieldSetting.kt
diff --git a/web/src/main/java/com/vayunmathur/web/data/ShieldSetting.kt b/web/src/main/java/com/vayunmathur/web/data/ShieldSetting.ktnew file mode 100644index 0000000000..cdc1b47cfb--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/data/ShieldSetting.kt@@ -0,0 +1,42 @@+package com.vayunmathur.web.data++import androidx.room.Entity+import androidx.room.PrimaryKey+import com.vayunmathur.web.util.ShieldLevel+import com.vayunmathur.web.util.ShieldsSettings++/**+ * Per-site shields override, keyed by host. Null fields inherit the global setting, so a+ * site that only turns off cosmetic filtering still tracks later changes to the others.+ * Host is the primary key — shields apply per registrable site, not per origin, matching+ * Brave's own panel. Not a DatabaseItem.+ */+@Entity+data class ShieldSetting(+    @PrimaryKey val host: String,+    val level: String? = null,+    val blockTrackers: Boolean? = null,+    val cosmeticFiltering: Boolean? = null,+    val fingerprintProtection: Boolean? = null,+    val httpsUpgrade: Boolean? = null,+    val updatedAt: Long = System.currentTimeMillis(),+) {+    fun toSettings(): ShieldsSettings = ShieldsSettings(+        level = level?.let { runCatching { ShieldLevel.valueOf(it) }.getOrNull() },+        blockTrackers = blockTrackers,+        cosmeticFiltering = cosmeticFiltering,+        fingerprintProtection = fingerprintProtection,+        httpsUpgrade = httpsUpgrade,+    )++    companion object {+        fun from(host: String, settings: ShieldsSettings) = ShieldSetting(+            host = host,+            level = settings.level?.name,+            blockTrackers = settings.blockTrackers,+            cosmeticFiltering = settings.cosmeticFiltering,+            fingerprintProtection = settings.fingerprintProtection,+            httpsUpgrade = settings.httpsUpgrade,+        )+    }+}
web/src/main/java/com/vayunmathur/web/data/WebDatabase.kt
diff --git a/web/src/main/java/com/vayunmathur/web/data/WebDatabase.kt b/web/src/main/java/com/vayunmathur/web/data/WebDatabase.ktindex 17e159f300..e954d34eaf 100644--- a/web/src/main/java/com/vayunmathur/web/data/WebDatabase.kt+++ b/web/src/main/java/com/vayunmathur/web/data/WebDatabase.kt@@ -149,6 +149,28 @@ interface InstalledSiteDao {     suspend fun clearAll() } +@Dao+interface ShieldSettingDao {+    @Query("SELECT * FROM ShieldSetting ORDER BY host ASC")+    fun allFlow(): Flow<List<ShieldSetting>>++    /** One-shot read so the first page load already knows about site exceptions. */+    @Query("SELECT * FROM ShieldSetting")+    suspend fun all(): List<ShieldSetting>++    @Query("SELECT * FROM ShieldSetting WHERE host = :host LIMIT 1")+    suspend fun byHost(host: String): ShieldSetting?++    @Upsert+    suspend fun upsert(setting: ShieldSetting)++    @Query("DELETE FROM ShieldSetting WHERE host = :host")+    suspend fun deleteHost(host: String)++    @Query("DELETE FROM ShieldSetting")+    suspend fun clearAll()+}+ @Database(     entities = [         HistoryEntry::class,@@ -158,8 +180,9 @@ interface InstalledSiteDao {         StorageInfo::class,         DownloadEntry::class,         InstalledSite::class,+        ShieldSetting::class,     ],-    version = 2,+    version = 3,     exportSchema = false ) abstract class WebDatabase : RoomDatabase() {@@ -169,9 +192,10 @@ abstract class WebDatabase : RoomDatabase() {     abstract fun storageInfoDao(): StorageInfoDao     abstract fun downloadDao(): DownloadDao     abstract fun installedSiteDao(): InstalledSiteDao+    abstract fun shieldSettingDao(): ShieldSettingDao      companion object : DatabaseMigrations {-        override val migrations = listOf(MIGRATION_1_2)+        override val migrations = listOf(MIGRATION_1_2, MIGRATION_2_3)     } } @@ -196,3 +220,20 @@ private val MIGRATION_1_2 = object : Migration(1, 2) {         )     } }++private val MIGRATION_2_3 = object : Migration(2, 3) {+    override fun migrate(db: SupportSQLiteDatabase) {+        db.execSQL(+            """CREATE TABLE IF NOT EXISTS `ShieldSetting` (+                `host` TEXT NOT NULL,+                `level` TEXT,+                `blockTrackers` INTEGER,+                `cosmeticFiltering` INTEGER,+                `fingerprintProtection` INTEGER,+                `httpsUpgrade` INTEGER,+                `updatedAt` INTEGER NOT NULL,+                PRIMARY KEY(`host`)+            )"""+        )+    }+}
web/src/main/java/com/vayunmathur/web/shields/ResourceTypes.kt
diff --git a/web/src/main/java/com/vayunmathur/web/shields/ResourceTypes.kt b/web/src/main/java/com/vayunmathur/web/shields/ResourceTypes.ktnew file mode 100644index 0000000000..10620b65a0--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/shields/ResourceTypes.kt@@ -0,0 +1,111 @@+package com.vayunmathur.web.shields++/**+ * Maps a WebView subresource request onto one of adblock-rust's request types.+ *+ * `WebResourceRequest` carries no resource type, so this reconstructs it the way+ * Chromium would have labelled the request: `Sec-Fetch-Dest` when the WebView sends it,+ * then the `Accept` header, then the URL's file extension. Getting this right matters+ * because a large share of filters are qualified with `$script`, `$image`, `$xhr` etc.+ *+ * Kept free of `android.*` so it can be unit tested on the JVM.+ */+object ResourceTypes {++    /** adblock-rust's fallback bucket, used when nothing more specific is known. */+    const val OTHER = "other"++    private val BY_FETCH_DEST = mapOf(+        "audio" to "media",+        "audioworklet" to "script",+        "document" to "document",+        "embed" to "object",+        "empty" to "xmlhttprequest",+        "font" to "font",+        "frame" to "subdocument",+        "iframe" to "subdocument",+        "image" to "image",+        "manifest" to OTHER,+        "object" to "object",+        "paintworklet" to "script",+        "report" to "other",+        "script" to "script",+        "serviceworker" to "script",+        "sharedworker" to "script",+        "style" to "stylesheet",+        "track" to OTHER,+        "video" to "media",+        "worker" to "script",+        "xslt" to "xlst",+    )++    private val BY_EXTENSION = mapOf(+        "js" to "script",+        "mjs" to "script",+        "css" to "stylesheet",+        "gif" to "image",+        "png" to "image",+        "jpg" to "image",+        "jpeg" to "image",+        "webp" to "image",+        "svg" to "image",+        "ico" to "image",+        "bmp" to "image",+        "avif" to "image",+        "woff" to "font",+        "woff2" to "font",+        "ttf" to "font",+        "otf" to "font",+        "eot" to "font",+        "mp3" to "media",+        "mp4" to "media",+        "webm" to "media",+        "ogg" to "media",+        "m4a" to "media",+        "wav" to "media",+        "m3u8" to "media",+        "json" to "xmlhttprequest",+        "html" to "subdocument",+        "htm" to "subdocument",+    )++    /**+     * @param isMainFrame from `WebResourceRequest.isForMainFrame`+     * @param headers from `WebResourceRequest.requestHeaders`, looked up case-insensitively+     */+    fun of(url: String, isMainFrame: Boolean, headers: Map<String, String>): String {+        if (isMainFrame) return "document"++        header(headers, "Sec-Fetch-Dest")?.lowercase()?.let { dest ->+            BY_FETCH_DEST[dest]?.let { return it }+        }+        fromAccept(header(headers, "Accept"))?.let { return it }+        return BY_EXTENSION[extensionOf(url)] ?: OTHER+    }++    private fun header(headers: Map<String, String>, name: String): String? =+        headers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value++    /**+     * Chromium sends a distinctive `Accept` per destination. `text/html` is deliberately+     * not mapped: navigations already returned above, and an `Accept` of `text/html` on a+     * subresource is the generic default that XHR also sends.+     */+    private fun fromAccept(accept: String?): String? {+        val value = accept?.lowercase() ?: return null+        return when {+            value.startsWith("text/css") -> "stylesheet"+            value.startsWith("image/") -> "image"+            value.startsWith("audio/") || value.startsWith("video/") -> "media"+            value.contains("application/font") || value.contains("font/") -> "font"+            else -> null+        }+    }++    private fun extensionOf(url: String): String {+        val path = url.substringBefore('#').substringBefore('?')+        val lastSegment = path.substringAfterLast('/', "")+        if (!lastSegment.contains('.')) return ""+        return lastSegment.substringAfterLast('.').lowercase()+    }+}
web/src/main/java/com/vayunmathur/web/shields/ShieldsEngine.kt
diff --git a/web/src/main/java/com/vayunmathur/web/shields/ShieldsEngine.kt b/web/src/main/java/com/vayunmathur/web/shields/ShieldsEngine.ktnew file mode 100644index 0000000000..375bee3916--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/shields/ShieldsEngine.kt@@ -0,0 +1,145 @@+package com.vayunmathur.web.shields++import android.content.Context+import android.util.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import org.brotli.dec.BrotliInputStream+import java.io.File++private const val TAG = "ShieldsEngine"+private const val ASSET_DIR = "shields"+private const val CACHE_DIR = "shields"+private const val CACHE_FILE = "engine.dat"+private const val CACHE_VERSION_FILE = "engine.version"++/** Outcome of [ShieldsEngine.check] for one network request. */+@Serializable+data class ShieldsCheck(+    val blocked: Boolean = false,+    val important: Boolean = false,+    val exception: Boolean = false,+    /** `data:` URL holding the uBO resource body named by a `$redirect` rule. */+    val redirect: String? = null,+    /** The URL with `$removeparam` parameters stripped. Only meaningful when not blocked. */+    val rewritten: String? = null,+)++/** Everything needed to prepare a page before it starts loading. */+@Serializable+data class CosmeticResources(+    val hide: List<String> = emptyList(),+    val procedural: List<String> = emptyList(),+    val exceptions: List<String> = emptyList(),+    val script: String = "",+    @SerialName("generichide") val genericHide: Boolean = false,+)++/**+ * Process-wide handle on Brave's adblock engine.+ *+ * Parsing ~8 MB of filter lists takes seconds, so [load] deserializes a cached snapshot+ * whenever the bundled assets have not changed, and only reparses (then rewrites the+ * snapshot) after an asset update.+ *+ * Until [ready] flips true every query returns null and callers must fail open:+ * `shouldInterceptRequest` runs on the render thread and blocking it stalls the page.+ */+object ShieldsEngine {++    @Volatile+    private var handle: Long = 0++    @Volatile+    private var loading = false++    val ready: Boolean get() = handle != 0L++    private val json = Json { ignoreUnknownKeys = true }++    suspend fun load(context: Context) {+        if (ready || loading || !ShieldsNative.isAvailable) return+        loading = true+        try {+            withContext(Dispatchers.IO) {+                val app = context.applicationContext+                val version = app.assets.open("$ASSET_DIR/version.txt").use {+                    it.readBytes().decodeToString().trim()+                }+                val resources = readBrotliAsset(app, "resources.json")+                val cacheDir = File(app.filesDir, CACHE_DIR)+                val cache = File(cacheDir, CACHE_FILE)+                val cachedVersion = File(cacheDir, CACHE_VERSION_FILE)++                var built = 0L+                if (cache.isFile && cachedVersion.isFile && cachedVersion.readText().trim() == version) {+                    built = ShieldsNative.nativeCreateFromCache(cache.readBytes(), resources)+                    if (built == 0L) Log.w(TAG, "engine cache rejected, reparsing lists")+                }+                if (built == 0L) {+                    built = ShieldsNative.nativeCreate(readBrotliAsset(app, "filters.txt"), resources)+                    if (built != 0L) writeCache(cacheDir, cache, cachedVersion, built, version)+                }+                handle = built+            }+        } catch (e: Exception) {+            Log.e(TAG, "load failed — shields stay open", e)+        } finally {+            loading = false+        }+    }++    private fun writeCache(dir: File, cache: File, versionFile: File, handle: Long, version: String) {+        try {+            val snapshot = ShieldsNative.nativeSerialize(handle) ?: return+            dir.mkdirs()+            cache.writeBytes(snapshot)+            versionFile.writeText(version)+        } catch (e: Exception) {+            Log.w(TAG, "could not cache engine snapshot", e)+        }+    }++    private fun readBrotliAsset(context: Context, name: String): String =+        BrotliInputStream(context.assets.open("$ASSET_DIR/$name.br")).use {+            it.readBytes().decodeToString()+        }++    /**+     * Should the request for [url], issued by the page at [sourceUrl], be blocked?+     * Returns null while the engine is still loading, which means "allow".+     */+    fun check(url: String, sourceUrl: String, requestType: String): ShieldsCheck? {+        val h = handle+        if (h == 0L) return null+        val raw = ShieldsNative.nativeCheck(h, url, sourceUrl, requestType) ?: return null+        return runCatching { json.decodeFromString<ShieldsCheck>(raw) }.getOrNull()+    }++    fun cosmetic(url: String): CosmeticResources? {+        val h = handle+        if (h == 0L) return null+        val raw = ShieldsNative.nativeCosmeticResources(h, url) ?: return null+        return runCatching { json.decodeFromString<CosmeticResources>(raw) }.getOrNull()+    }++    /** Generic hide rules matching classes and ids that only appeared after page load. */+    fun hiddenClassIdSelectors(+        classes: List<String>,+        ids: List<String>,+        exceptions: List<String>,+    ): List<String> {+        val h = handle+        if (h == 0L) return emptyList()+        val raw = ShieldsNative.nativeHiddenClassIdSelectors(+            h,+            json.encodeToString(classes),+            json.encodeToString(ids),+            json.encodeToString(exceptions),+        ) ?: return emptyList()+        return runCatching { json.decodeFromString<List<String>>(raw) }.getOrDefault(emptyList())+    }+}
web/src/main/java/com/vayunmathur/web/shields/ShieldsInjection.kt
diff --git a/web/src/main/java/com/vayunmathur/web/shields/ShieldsInjection.kt b/web/src/main/java/com/vayunmathur/web/shields/ShieldsInjection.ktnew file mode 100644index 0000000000..90f87ccce4--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/shields/ShieldsInjection.kt@@ -0,0 +1,203 @@+package com.vayunmathur.web.shields++import android.content.Context+import com.vayunmathur.web.util.EffectiveShields+import com.vayunmathur.web.util.ShieldsSettings++/**+ * Whether to farble, resolved for every site up front.+ *+ * The document-start script runs before anything can tell it what page it is on, so the+ * decision has to travel with it: [enabled]/[aggressive] are the global defaults and+ * [overrides] carries the handful of hosts the user changed.+ */+data class FarblingConfig(+    val enabled: Boolean,+    val aggressive: Boolean,+    val overrides: Map<String, Pair<Boolean?, Boolean?>>,+) {+    fun toJson(): String = buildString {+        append("{\"enabled\":").append(enabled)+        append(",\"aggressive\":").append(aggressive)+        append(",\"overrides\":{")+        overrides.entries.forEachIndexed { index, (host, flags) ->+            if (index > 0) append(',')+            append(ShieldsInjection.jsString(host)).append(":{")+            append("\"enabled\":").append(flags.first?.toString() ?: "null")+            append(",\"aggressive\":").append(flags.second?.toString() ?: "null")+            append('}')+        }+        append("}}")+    }++    companion object {+        /** Builds the config from the global defaults plus every per-site record. */+        fun of(global: ShieldsSettings, sites: Map<String, ShieldsSettings>): FarblingConfig {+            val effective = EffectiveShields.resolve(global)+            return FarblingConfig(+                enabled = effective.fingerprintProtection,+                aggressive = effective.aggressiveFingerprinting,+                overrides = sites.mapValues { (_, site) ->+                    val resolved = EffectiveShields.resolve(global, site)+                    resolved.fingerprintProtection to resolved.aggressiveFingerprinting+                },+            )+        }+    }+}++/**+ * Builds the JavaScript that shields inject into every page.+ *+ * Two things have to happen before the page's own scripts run: fingerprint farbling+ * (useless afterwards, since a script could have already read the true values) and the+ * cosmetic stylesheet (otherwise ad slots flash before being hidden). Both are packed+ * into a single document-start script.+ */+internal object ShieldsInjection {++    /** Name of the object [ShieldsWebViewClient] exposes for the second cosmetic pass. */+    const val COSMETIC_CHANNEL = "shieldsCosmetic"++    private const val FARBLE_ASSET = "shields/farble.js"++    @Volatile+    private var farbleSource: String? = null++    private fun farble(context: Context): String =+        farbleSource ?: synchronized(this) {+            farbleSource ?: context.applicationContext.assets+                .open(FARBLE_ASSET)+                .use { it.readBytes().decodeToString() }+                .also { farbleSource = it }+        }++    /**+     * The fingerprinting payload, registered once per WebView at creation.+     *+     * This has to be a document-start script and it has to be registered *before* the+     * navigation: `addDocumentStartJavaScript` only affects documents that start loading+     * after the call, so registering it from `onPageStarted` would leave the very first+     * page unprotected. That rules out baking the current URL into it, so the script+     * decides per origin at runtime from [config] and derives its own seed.+     */+    fun farbling(context: Context, config: FarblingConfig, sessionSalt: Int): String = buildString {+        append("(function(){")+        append("if(window.__shieldsFarbled)return;")+        append("var host=location.hostname||'';")+        append("var cfg=").append(config.toJson()).append(";")+        append("var o=cfg.overrides[host];")+        append("var on=(o&&typeof o.enabled==='boolean')?o.enabled:cfg.enabled;")+        append("if(!on)return;")+        append("window.__shieldsFarbled=true;")+        append("var agg=(o&&typeof o.aggressive==='boolean')?o.aggressive:cfg.aggressive;")+        // Seed = session salt mixed with the hostname, so it is stable for this site in+        // this session and unrelated to any other site or run.+        append("var h=").append(sessionSalt).append("|0;")+        append("for(var i=0;i<host.length;i++){h=(h*31+host.charCodeAt(i))|0;}")+        append("window.__shieldsSeed=h>>>0;window.__shieldsAggressive=agg;")+        append("try{").append(farble(context)).append("}catch(e){}")+        append("})();")+    }++    /**+     * The per-page cosmetic payload. Unlike farbling this depends on the URL, so it is+     * applied once the navigation is known; arriving a few milliseconds late only means a+     * hidden element may flash, never that protection is lost.+     */+    fun cosmetic(resources: CosmeticResources?): String {+        if (resources == null) return ""+        return buildString {+            append("(function(){if(window.__shieldsCosmetic)return;window.__shieldsCosmetic=true;")+            if (resources.hide.isNotEmpty()) {+                append("try{").append(hideCss(resources.hide)).append("}catch(e){}")+            }+            if (resources.script.isNotEmpty()) {+                append("try{").append(resources.script).append("}catch(e){}")+            }+            if (!resources.genericHide) {+                append("try{").append(observer(resources.exceptions)).append("}catch(e){}")+            }+            append("})();")+        }+    }++    /**+     * Injects `selectors { display: none !important }` as a stylesheet.+     *+     * Split into chunks because a single rule with tens of thousands of selectors is slow+     * to match and some engines cap selector-list length.+     */+    fun hideCss(selectors: List<String>): String {+        if (selectors.isEmpty()) return ""+        val rules = selectors.chunked(SELECTORS_PER_RULE).joinToString("\n") {+            it.joinToString(",") + "{display:none !important;}"+        }+        return buildString {+            append("(function(){var s=document.getElementById('__shields_css__');")+            append("if(!s){s=document.createElement('style');s.id='__shields_css__';")+            append("(document.head||document.documentElement).appendChild(s);}")+            append("s.appendChild(document.createTextNode(").append(jsString(rules)).append("));})();")+        }+    }++    private const val SELECTORS_PER_RULE = 128++    /**+     * Brave's second cosmetic pass: generic hide rules are far too numerous to inject+     * wholesale, so the page reports the classes and ids it actually uses and the engine+     * replies with only the rules that could match.+     */+    private fun observer(exceptions: List<String>): String = buildString {+        append("(function(){var ch=window.").append(COSMETIC_CHANNEL).append(";if(!ch)return;")+        append("var seenC={},seenI={},pending=false;")+        append("var exc=").append(jsonArray(exceptions)).append(";")+        append("function collect(root){")+        append("if(!root||root.nodeType!==1)return;")+        append("var all=root.querySelectorAll?root.querySelectorAll('[class],[id]'):[];")+        append("var nodes=[root];for(var i=0;i<all.length;i++)nodes.push(all[i]);")+        append("for(var n=0;n<nodes.length;n++){var el=nodes[n];")+        append("if(el.id&&!seenI[el.id])seenI[el.id]=1;")+        append("var cl=el.classList;if(cl)for(var c=0;c<cl.length;c++){if(!seenC[cl[c]])seenC[cl[c]]=1;}}")+        append("schedule();}")+        append("function schedule(){if(pending)return;pending=true;")+        // Batch a frame's worth of mutations into one JNI round trip.+        append("(window.requestIdleCallback||window.setTimeout)(function(){pending=false;")+        append("var c=Object.keys(seenC),i=Object.keys(seenI);seenC={};seenI={};")+        append("if(c.length||i.length)ch.postMessage(JSON.stringify({classes:c,ids:i,exceptions:exc}));")+        append("},1);}")+        append("ch.onmessage=function(e){try{var sel=JSON.parse(e.data);")+        append("if(sel.length)applyHide(sel);}catch(err){}};")+        append("function applyHide(sel){var s=document.getElementById('__shields_css2__');")+        append("if(!s){s=document.createElement('style');s.id='__shields_css2__';")+        append("(document.head||document.documentElement).appendChild(s);}")+        append("s.appendChild(document.createTextNode(sel.join(',')+'{display:none !important;}'));}")+        append("collect(document.documentElement);")+        append("new MutationObserver(function(muts){for(var m=0;m<muts.length;m++){")+        append("var added=muts[m].addedNodes;for(var a=0;a<added.length;a++)collect(added[a]);")+        append("if(muts[m].type==='attributes')collect(muts[m].target);}})")+        append(".observe(document.documentElement,{childList:true,subtree:true,")+        append("attributes:true,attributeFilter:['class','id']});})();")+    }++    private fun jsonArray(values: List<String>): String =+        values.joinToString(",", "[", "]") { jsString(it) }++    /** JS string literal. `<` is escaped so the payload survives being parsed inside a page. */+    internal fun jsString(value: String): String = buildString {+        append('"')+        for (c in value) {+            when (c) {+                '"' -> append("\\\"")+                '\\' -> append("\\\\")+                '\n' -> append("\\n")+                '\r' -> append("\\r")+                '\u2028' -> append("\\u2028")+                '\u2029' -> append("\\u2029")+                '<' -> append("\\u003c")+                else -> append(c)+            }+        }+        append('"')+    }+}
web/src/main/java/com/vayunmathur/web/shields/ShieldsNative.kt
diff --git a/web/src/main/java/com/vayunmathur/web/shields/ShieldsNative.kt b/web/src/main/java/com/vayunmathur/web/shields/ShieldsNative.ktnew file mode 100644index 0000000000..a25bbc8498--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/shields/ShieldsNative.kt@@ -0,0 +1,47 @@+package com.vayunmathur.web.shields++/**+ * JNI bridge to Brave's adblock engine (`libweb_shields.so`, built from+ * `web/src/main/rust/`). [isAvailable] is false when the native lib is missing for the+ * current ABI, which makes [ShieldsEngine] fail open rather than break every page.+ *+ * Handles are opaque; 0 means "no engine". Every call is safe to make from any thread —+ * the Rust `Engine` is `Send + Sync` — but they are all blocking, so only [nativeCheck]+ * belongs on the WebView render thread.+ */+internal object ShieldsNative {++    val isAvailable: Boolean =+        try {+            System.loadLibrary("web_shields")+            true+        } catch (t: Throwable) {+            android.util.Log.e("ShieldsNative", "System.loadLibrary(web_shields) failed", t)+            false+        }++    /** Parses `filters` (Adblock Plus syntax) and returns an engine handle, or 0. */+    external fun nativeCreate(filters: String, resourcesJson: String): Long++    /** Restores an engine from [nativeSerialize] output. Returns 0 if the format changed. */+    external fun nativeCreateFromCache(cache: ByteArray, resourcesJson: String): Long++    /** Snapshot of the parsed filter data, for [nativeCreateFromCache]. */+    external fun nativeSerialize(handle: Long): ByteArray?++    /** `{"blocked","important","exception","redirect","rewritten"}` — see [ShieldsCheck]. */+    external fun nativeCheck(handle: Long, url: String, sourceUrl: String, requestType: String): String?++    /** `{"hide","procedural","exceptions","script","generichide"}` — see [CosmeticResources]. */+    external fun nativeCosmeticResources(handle: Long, url: String): String?++    /** JSON array of extra hide selectors for classes/ids that appeared after load. */+    external fun nativeHiddenClassIdSelectors(+        handle: Long,+        classesJson: String,+        idsJson: String,+        exceptionsJson: String,+    ): String?++    external fun nativeDestroy(handle: Long)+}
web/src/main/java/com/vayunmathur/web/shields/ShieldsWebViewClient.kt
diff --git a/web/src/main/java/com/vayunmathur/web/shields/ShieldsWebViewClient.kt b/web/src/main/java/com/vayunmathur/web/shields/ShieldsWebViewClient.ktnew file mode 100644index 0000000000..3230c1cd97--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/shields/ShieldsWebViewClient.kt@@ -0,0 +1,240 @@+package com.vayunmathur.web.shields++import android.content.Context+import android.graphics.Bitmap+import android.net.Uri+import android.util.Log+import android.webkit.WebResourceRequest+import android.webkit.WebResourceResponse+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.webkit.JavaScriptReplyProxy+import androidx.webkit.ScriptHandler+import androidx.webkit.WebMessageCompat+import androidx.webkit.WebViewCompat+import androidx.webkit.WebViewFeature+import com.vayunmathur.web.util.EffectiveShields+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.io.ByteArrayInputStream+import java.util.Base64+import kotlin.random.Random++private const val TAG = "ShieldsWebViewClient"++/** Empty bodies returned for blocked requests, by resource type. */+private val EMPTY_GIF: ByteArray = Base64.getDecoder()+    .decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")++@Serializable+private data class CosmeticQuery(+    val classes: List<String> = emptyList(),+    val ids: List<String> = emptyList(),+    val exceptions: List<String> = emptyList(),+)++/**+ * A [WebViewClient] that applies Brave Shields.+ *+ * Subclasses add the host's own navigation and title plumbing; everything shields-related+ * lives here so `WebViewBrowser` and `PwaActivity` cannot drift apart. Subclasses that+ * override [onPageStarted] or [shouldOverrideUrlLoading] **must** call through to super.+ *+ * @param shieldsFor resolved shields for a host, consulted per request+ * @param onBlocked  called on the render thread each time a request is blocked+ * @param onNavigate asks the host to load a URL shields rewrote (HTTPS upgrade, param strip)+ */+open class ShieldsWebViewClient(+    private val context: Context,+    private val shieldsFor: (host: String) -> EffectiveShields,+    private val onBlocked: (pageUrl: String, blockedUrl: String) -> Unit = { _, _ -> },+    private val onNavigate: (WebView, String) -> Unit = { view, url -> view.loadUrl(url) },+) : WebViewClient() {++    /**+     * The document the current subresources belong to. `WebResourceRequest` has no+     * initiator, so first-party detection depends entirely on tracking this.+     */+    @Volatile+    private var pageUrl: String = ""++    /** Per-session salt; combined with the site's host it gives Brave's per-origin seed. */+    private val sessionSalt: Int = Random.nextInt()++    private val json = Json { ignoreUnknownKeys = true }++    /** URLs this client already rewrote, so the reload does not bounce forever. */+    private var lastRewritten: String? = null++    private var cosmeticChannelInstalled = false+    private var farbleHandle: ScriptHandler? = null+    private var installedFarbling: String? = null++    /**+     * Installs the fingerprinting defence on [view].+     *+     * Must be called before the first `loadUrl`: `addDocumentStartJavaScript` only applies+     * to documents that begin loading after registration, and farbling is worthless once+     * the page has read the real values. Re-registering after a settings change is cheap+     * — the previous script handle is removed first.+     */+    fun installFarbling(view: WebView, config: FarblingConfig) {+        if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) return+        val script = ShieldsInjection.farbling(context, config, sessionSalt)+        if (script == installedFarbling) return+        runCatching {+            farbleHandle?.remove()+            farbleHandle = WebViewCompat.addDocumentStartJavaScript(view, script, setOf("*"))+            installedFarbling = script+        }.onFailure { Log.w(TAG, "farbling script rejected", it) }+    }++    // ---------------------------------------------------------------- network++    override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {+        val url = request.url.toString()+        val scheme = request.url.scheme?.lowercase()+        if (scheme != "http" && scheme != "https") return null++        if (request.isForMainFrame) {+            pageUrl = url+            return null+        }++        val source = pageUrl.ifEmpty { url }+        val shields = shieldsFor(hostOf(source))+        if (!shields.blockTrackers) return null++        val type = ResourceTypes.of(url, isMainFrame = false, headers = request.requestHeaders)+        val result = ShieldsEngine.check(url, source, type) ?: return null+        if (!result.blocked) return null++        onBlocked(source, url)+        return result.redirect?.let { dataUrlResponse(it) } ?: emptyResponse(type)+    }++    /**+     * An empty 200 rather than a failure: a blocked script that 404s can send a page down+     * an error path, whereas an empty body usually just no-ops. The content type has to+     * match what the element expected or the browser logs a MIME error and, for images,+     * shows a broken-image placeholder.+     */+    private fun emptyResponse(type: String): WebResourceResponse {+        val (mime, body) = when (type) {+            "image" -> "image/gif" to EMPTY_GIF+            "script" -> "application/javascript" to ByteArray(0)+            "stylesheet" -> "text/css" to ByteArray(0)+            "media" -> "video/mp4" to ByteArray(0)+            "xmlhttprequest" -> "application/json" to ByteArray(0)+            "subdocument" -> "text/html" to ByteArray(0)+            else -> "text/plain" to ByteArray(0)+        }+        return WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(body))+    }++    /** Serves the body of a `$redirect` rule, which the engine hands back as a data URL. */+    private fun dataUrlResponse(dataUrl: String): WebResourceResponse? = try {+        val header = dataUrl.substringBefore(',', "")+        val payload = dataUrl.substringAfter(',', "")+        val mime = header.removePrefix("data:").substringBefore(';').ifEmpty { "text/plain" }+        val bytes = if (header.endsWith(";base64")) {+            Base64.getDecoder().decode(payload)+        } else {+            Uri.decode(payload).toByteArray()+        }+        WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(bytes))+    } catch (e: Exception) {+        Log.w(TAG, "malformed redirect resource", e)+        null+    }++    // ------------------------------------------------------------- navigation++    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {+        if (!request.isForMainFrame) return false+        val url = request.url.toString()+        val rewritten = rewrite(url, shieldsFor(hostOf(url)))+        if (rewritten != null && rewritten != url) {+            lastRewritten = rewritten+            onNavigate(view, rewritten)+            return true+        }+        return false+    }++    /**+     * The HTTPS upgrade and parameter strip Brave applies to top-level navigations.+     * Returns null when the URL is already clean.+     */+    private fun rewrite(url: String, shields: EffectiveShields): String? {+        if (url == lastRewritten) return null+        var result = url+        if (shields.httpsUpgrade) {+            UrlCleaner.httpsUpgrade(result)?.let { result = it }+        }+        if (shields.blockTrackers) {+            result = UrlCleaner.clean(result)+        }+        return if (result == url) null else result+    }++    override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {+        super.onPageStarted(view, url, favicon)+        url ?: return+        pageUrl = url+        if (url == lastRewritten) lastRewritten = null+        applyShields(view, url)+    }++    // -------------------------------------------------------------- injection++    /**+     * Applies the cosmetic payload for the document that just started loading.+     *+     * Farbling is not done here — see [installFarbling]. Hide rules are URL-specific and+     * only cosmetic, so evaluating them at page start is soon enough.+     */+    private fun applyShields(view: WebView, url: String) {+        if (!url.startsWith("http")) return+        val shields = shieldsFor(hostOf(url))+        if (!shields.cosmeticFiltering) return++        installCosmeticChannel(view)+        val script = ShieldsInjection.cosmetic(ShieldsEngine.cosmetic(url))+        if (script.isNotEmpty()) view.evaluateJavascript(script, null)+    }++    /**+     * Wires the page's `MutationObserver` to [ShieldsEngine.hiddenClassIdSelectors] so+     * generic hide rules can be resolved for classes and ids that appear after load.+     */+    private fun installCosmeticChannel(view: WebView) {+        if (cosmeticChannelInstalled) return+        if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return+        runCatching {+            WebViewCompat.addWebMessageListener(+                view,+                ShieldsInjection.COSMETIC_CHANNEL,+                setOf("*"),+                { _, message, _, isMainFrame, reply -> onCosmeticQuery(message, isMainFrame, reply) },+            )+            cosmeticChannelInstalled = true+        }.onFailure { Log.w(TAG, "cosmetic channel unavailable", it) }+    }++    private fun onCosmeticQuery(+        message: WebMessageCompat,+        isMainFrame: Boolean,+        reply: JavaScriptReplyProxy,+    ) {+        if (!isMainFrame) return+        val raw = message.data ?: return+        val query = runCatching { json.decodeFromString<CosmeticQuery>(raw) }.getOrNull() ?: return+        val selectors = ShieldsEngine.hiddenClassIdSelectors(query.classes, query.ids, query.exceptions)+        if (selectors.isEmpty()) return+        runCatching { reply.postMessage(json.encodeToString(selectors)) }+    }++    private fun hostOf(url: String): String =+        runCatching { Uri.parse(url).host.orEmpty() }.getOrDefault("")+}
web/src/main/java/com/vayunmathur/web/shields/UrlCleaner.kt
diff --git a/web/src/main/java/com/vayunmathur/web/shields/UrlCleaner.kt b/web/src/main/java/com/vayunmathur/web/shields/UrlCleaner.ktnew file mode 100644index 0000000000..661bf2e1d8--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/shields/UrlCleaner.kt@@ -0,0 +1,93 @@+package com.vayunmathur.web.shields++/**+ * Brave's query-parameter stripping and HTTPS upgrading for top-level navigations.+ *+ * The engine's own `$removeparam` rules cover most tracking parameters, but they only+ * apply to requests it inspects. Brave additionally strips a fixed list on every+ * navigation, which is what this reproduces — it catches links pasted into the omnibox+ * and cross-site redirects that never reach a subresource check.+ *+ * Pure Kotlin (no `android.net.Uri`) so it runs in JVM unit tests.+ */+object UrlCleaner {++    /**+     * Exact parameter names Brave removes. Kept in sync with `brave-core`'s+     * `query_filter.cc` tracking-parameter list.+     */+    private val TRACKING_PARAMS = setOf(+        "fbclid", "gclid", "gclsrc", "dclid", "msclkid", "mc_eid", "mkt_tok",+        "igshid", "igsh", "twclid", "yclid", "ttclid", "rb_clickid", "s_cid",+        "wickedid", "oly_anon_id", "oly_enc_id", "vero_conv", "vero_id",+        "_hsenc", "_hsmi", "__hssc", "__hstc", "hsCtaTracking", "__s",+        "_openstat", "wt_zmc", "guccounter", "guce_referrer", "guce_referrer_sig",+        "cmpid", "os_ehash", "pk_campaign", "pk_kwd", "piwik_campaign", "piwik_kwd",+        "spm", "scm", "share_source", "share_medium", "share_plat", "share_tag",+        "share_session_id", "share_from", "unique_k", "vd_source",+    )++    /** Prefixes covering whole families: `utm_*`, `ga_*`, `hsa_*`, `matomo_*`. */+    private val TRACKING_PREFIXES = listOf("utm_", "ga_", "hsa_", "matomo_")++    private fun isTracking(name: String): Boolean {+        val lower = name.lowercase()+        return lower in TRACKING_PARAMS || TRACKING_PREFIXES.any { lower.startsWith(it) }+    }++    /**+     * Removes tracking parameters from [url], preserving parameter order, repeated keys+     * and the fragment. Returns [url] unchanged when there is nothing to strip, so callers+     * can compare by identity to decide whether a reload is warranted.+     */+    fun clean(url: String): String {+        val queryStart = url.indexOf('?')+        if (queryStart < 0) return url++        val fragmentStart = url.indexOf('#', queryStart)+        val query = if (fragmentStart < 0) {+            url.substring(queryStart + 1)+        } else {+            url.substring(queryStart + 1, fragmentStart)+        }+        if (query.isEmpty()) return url++        val kept = query.split('&').filter { param ->+            param.isNotEmpty() && !isTracking(param.substringBefore('='))+        }+        if (kept.size == query.split('&').count { it.isNotEmpty() }) return url++        val prefix = url.substring(0, queryStart)+        val fragment = if (fragmentStart < 0) "" else url.substring(fragmentStart)+        return if (kept.isEmpty()) prefix + fragment else "$prefix?${kept.joinToString("&")}$fragment"+    }++    /**+     * The `https://` form of an `http://` [url], or null when it is already secure or is+     * an address HTTPS cannot serve.+     *+     * localhost and bare IPs are left alone: they have no publicly trusted certificate and+     * upgrading them breaks local development servers, which is also Brave's behaviour.+     */+    fun httpsUpgrade(url: String): String? {+        if (!url.startsWith("http://", ignoreCase = true)) return null+        val host = hostOf(url)+        if (host.isEmpty() || host == "localhost" || host.endsWith(".localhost")) return null+        if (isIpLiteral(host)) return null+        return "https://" + url.substring("http://".length)+    }++    private fun hostOf(url: String): String {+        val afterScheme = url.substringAfter("://", "")+        val authority = afterScheme.substringBefore('/').substringBefore('?').substringBefore('#')+        return authority.substringAfter('@').substringBefore(':').lowercase()+    }++    private fun isIpLiteral(host: String): Boolean {+        if (host.startsWith("[")) return true // IPv6+        val octets = host.split('.')+        return octets.size == 4 && octets.all { part ->+            part.isNotEmpty() && part.all { it.isDigit() } && part.toInt() <= 255+        }+    }+}
web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.ktindex 7d7111b69b..ac0af14127 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt@@ -75,8 +75,10 @@ import com.vayunmathur.library.ui.IconBack import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconMoreVert import com.vayunmathur.library.ui.IconSearch+import com.vayunmathur.library.ui.IconShield import com.vayunmathur.web.Route import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.web.shields.ShieldsWebViewClient import com.vayunmathur.web.util.BrowserUtils import com.vayunmathur.web.util.PwaHelper import com.vayunmathur.web.util.PwaInfo@@ -108,6 +110,11 @@ fun BrowserPage(     val history by viewModel.history.collectAsStateWithLifecycle()     val isCurrentBookmarked = activeTab?.url?.let { url -> url.isNotBlank() && bookmarks.any { it.url == url } } ?: false +    val shieldHost = activeTab?.url?.takeIf { it.startsWith("http") }?.let { BrowserUtils.hostFromUrl(it) }+    // Navigating away from the site the panel describes has to close it, otherwise it would+    // silently start editing a different host's settings.+    LaunchedEffect(shieldHost) { viewModel.showShieldsPanel = false }+     val multiDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->         viewModel.deliverFileChooserResult(uris.toTypedArray().takeIf { it.isNotEmpty() })     }@@ -312,6 +319,9 @@ fun BrowserPage(                     viewModel.omniboxFocused = true                 },                 onTabSwitcherClick = { viewModel.showTabSwitcher = true },+                shieldHost = shieldHost,+                blockedCount = activeTab?.let { viewModel.blockedCount(it.id) } ?: 0,+                onShieldClick = { viewModel.showShieldsPanel = true },                 onMenuClick = { showMenu = true },                 menu = {                     DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {@@ -426,6 +436,26 @@ fun BrowserPage(             )         } +        if (viewModel.showShieldsPanel && shieldHost != null) {+            ShieldsPanel(+                host = shieldHost,+                blockedCount = activeTab?.let { viewModel.blockedCount(it.id) } ?: 0,+                viewModel = viewModel,+                onReload = {+                    activeTab?.let { tab ->+                        webViewPool[tab.id]?.let { webView ->+                            // Re-register before reloading, not after: document-start scripts+                            // only apply to documents that start loading after the call.+                            (webView.webViewClient as? ShieldsWebViewClient)+                                ?.installFarbling(webView, viewModel.farblingConfig())+                            webView.reload()+                        }+                    }+                },+                onDismiss = { viewModel.showShieldsPanel = false },+            )+        }+         viewModel.pendingPermissionPrompt?.let { prompt ->             PermissionPromptSheet(                 origin = prompt.origin,@@ -551,6 +581,9 @@ fun BrowserChrome(     onForward: () -> Unit = {},     onOmniboxClick: () -> Unit = {},     onTabSwitcherClick: () -> Unit = {},+    shieldHost: String? = null,+    blockedCount: Int = 0,+    onShieldClick: () -> Unit = {},     onMenuClick: () -> Unit = {},     menu: @Composable () -> Unit = {},     content: @Composable (PaddingValues) -> Unit,@@ -573,6 +606,10 @@ fun BrowserChrome(                         )                     },                     actions = {+                        if (shieldHost != null) {+                            ShieldChip(blockedCount = blockedCount, onClick = onShieldClick)+                            Spacer(Modifier.width(4.dp))+                        }                         Surface(                             shape = RoundedCornerShape(20.dp),                             color = MaterialTheme.colorScheme.secondaryContainer,@@ -601,6 +638,30 @@ fun BrowserChrome(     ) } +/**+ * Toolbar shield. Shows the number of requests blocked on the current page, which is the+ * only feedback the user gets that shields are doing anything.+ */+@Composable+private fun ShieldChip(blockedCount: Int, onClick: () -> Unit) {+    Surface(+        shape = RoundedCornerShape(20.dp),+        color = MaterialTheme.colorScheme.secondaryContainer,+        modifier = Modifier.clip(RoundedCornerShape(20.dp)).clickable(onClick = onClick),+    ) {+        Row(+            Modifier.padding(horizontal = 10.dp, vertical = 8.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            IconShield(Modifier.size(18.dp))+            if (blockedCount > 0) {+                Spacer(Modifier.width(4.dp))+                Text(blockedCount.toString(), style = MaterialTheme.typography.labelLarge)+            }+        }+    }+}+ @Composable private fun DisplayOnlyAddressPill(     fullUrl: String,
web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt b/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.ktindex 0307b7bd8d..d1f1393e91 100644--- a/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt@@ -123,8 +123,19 @@ fun SettingsPage(              item {                 ListItem(-                    headlineContent = { Text(stringResource(R.string.ad_tracker_blocking)) },-                    supportingContent = { Text(stringResource(R.string.blocks_doubleclick_googletagmanager_anal) + " — Always on") }+                    headlineContent = { Text(stringResource(R.string.shields)) },+                    supportingContent = {+                        Text(+                            stringResource(+                                when (viewModel.shields.level) {+                                    com.vayunmathur.web.util.ShieldLevel.OFF -> R.string.shields_level_off_desc+                                    com.vayunmathur.web.util.ShieldLevel.STANDARD -> R.string.shields_level_standard_desc+                                    else -> R.string.shields_level_aggressive_desc+                                }+                            )+                        )+                    },+                    modifier = Modifier.clickable { backStack.add(Route.Shields) }                 )             } 
web/src/main/java/com/vayunmathur/web/ui/ShieldsPanel.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/ShieldsPanel.kt b/web/src/main/java/com/vayunmathur/web/ui/ShieldsPanel.ktnew file mode 100644index 0000000000..4bbead5d3b--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/ShieldsPanel.kt@@ -0,0 +1,300 @@+package com.vayunmathur.web.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalBottomSheet+import com.vayunmathur.library.ui.RadioButton+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.web.R+import com.vayunmathur.web.Route+import com.vayunmathur.web.util.EffectiveShields+import com.vayunmathur.web.util.ShieldLevel+import com.vayunmathur.web.util.ShieldsSettings+import com.vayunmathur.web.util.WebViewModel++/**+ * Brave's shields panel: the shield in the toolbar opens this for the current site.+ *+ * Changes are stored per host and take effect for new requests immediately, but the page+ * already rendered keeps whatever was injected into it, hence the reload affordance.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ShieldsPanel(+    host: String,+    blockedCount: Int,+    viewModel: WebViewModel,+    onReload: () -> Unit,+    onDismiss: () -> Unit,+) {+    // Read through the Room-backed flow, not the render-thread mirror, so the panel+    // recomposes as soon as a change lands.+    val overrides by viewModel.shieldSettings.collectAsStateWithLifecycle()+    val site = overrides.firstOrNull { it.host == host }?.toSettings()+    val effective = EffectiveShields.resolve(viewModel.shields, site)++    fun update(transform: (ShieldsSettings) -> ShieldsSettings) {+        viewModel.updateSiteShields(host, transform(site ?: ShieldsSettings()))+    }++    ModalBottomSheet(onDismissRequest = onDismiss) {+        Column(+            Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp),+            verticalArrangement = Arrangement.spacedBy(0.dp),+        ) {+            Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) {+                Text(stringResource(R.string.shields_for_host, host), style = MaterialTheme.typography.titleMedium)+                Text(+                    if (effective.level == ShieldLevel.OFF) {+                        stringResource(R.string.shields_down)+                    } else {+                        stringResource(R.string.shields_blocked_count, blockedCount)+                    },+                    style = MaterialTheme.typography.bodySmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }++            HorizontalDivider(Modifier.padding(vertical = 8.dp))++            ShieldLevel.entries.forEach { level ->+                Row(+                    Modifier+                        .fillMaxWidth()+                        .clickable { update { it.copy(level = level) } }+                        .padding(horizontal = 24.dp, vertical = 8.dp),+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    RadioButton(+                        selected = effective.level == level,+                        onClick = { update { it.copy(level = level) } },+                    )+                    Spacer(Modifier.width(12.dp))+                    Column {+                        Text(stringResource(level.titleRes), style = MaterialTheme.typography.bodyMedium)+                        Text(+                            stringResource(level.descriptionRes),+                            style = MaterialTheme.typography.bodySmall,+                            color = MaterialTheme.colorScheme.onSurfaceVariant,+                        )+                    }+                }+            }++            if (effective.level != ShieldLevel.OFF) {+                HorizontalDivider(Modifier.padding(vertical = 8.dp))+                ShieldToggle(+                    R.string.shields_block_trackers,+                    R.string.shields_block_trackers_desc,+                    effective.blockTrackers,+                ) { on -> update { it.copy(blockTrackers = on) } }+                ShieldToggle(+                    R.string.shields_cosmetic,+                    R.string.shields_cosmetic_desc,+                    effective.cosmeticFiltering,+                ) { on -> update { it.copy(cosmeticFiltering = on) } }+                ShieldToggle(+                    R.string.shields_fingerprint,+                    R.string.shields_fingerprint_desc,+                    effective.fingerprintProtection,+                ) { on -> update { it.copy(fingerprintProtection = on) } }+                ShieldToggle(+                    R.string.shields_https,+                    R.string.shields_https_desc,+                    effective.httpsUpgrade,+                ) { on -> update { it.copy(httpsUpgrade = on) } }+            }++            HorizontalDivider(Modifier.padding(vertical = 8.dp))+            Row(+                Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                horizontalArrangement = Arrangement.SpaceBetween,+            ) {+                TextButton(onClick = { viewModel.updateSiteShields(host, ShieldsSettings()) }) {+                    Text(stringResource(R.string.shields_reset_site))+                }+                TextButton(onClick = { onReload(); onDismiss() }) {+                    Text(stringResource(R.string.shields_reload_to_apply))+                }+            }+        }+    }+}++@Composable+private fun ShieldToggle(+    titleRes: Int,+    descriptionRes: Int,+    checked: Boolean,+    onCheckedChange: (Boolean) -> Unit,+) {+    ListItem(+        headlineContent = { Text(stringResource(titleRes)) },+        supportingContent = { Text(stringResource(descriptionRes)) },+        trailingContent = { Switch(checked = checked, onCheckedChange = onCheckedChange) },+    )+}++private val ShieldLevel.titleRes: Int+    get() = when (this) {+        ShieldLevel.OFF -> R.string.shields_level_off+        ShieldLevel.STANDARD -> R.string.shields_level_standard+        ShieldLevel.AGGRESSIVE -> R.string.shields_level_aggressive+    }++private val ShieldLevel.descriptionRes: Int+    get() = when (this) {+        ShieldLevel.OFF -> R.string.shields_level_off_desc+        ShieldLevel.STANDARD -> R.string.shields_level_standard_desc+        ShieldLevel.AGGRESSIVE -> R.string.shields_level_aggressive_desc+    }++/** Global shield defaults plus the list of sites that deviate from them. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ShieldsPage(+    viewModel: WebViewModel,+    backStack: NavBackStack<Route>,+) {+    val overrides by viewModel.shieldSettings.collectAsStateWithLifecycle()+    val global = viewModel.shields++    AppScaffold(title = stringResource(R.string.shields), backStack = backStack) { padding ->+        LazyColumn(Modifier.padding(padding)) {+            item {+                Text(+                    stringResource(R.string.shields_level),+                    style = MaterialTheme.typography.titleSmall,+                    color = MaterialTheme.colorScheme.primary,+                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),+                )+            }+            items(ShieldLevel.entries) { level ->+                Row(+                    Modifier+                        .fillMaxWidth()+                        .clickable { viewModel.updateShields(global.copy(level = level)) }+                        .padding(horizontal = 16.dp, vertical = 10.dp),+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    RadioButton(+                        selected = global.level == level,+                        onClick = { viewModel.updateShields(global.copy(level = level)) },+                    )+                    Spacer(Modifier.width(12.dp))+                    Column {+                        Text(stringResource(level.titleRes), style = MaterialTheme.typography.bodyMedium)+                        Text(+                            stringResource(level.descriptionRes),+                            style = MaterialTheme.typography.bodySmall,+                            color = MaterialTheme.colorScheme.onSurfaceVariant,+                        )+                    }+                }+            }++            item { HorizontalDivider(Modifier.padding(vertical = 8.dp)) }++            item {+                ShieldToggle(+                    R.string.shields_block_trackers,+                    R.string.shields_block_trackers_desc,+                    global.blockTrackers != false,+                ) { on -> viewModel.updateShields(global.copy(blockTrackers = on)) }+            }+            item {+                ShieldToggle(+                    R.string.shields_cosmetic,+                    R.string.shields_cosmetic_desc,+                    global.cosmeticFiltering != false,+                ) { on -> viewModel.updateShields(global.copy(cosmeticFiltering = on)) }+            }+            item {+                ShieldToggle(+                    R.string.shields_fingerprint,+                    R.string.shields_fingerprint_desc,+                    global.fingerprintProtection != false,+                ) { on -> viewModel.updateShields(global.copy(fingerprintProtection = on)) }+            }+            item {+                ShieldToggle(+                    R.string.shields_https,+                    R.string.shields_https_desc,+                    global.httpsUpgrade != false,+                ) { on -> viewModel.updateShields(global.copy(httpsUpgrade = on)) }+            }++            item { HorizontalDivider(Modifier.padding(vertical = 8.dp)) }++            item {+                Text(+                    stringResource(R.string.shields_site_exceptions),+                    style = MaterialTheme.typography.titleSmall,+                    color = MaterialTheme.colorScheme.primary,+                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),+                )+            }++            if (overrides.isEmpty()) {+                item {+                    Surface(+                        shape = RoundedCornerShape(16.dp),+                        color = MaterialTheme.colorScheme.surfaceVariant,+                        modifier = Modifier.padding(16.dp),+                    ) {+                        Text(+                            stringResource(R.string.shields_no_site_exceptions),+                            style = MaterialTheme.typography.bodySmall,+                            modifier = Modifier.padding(14.dp),+                        )+                    }+                }+            } else {+                items(overrides, key = { it.host }) { override ->+                    ListItem(+                        headlineContent = { Text(override.host) },+                        supportingContent = {+                            Text(stringResource(EffectiveShields.resolve(global, override.toSettings()).level.titleRes))+                        },+                        modifier = Modifier.clickable {+                            viewModel.updateSiteShields(override.host, ShieldsSettings())+                        },+                    )+                }+                item {+                    TextButton(+                        onClick = { viewModel.clearSiteShields() },+                        modifier = Modifier.padding(horizontal = 8.dp),+                    ) { Text(stringResource(R.string.shields_clear_exceptions)) }+                }+            }+        }+    }+}
web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.ktindex 0791eb53bd..c9c2415ac9 100644--- a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt@@ -13,7 +13,6 @@ import android.webkit.GeolocationPermissions import android.webkit.PermissionRequest import android.webkit.WebChromeClient import android.webkit.WebResourceRequest-import android.webkit.WebResourceResponse import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient@@ -30,8 +29,11 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat+import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.webkit.WebSettingsCompat import androidx.webkit.WebViewFeature+import com.vayunmathur.web.shields.FarblingConfig+import com.vayunmathur.web.shields.ShieldsWebViewClient import com.vayunmathur.web.util.BrowserUtils import com.vayunmathur.web.util.PwaHelper import com.vayunmathur.web.util.SitePermissionType@@ -58,6 +60,13 @@ fun WebViewBrowser(     val context = LocalContext.current     val holder = remember(tabId) { WebViewHolder() } +    // Observed so a shields change recomposes and re-registers the document-start script;+    // the view model's own mirror is a plain map and would not trigger anything.+    val siteShields by viewModel.shieldSettings.collectAsStateWithLifecycle()+    val farblingConfig = remember(siteShields, viewModel.shields) {+        FarblingConfig.of(viewModel.shields, siteShields.associate { it.host to it.toSettings() })+    }+     var pendingSysPermissionRequest by remember { mutableStateOf<PermissionRequest?>(null) }      val cameraPermissionLauncher = rememberLauncherForActivityResult(@@ -155,21 +164,16 @@ fun WebViewBrowser(                     }                 }) -                webViewClient = object : WebViewClient() {-                    private val adHosts = setOf(-                        "doubleclick.net", "googleadservices.com", "googlesyndication.com",-                        "facebook.com/tr", "googletagmanager.com", "google-analytics.com",-                        "hotjar.com", "mixpanel.com", "segment.com", "criteo.net"-                    )--                    override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {-                        val host = request.url.host ?: ""-                        if (adHosts.any { host.contains(it) }) {-                            return WebResourceResponse("text/plain", "utf-8", "".byteInputStream())-                        }-                        return super.shouldInterceptRequest(view, request)-                    }+                // The tab a WebView belongs to never changes, so capture privacy once instead+                // of reading the Compose tab list from the render thread.+                val isPrivateTab = viewModel.tabs.find { it.id == tabId }?.isPrivate == true +                webViewClient = object : ShieldsWebViewClient(+                    context = ctx,+                    shieldsFor = { host -> viewModel.shieldsFor(host, isPrivateTab) },+                    onBlocked = { _, _ -> viewModel.onRequestBlocked(tabId) },+                    onNavigate = { _, rewritten -> viewModel.onTabUrlChange(tabId, rewritten) },+                ) {                     override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {                         val scheme = request.url.scheme ?: return false                         if (scheme !in setOf("http", "https", "about", "data", "blob", "javascript")) {@@ -181,10 +185,12 @@ fun WebViewBrowser(                                 true                             } catch (_: Exception) { false }                         }-                        return false+                        return super.shouldOverrideUrlLoading(view, request)                     }                      override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {+                        super.onPageStarted(view, url, favicon)+                        viewModel.resetBlockedCount(tabId)                         url?.let { viewModel.onTabUrlChange(tabId, it) }                         viewModel.onTabCanGoBack(tabId, view.canGoBack())                         viewModel.onTabCanGoForward(tabId, view.canGoForward())@@ -362,6 +368,8 @@ fun WebViewBrowser(                 }                  val toLoad = if (initialUrl.isBlank()) "about:blank" else initialUrl+                // Before the first load: document-start scripts do not apply retroactively.+                (webViewClient as ShieldsWebViewClient).installFarbling(this, farblingConfig)                 loadUrl(toLoad)             }.also {                 webViewPool[tabId] = it@@ -380,6 +388,8 @@ fun WebViewBrowser(                 }             }             applySettings(webView, viewModel)+            (webView.webViewClient as? ShieldsWebViewClient)+                ?.installFarbling(webView, farblingConfig)             holder.webView = webView         }     )@@ -426,7 +436,14 @@ private fun applySettings(webView: WebView, viewModel: WebViewModel) {     settings.useWideViewPort = true     settings.loadWithOverviewMode = true -    settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE+    // Aggressive shields refuse plaintext subresources outright; otherwise stay permissive+    // so pages with a few http:// images still render.+    val globalShields = com.vayunmathur.web.util.EffectiveShields.resolve(viewModel.shields)+    settings.mixedContentMode = if (globalShields.httpsOnly) {+        WebSettings.MIXED_CONTENT_NEVER_ALLOW+    } else {+        WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE+    }      // Geolocation DB persists across loads     settings.setGeolocationEnabled(true)
web/src/main/java/com/vayunmathur/web/util/ShieldsSettings.kt
diff --git a/web/src/main/java/com/vayunmathur/web/util/ShieldsSettings.kt b/web/src/main/java/com/vayunmathur/web/util/ShieldsSettings.ktnew file mode 100644index 0000000000..bed97b9646--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/util/ShieldsSettings.kt@@ -0,0 +1,95 @@+package com.vayunmathur.web.util++/**+ * How hard shields work on a site. Mirrors Brave's block-mode selector.+ *+ * [AGGRESSIVE] is the default: it additionally farbles timezone and disables WebRTC,+ * both of which are effective against fingerprinting but break a minority of sites —+ * hence the per-site override in the shields panel.+ */+enum class ShieldLevel { OFF, STANDARD, AGGRESSIVE }++/**+ * A shields configuration.+ *+ * The global instance held by the view model has every field set. Per-site records leave+ * fields null to inherit the global value, so turning one shield off for a site does not+ * freeze the rest at their current values.+ */+data class ShieldsSettings(+    val level: ShieldLevel? = null,+    val blockTrackers: Boolean? = null,+    val cosmeticFiltering: Boolean? = null,+    val fingerprintProtection: Boolean? = null,+    val httpsUpgrade: Boolean? = null,+) {+    /** True when this per-site record says nothing and can be dropped from the database. */+    val isEmpty: Boolean+        get() = level == null && blockTrackers == null && cosmeticFiltering == null &&+            fingerprintProtection == null && httpsUpgrade == null++    companion object {+        /** Brave's "Aggressive" preset, applied on first run. */+        val AGGRESSIVE_DEFAULTS = ShieldsSettings(+            level = ShieldLevel.AGGRESSIVE,+            blockTrackers = true,+            cosmeticFiltering = true,+            fingerprintProtection = true,+            httpsUpgrade = true,+        )+    }+}++/** The resolved shields for one site — what the WebView client actually acts on. */+data class EffectiveShields(+    val level: ShieldLevel,+    val blockTrackers: Boolean,+    val cosmeticFiltering: Boolean,+    val fingerprintProtection: Boolean,+    /** Also farble timezone and remove `RTCPeerConnection`. */+    val aggressiveFingerprinting: Boolean,+    val httpsUpgrade: Boolean,+    /** Block plaintext navigations outright instead of silently downgrading. */+    val httpsOnly: Boolean,+) {+    val anyEnabled: Boolean+        get() = blockTrackers || cosmeticFiltering || fingerprintProtection || httpsUpgrade++    companion object {+        val OFF = EffectiveShields(+            level = ShieldLevel.OFF,+            blockTrackers = false,+            cosmeticFiltering = false,+            fingerprintProtection = false,+            aggressiveFingerprinting = false,+            httpsUpgrade = false,+            httpsOnly = false,+        )++        /**+         * Combines the global defaults with a site's overrides. A site setting always wins;+         * anything it leaves null falls back to the global value, then to the level's preset.+         */+        fun resolve(global: ShieldsSettings, site: ShieldsSettings? = null): EffectiveShields {+            val level = site?.level ?: global.level ?: ShieldLevel.AGGRESSIVE+            if (level == ShieldLevel.OFF) return OFF++            fun pick(+                selector: (ShieldsSettings) -> Boolean?,+            ): Boolean = site?.let(selector) ?: global.let(selector) ?: true++            val fingerprint = pick { it.fingerprintProtection }+            val https = pick { it.httpsUpgrade }+            val aggressive = level == ShieldLevel.AGGRESSIVE+            return EffectiveShields(+                level = level,+                blockTrackers = pick { it.blockTrackers },+                cosmeticFiltering = pick { it.cosmeticFiltering },+                fingerprintProtection = fingerprint,+                aggressiveFingerprinting = fingerprint && aggressive,+                httpsUpgrade = https,+                httpsOnly = https && aggressive,+            )+        }+    }+}
web/src/main/java/com/vayunmathur/web/util/WebViewModel.kt
diff --git a/web/src/main/java/com/vayunmathur/web/util/WebViewModel.kt b/web/src/main/java/com/vayunmathur/web/util/WebViewModel.ktindex 4c561c7f1f..5349140c14 100644--- a/web/src/main/java/com/vayunmathur/web/util/WebViewModel.kt+++ b/web/src/main/java/com/vayunmathur/web/util/WebViewModel.kt@@ -24,8 +24,11 @@ import com.vayunmathur.web.data.InstalledSite import com.vayunmathur.web.data.InstalledSiteDao import com.vayunmathur.web.data.SitePermission import com.vayunmathur.web.data.SitePermissionDao+import com.vayunmathur.web.data.ShieldSetting+import com.vayunmathur.web.data.ShieldSettingDao import com.vayunmathur.web.data.StorageIn

Diff truncated.