Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess): tabs and windows, address bar with suggestions, history, bookmarks and reading list, downloads with resume and external download managers, encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists), VPN through Tor or a proxy and secure DNS via a local bridge proxy, picture in picture, Discord Rich Presence, media player and visualizer, spell check, site apps, user scripts and styles, import from other browsers, gamepads, Web Bluetooth, and every setting of the original Nacre in a plain egui interface. Not compiled yet; docs/HANDOFF.md has the first build checklist. Co-Authored-By: Claude Opus 5.5 <[email protected]>
365 lines
19 KiB
Rust
365 lines
19 KiB
Rust
//! Ad and tracker blocking with adblock-rust (the engine Brave uses): network rules decide each
|
|
//! request in `load_web_resource`, cosmetic rules hide elements on the page, and a YouTube script
|
|
//! removes video ads. Lists are downloaded to the cache and refreshed every `update_days`; seed
|
|
//! copies ship with Nacre so blocking works offline on the first start.
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::{Arc, RwLock};
|
|
use std::time::Duration;
|
|
|
|
use adblock::lists::{FilterFormat, FilterSet, ParseOptions};
|
|
use adblock::request::Request;
|
|
use adblock::Engine;
|
|
|
|
use crate::net::fetch;
|
|
use crate::store::settings::AdBlock as AdBlockSettings;
|
|
use crate::util;
|
|
|
|
pub struct FilterList {
|
|
pub key: &'static str,
|
|
pub group: &'static str,
|
|
pub name: &'static str,
|
|
pub url: &'static str,
|
|
pub description: &'static str,
|
|
}
|
|
|
|
macro_rules! list {
|
|
($key:literal, $group:literal, $name:literal, $url:expr, $desc:literal) => {
|
|
FilterList { key: $key, group: $group, name: $name, url: $url, description: $desc }
|
|
};
|
|
}
|
|
|
|
pub const LISTS: &[FilterList] = &[
|
|
list!("easylist", "Ads", "EasyList", "https://easylist.to/easylist/easylist.txt", "The main ad list"),
|
|
list!("ublock", "Ads", "uBlock filters", "https://ublockorigin.github.io/uAssets/filters/filters.txt", "uBlock Origin's own ad rules"),
|
|
list!("adguard_base", "Ads", "AdGuard Base", "https://filters.adtidy.org/extension/ublock/filters/2_without_easylist.txt", "AdGuard ads, minus EasyList overlap"),
|
|
list!("adguard_mobile", "Ads", "AdGuard Mobile Ads", "https://filters.adtidy.org/extension/ublock/filters/11.txt", "Ads on mobile-style sites"),
|
|
list!("pgl", "Ads", "Peter Lowe's list", "https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext", "Small, fast ad and tracker host list"),
|
|
list!("easyprivacy", "Privacy", "EasyPrivacy", "https://easylist.to/easylist/easyprivacy.txt", "Trackers and analytics"),
|
|
list!("ublock_privacy", "Privacy", "uBlock Privacy", "https://ublockorigin.github.io/uAssets/filters/privacy.txt", "Extra tracking protection"),
|
|
list!("adguard_tracking", "Privacy", "AdGuard Tracking Protection", "https://filters.adtidy.org/extension/ublock/filters/3.txt", "Thorough tracker blocking"),
|
|
list!("adguard_url", "Privacy", "AdGuard URL Tracking", "https://filters.adtidy.org/extension/ublock/filters/17.txt", "Tracking parameters and endpoints"),
|
|
list!("ublock_badware", "Security", "uBlock Badware risks", "https://ublockorigin.github.io/uAssets/filters/badware.txt", "Scam and fake-download sites"),
|
|
list!("urlhaus", "Security", "URLhaus Malicious URLs", "https://malware-filter.gitlab.io/malware-filter/urlhaus-filter-ag-online.txt", "Active malware hosts"),
|
|
list!("phishing", "Security", "Phishing URL Blocklist", "https://malware-filter.gitlab.io/malware-filter/phishing-filter-ag.txt", "Known phishing pages"),
|
|
list!("annoyances", "Annoyances", "uBlock Annoyances", "https://ublockorigin.github.io/uAssets/filters/annoyances.txt", "Pop-ups, overlays, nags"),
|
|
list!("cookies", "Annoyances", "EasyList Cookie List", "https://secure.fanboy.co.nz/fanboy-cookiemonster.txt", "Hides cookie banners"),
|
|
list!("fanboy_annoyance", "Annoyances", "Fanboy Annoyances", "https://secure.fanboy.co.nz/fanboy-annoyance.txt", "Social widgets, newsletters"),
|
|
list!("adguard_annoyances", "Annoyances", "AdGuard Annoyances", "https://filters.adtidy.org/extension/ublock/filters/14.txt", "AdGuard's annoyance collection"),
|
|
list!("stevenblack", "Hosts & DNS lists", "StevenBlack hosts", "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts", "Unified ad and malware hosts"),
|
|
list!("oisd", "Hosts & DNS lists", "OISD small", "https://small.oisd.nl/", "Low false-positive DNS list"),
|
|
list!("hagezi", "Hosts & DNS lists", "HaGeZi Pro", "https://raw.githubusercontent.com/hagezi/dns-blocklists/main/adblock/pro.txt", "Aggressive but well maintained"),
|
|
list!("onehosts", "Hosts & DNS lists", "1Hosts Lite", "https://o0.pages.dev/Lite/adblock.txt", "Light, balanced host list"),
|
|
list!("ublock_quick", "Fixes", "uBlock Quick fixes", "https://ublockorigin.github.io/uAssets/filters/quick-fixes.txt", "Fast-moving fixes (YouTube, Twitch…)"),
|
|
list!("ublock_unbreak", "Fixes", "uBlock Unbreak", "https://ublockorigin.github.io/uAssets/filters/unbreak.txt", "Exceptions that un-break sites"),
|
|
];
|
|
|
|
pub fn list_by_key(key: &str) -> Option<&'static FilterList> {
|
|
LISTS.iter().find(|l| l.key == key)
|
|
}
|
|
|
|
/// CSS selectors removed on YouTube in addition to the lists.
|
|
pub const YT_AD_SELECTORS: &[&str] = &[
|
|
"ytd-ad-slot-renderer", "ytd-in-feed-ad-layout-renderer", "ytd-display-ad-renderer", "ytd-promoted-sparkles-web-renderer",
|
|
"ytd-promoted-video-renderer", "ytd-compact-promoted-video-renderer", "ytd-search-pyv-renderer", "ytd-banner-promo-renderer",
|
|
"ytd-statement-banner-renderer", "ytd-video-masthead-ad-v3-renderer", "#masthead-ad", "#player-ads",
|
|
"ytd-engagement-panel-section-list-renderer[target-id='engagement-panel-ads']", "ytd-merch-shelf-renderer",
|
|
"ytd-ads-engagement-panel-content-renderer", "ytd-player-legacy-desktop-watch-ads-renderer",
|
|
".ytd-mealbar-promo-renderer", "ytmusic-mealbar-promo-renderer", "ytm-promoted-sparkles-web-renderer",
|
|
];
|
|
|
|
/// Removes ads from YouTube's player data and skips video ads that still play.
|
|
pub const YOUTUBE_JS: &str = r#"(() => { const h = location.hostname; if (!/(^|\.)youtube(-nocookie)?\.com$/.test(h)) return;
|
|
const KEYS = ['adPlacements', 'adSlots', 'playerAds', 'adBreakHeartbeatParams'];
|
|
const prune = o => { try { if (o && typeof o === 'object') { for (const k of KEYS) if (k in o) delete o[k];
|
|
if (o.playerResponse) prune(o.playerResponse); if (o.response) prune(o.response); } } catch (e) {} return o; };
|
|
const jp = JSON.parse; JSON.parse = function () { return prune(jp.apply(this, arguments)); };
|
|
const rj = Response.prototype.json; Response.prototype.json = function () { return rj.apply(this, arguments).then(prune); };
|
|
for (const name of ['ytInitialPlayerResponse', 'ytInitialData']) { let v;
|
|
try { Object.defineProperty(window, name, { configurable: true, get: () => v, set: x => { v = prune(x); } }); } catch (e) {} }
|
|
const skip = () => { const p = document.querySelector('#movie_player.ad-showing, ytmusic-player .ad-showing');
|
|
if (p) { const v = p.querySelector('video'); if (v && isFinite(v.duration)) { v.muted = true; v.currentTime = v.duration; } }
|
|
const b = document.querySelector('.ytp-skip-ad-button, .ytp-ad-skip-button, .ytp-ad-skip-button-modern');
|
|
if (b) b.click(); };
|
|
const start = () => new MutationObserver(skip).observe(document.documentElement, { subtree: true, attributes: true, attributeFilter: ['class'], childList: true });
|
|
if (document.documentElement) start(); else document.addEventListener('readystatechange', start, { once: true });
|
|
})();"#;
|
|
|
|
/// What to do with a request.
|
|
pub enum Verdict {
|
|
Allow,
|
|
Block,
|
|
/// Serve this body instead (a harmless stand-in from a `redirect` rule): (mime, body).
|
|
Replace(String, Vec<u8>),
|
|
}
|
|
|
|
/// Map a fetch destination to an adblock request type.
|
|
pub fn request_type(destination: &str) -> &'static str {
|
|
match destination {
|
|
"document" => "document",
|
|
"iframe" | "frame" => "subdocument",
|
|
"script" | "worker" | "sharedworker" | "serviceworker" | "audioworklet" | "paintworklet" => "script",
|
|
"style" | "xslt" => "stylesheet",
|
|
"image" => "image",
|
|
"font" => "font",
|
|
"audio" | "video" | "track" => "media",
|
|
"object" | "embed" => "object",
|
|
"report" => "ping",
|
|
"json" | "none" | "" => "xmlhttprequest",
|
|
_ => "other",
|
|
}
|
|
}
|
|
|
|
struct Built {
|
|
engine: Engine,
|
|
rules: usize,
|
|
}
|
|
|
|
pub struct AdBlocker {
|
|
built: RwLock<Option<Built>>,
|
|
/// Lists that failed to download last time: key -> reason.
|
|
pub failures: RwLock<HashMap<String, String>>,
|
|
pub updating: std::sync::atomic::AtomicBool,
|
|
pub building: std::sync::atomic::AtomicBool,
|
|
}
|
|
|
|
/// The seed copies shipped with Nacre (next to the program, or in the source tree when developing).
|
|
fn seed_dir() -> Option<PathBuf> {
|
|
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned));
|
|
let candidates = [exe_dir.as_ref().map(|d| d.join("filters")), exe_dir.as_ref().map(|d| d.join("../share/nacre/filters")), Some(PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/assets/filters")))];
|
|
candidates.into_iter().flatten().find(|d| d.is_dir())
|
|
}
|
|
|
|
fn list_path(dir: &Path, key: &str) -> PathBuf {
|
|
dir.join(format!("{}.txt", util::safe_file_name(key)))
|
|
}
|
|
|
|
fn custom_key(url: &str) -> String {
|
|
format!("custom-{}", &util::hex(url.as_bytes())[..url.len().min(24) * 2])
|
|
}
|
|
|
|
impl Default for AdBlocker {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
impl AdBlocker {
|
|
pub fn new() -> AdBlocker {
|
|
AdBlocker { built: RwLock::new(None), failures: RwLock::new(HashMap::new()), updating: false.into(), building: false.into() }
|
|
}
|
|
|
|
pub fn ready(&self) -> bool {
|
|
self.built.read().map(|b| b.is_some()).unwrap_or(false)
|
|
}
|
|
|
|
pub fn rule_count(&self) -> usize {
|
|
self.built.read().ok().and_then(|b| b.as_ref().map(|b| b.rules)).unwrap_or(0)
|
|
}
|
|
|
|
/// Copy seed lists into the cache for any enabled list that has never been downloaded.
|
|
pub fn seed(dir: &Path) {
|
|
let Some(seed) = seed_dir() else { return };
|
|
let _ = std::fs::create_dir_all(dir);
|
|
for list in LISTS {
|
|
let target = list_path(dir, list.key);
|
|
let source = list_path(&seed, list.key);
|
|
if !target.exists() && source.exists() {
|
|
let _ = std::fs::copy(&source, &target);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Age of a downloaded list in seconds, or None if it isn't there.
|
|
pub fn list_age(dir: &Path, key: &str) -> Option<u64> {
|
|
let modified = std::fs::metadata(list_path(dir, key)).ok()?.modified().ok()?;
|
|
Some(modified.elapsed().map(|d| d.as_secs()).unwrap_or(0))
|
|
}
|
|
|
|
/// Build the engine from the enabled lists. Blocking (a second or two); call from a worker.
|
|
/// Uses the cached compiled engine when the lists haven't changed.
|
|
pub fn build(&self, settings: &AdBlockSettings, dir: &Path, cache: &Path) {
|
|
use std::sync::atomic::Ordering;
|
|
if self.building.swap(true, Ordering::SeqCst) {
|
|
return;
|
|
}
|
|
Self::seed(dir);
|
|
let mut keys: Vec<String> = settings.lists.iter().filter(|k| list_by_key(k).is_some()).cloned().collect();
|
|
keys.extend(settings.custom.iter().map(|u| custom_key(u)));
|
|
// Fingerprint: list names, sizes, change times and the user's own rules.
|
|
let mut fingerprint = String::new();
|
|
for key in &keys {
|
|
if let Ok(meta) = std::fs::metadata(list_path(dir, key)) {
|
|
let modified = meta.modified().ok().and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0);
|
|
fingerprint.push_str(&format!("{key}:{}:{modified};", meta.len()));
|
|
}
|
|
}
|
|
fingerprint.push_str(&settings.own_rules);
|
|
let fingerprint = util::hex(&simple_hash(fingerprint.as_bytes()).to_le_bytes());
|
|
let stamp_path = cache.with_extension("stamp");
|
|
let cached_stamp = std::fs::read_to_string(&stamp_path).unwrap_or_default();
|
|
if cached_stamp.trim_start().starts_with(&fingerprint)
|
|
&& let Ok(bytes) = std::fs::read(cache)
|
|
{
|
|
let mut engine = Engine::default();
|
|
if engine.deserialize(&bytes).is_ok() {
|
|
let rules = cached_stamp.split_whitespace().nth(1).and_then(|n| n.parse().ok()).unwrap_or(0);
|
|
if let Ok(mut built) = self.built.write() {
|
|
*built = Some(Built { engine, rules });
|
|
}
|
|
self.building.store(false, Ordering::SeqCst);
|
|
return;
|
|
}
|
|
}
|
|
let mut set = FilterSet::new(false);
|
|
let mut rules = 0usize;
|
|
for key in &keys {
|
|
let Ok(text) = std::fs::read_to_string(list_path(dir, key)) else { continue };
|
|
let format = if looks_like_hosts(&text) { FilterFormat::Hosts } else { FilterFormat::Standard };
|
|
rules += count_rules(&text);
|
|
set.add_filter_list(text, ParseOptions { format, ..ParseOptions::default() });
|
|
}
|
|
if !settings.own_rules.trim().is_empty() {
|
|
rules += count_rules(&settings.own_rules);
|
|
set.add_filter_list(settings.own_rules.clone(), ParseOptions::default());
|
|
}
|
|
let engine = Engine::new_with_filter_set(set);
|
|
let _ = util::write_atomic(cache, &engine.serialize(), false);
|
|
let _ = std::fs::write(&stamp_path, format!("{fingerprint} {rules}"));
|
|
if let Ok(mut built) = self.built.write() {
|
|
*built = Some(Built { engine, rules });
|
|
}
|
|
self.building.store(false, Ordering::SeqCst);
|
|
}
|
|
|
|
/// Download enabled lists that are older than `max_age` seconds (0 = all). Blocking.
|
|
/// Returns how many were refreshed.
|
|
pub fn update_lists(&self, settings: &AdBlockSettings, dir: &Path, max_age: u64) -> usize {
|
|
use std::sync::atomic::Ordering;
|
|
if self.updating.swap(true, Ordering::SeqCst) {
|
|
return 0;
|
|
}
|
|
let _ = std::fs::create_dir_all(dir);
|
|
let mut wanted: Vec<(String, String)> = settings.lists.iter().filter_map(|k| list_by_key(k).map(|l| (k.clone(), l.url.to_owned()))).collect();
|
|
wanted.extend(settings.custom.iter().map(|u| (custom_key(u), u.clone())));
|
|
let mut refreshed = 0;
|
|
for (key, url) in wanted {
|
|
if max_age > 0 && Self::list_age(dir, &key).is_some_and(|age| age < max_age) {
|
|
continue;
|
|
}
|
|
match fetch::get(&url, &[], 32 * 1024 * 1024, Duration::from_secs(120)) {
|
|
Ok(fetched) if fetched.ok() && fetched.body.len() > 64 => {
|
|
if util::write_atomic(&list_path(dir, &key), &fetched.body, false).is_ok() {
|
|
refreshed += 1;
|
|
if let Ok(mut failures) = self.failures.write() {
|
|
failures.remove(&key);
|
|
}
|
|
}
|
|
},
|
|
Ok(fetched) => {
|
|
if let Ok(mut failures) = self.failures.write() {
|
|
failures.insert(key, format!("the server answered {}", fetched.status));
|
|
}
|
|
},
|
|
Err(error) => {
|
|
if let Ok(mut failures) = self.failures.write() {
|
|
failures.insert(key, error);
|
|
}
|
|
},
|
|
}
|
|
}
|
|
self.updating.store(false, Ordering::SeqCst);
|
|
refreshed
|
|
}
|
|
|
|
/// Decide a network request. `page_url` is the page that made it ("" for top-level loads).
|
|
pub fn check(&self, url: &str, page_url: &str, destination: &str) -> Verdict {
|
|
let Ok(built) = self.built.read() else { return Verdict::Allow };
|
|
let Some(built) = built.as_ref() else { return Verdict::Allow };
|
|
let source = if page_url.is_empty() { url } else { page_url };
|
|
let Ok(request) = Request::new(url, source, request_type(destination), "GET") else { return Verdict::Allow };
|
|
let result = built.engine.check_network_request(&request);
|
|
if let Some(redirect) = result.redirect.as_deref()
|
|
&& let Some((mime, body)) = decode_data_url(redirect)
|
|
{
|
|
return Verdict::Replace(mime, body);
|
|
}
|
|
if result.should_block() { Verdict::Block } else { Verdict::Allow }
|
|
}
|
|
|
|
/// Selectors to hide on this page and whether generic hiding is off for it.
|
|
pub fn page_selectors(&self, url: &str) -> (Vec<String>, HashSet<String>, bool) {
|
|
let Ok(built) = self.built.read() else { return (Vec::new(), HashSet::new(), false) };
|
|
let Some(built) = built.as_ref() else { return (Vec::new(), HashSet::new(), false) };
|
|
let resources = built.engine.url_cosmetic_resources(url);
|
|
let mut selectors: Vec<String> = resources.hide_selectors.into_iter().collect();
|
|
let host = util::host_of_str(url);
|
|
if util::host_matches(&host, "youtube.com") {
|
|
selectors.extend(YT_AD_SELECTORS.iter().map(|s| (*s).to_owned()));
|
|
}
|
|
(selectors, resources.exceptions, resources.generichide)
|
|
}
|
|
|
|
/// Generic hiding: selectors for the classes and ids found on a page.
|
|
pub fn generic_selectors(&self, classes: &[String], ids: &[String], exceptions: &HashSet<String>) -> Vec<String> {
|
|
let Ok(built) = self.built.read() else { return Vec::new() };
|
|
let Some(built) = built.as_ref() else { return Vec::new() };
|
|
built.engine.hidden_class_id_selectors(classes, ids, exceptions)
|
|
}
|
|
}
|
|
|
|
/// Rule lines in a list (comments and headers left out); shown in settings.
|
|
fn count_rules(text: &str) -> usize {
|
|
text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('!') && !l.starts_with('[') && (!l.starts_with('#') || l.starts_with("##") || l.starts_with("#@#") || l.starts_with("#?#"))).count()
|
|
}
|
|
|
|
fn looks_like_hosts(text: &str) -> bool {
|
|
text.lines().filter(|l| !l.trim().is_empty() && !l.starts_with('#') && !l.starts_with('!')).take(20).filter(|l| l.starts_with("0.0.0.0 ") || l.starts_with("127.0.0.1 ")).count() >= 10
|
|
}
|
|
|
|
fn decode_data_url(url: &str) -> Option<(String, Vec<u8>)> {
|
|
use base64::Engine as _;
|
|
let rest = url.strip_prefix("data:")?;
|
|
let (meta, data) = rest.split_once(',')?;
|
|
let mime = meta.split(';').next().unwrap_or("text/plain").to_owned();
|
|
let body = if meta.ends_with(";base64") { base64::engine::general_purpose::STANDARD.decode(data).ok()? } else { util::percent_decode(data).into_bytes() };
|
|
Some((mime, body))
|
|
}
|
|
|
|
/// FNV-1a; only used to notice that the lists changed.
|
|
fn simple_hash(data: &[u8]) -> u64 {
|
|
let mut hash = 0xcbf2_9ce4_8422_2325u64;
|
|
for b in data {
|
|
hash ^= *b as u64;
|
|
hash = hash.wrapping_mul(0x0100_0000_01b3);
|
|
}
|
|
hash
|
|
}
|
|
|
|
/// Shared handle.
|
|
pub type SharedAdBlocker = Arc<AdBlocker>;
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn urls_are_joined() {
|
|
assert_eq!(list_by_key("ublock").unwrap().url, "https://ublockorigin.github.io/uAssets/filters/filters.txt");
|
|
assert_eq!(request_type("iframe"), "subdocument");
|
|
}
|
|
|
|
#[test]
|
|
fn blocks_with_own_rules() {
|
|
let dir = std::env::temp_dir().join(format!("nacre-adblock-test-{}", util::random_hex(6)));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let settings = AdBlockSettings { lists: Vec::new(), own_rules: "||ads.example^\nexample.org##.banner".into(), ..AdBlockSettings::default() };
|
|
let blocker = AdBlocker::new();
|
|
blocker.build(&settings, &dir.join("lists"), &dir.join("engine.bin"));
|
|
assert!(matches!(blocker.check("https://ads.example/x.js", "https://news.example/", "script"), Verdict::Block));
|
|
assert!(matches!(blocker.check("https://news.example/app.js", "https://news.example/", "script"), Verdict::Allow));
|
|
assert!(blocker.page_selectors("https://example.org/").0.contains(&".banner".to_owned()));
|
|
let _ = std::fs::remove_dir_all(dir);
|
|
}
|
|
}
|