Nacre/src/hub.rs
astar76 d2cc780684 S024: privacy mode that holds up (R1-16)
Firefox-consistent anti-fingerprinting script (canvas/WebGL/audio/font noise per run and site; common screen,
CPU, platform, touch and WebGL values; frames covered), paused per site, on in incognito. Privacy mode also
switches third-party cookie blocking and a Firefox-style Accept-Language in the vendored servo-net;
document.cookie is emptied in cross-site frames. Engine gaps fixed on the way: screen geometry (was 0x0),
document.fonts.check, a pass-through DynamicsCompressorNode. Settings sub-page and shield flyout explain it.
Tests: unit tests, privacy-mode/incognito/net smokes, Cover Your Tracks run recorded in
docs/engine/privacy-mode.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 17:13:08 -06:00

522 lines
24 KiB
Rust

//! Everything Servo tells the browser arrives here, on the main thread, inside
//! `Servo::spin_event_loop`. Resource loads are decided on the spot (Servo holds a lock while it
//! waits); everything else becomes an `Event` that the app handles right after the spin.
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;
use std::sync::Arc;
use http::{HeaderMap, HeaderValue, StatusCode};
use servo::{
AllowOrDenyRequest, AuthenticationRequest, BluetoothDeviceSelectionRequest, ConsoleLogLevel, CreateNewWebViewRequest, Cursor, EmbedderControl, EmbedderControlId, LoadStatus, MediaSessionEvent, NavigationRequest, Notification, PermissionRequest, ServoDelegate, ServoError, WebResourceLoad, WebResourceResponse, WebView, WebViewDelegate, WebViewId,
};
use url::Url;
use crate::adblock::{AdBlocker, Verdict};
use crate::inject::{self, PageMessage};
use crate::store::permissions::{Answer, Decision, Kind, Permissions};
use crate::store::settings::Settings;
use crate::util;
pub enum Event {
UrlChanged(WebViewId, Url),
TitleChanged(WebViewId, Option<String>),
StatusText(WebViewId, Option<String>),
LoadStatus(WebViewId, LoadStatus),
Cursor(WebViewId, Cursor),
Favicon(WebViewId),
FrameReady(WebViewId),
History(WebViewId, Vec<Url>, usize),
Closed(WebViewId),
Crashed(WebViewId, String, Option<String>),
MediaSession(WebViewId, MediaSessionEvent),
Fullscreen(WebViewId, bool),
Animating(WebViewId, bool),
Navigation(WebViewId, NavigationRequest),
Unload(WebViewId, AllowOrDenyRequest),
CreateNew(WebViewId, CreateNewWebViewRequest),
Permission(WebViewId, PermissionRequest),
Auth(WebViewId, AuthenticationRequest),
Bluetooth(WebViewId, BluetoothDeviceSelectionRequest),
ProtocolHandler(WebViewId, servo::protocol_handler::ProtocolHandlerRegistration, AllowOrDenyRequest),
Control(WebViewId, EmbedderControl),
HideControl(WebViewId, EmbedderControlId),
Notification(Option<WebViewId>, Notification),
Page(WebViewId, PageMessage),
Console(WebViewId, ConsoleLogLevel, String),
ResizeTo(WebViewId, servo::DeviceIntSize),
/// A main-frame load was upgraded to https by HTTPS-only mode (original URL).
UpgradedToHttps(WebViewId, Url),
DevtoolsStarted(u16, String),
DevtoolsConnection(AllowOrDenyRequest),
ServoError(String),
}
/// One request seen by the network log (developer tools).
#[derive(Clone, Debug)]
pub struct NetEntry {
pub time_ms: u64,
pub method: String,
pub url: String,
pub kind: String,
pub blocked: bool,
}
const NET_LOG_LEN: usize = 400;
/// What the synchronous decisions need from the rest of the browser. The app keeps it current.
#[derive(Default)]
pub struct HubConfig {
pub adblock_enabled: bool,
pub adblock_allow: Vec<String>,
pub https_only: bool,
pub https_exceptions: Vec<String>,
pub strip_params: bool,
pub google_signin: bool,
/// Images permission: blocked unless a site says otherwise, and the sites that differ (host, blocked).
pub images_block_default: bool,
pub images_sites: Vec<(String, bool)>,
pub user_agent: String,
/// Tabs where the user chose "open over http anyway" this session (host).
pub http_allowed: Vec<String>,
}
impl HubConfig {
/// Whether pictures are blocked on pages of this host.
pub fn images_blocked(&self, host: &str) -> bool {
self.images_sites.iter().find(|(h, _)| h == host).map(|(_, block)| *block).unwrap_or(self.images_block_default)
}
pub fn from_settings(settings: &Settings, permissions: &Permissions, user_agent: &str, http_allowed: Vec<String>) -> HubConfig {
HubConfig {
adblock_enabled: settings.adblock.enabled,
adblock_allow: settings.adblock.allow.clone(),
https_only: settings.privacy.https_only,
https_exceptions: settings.privacy.https_exceptions.clone(),
strip_params: settings.privacy.strip_params,
google_signin: settings.privacy.google_signin,
images_block_default: permissions.answer(settings, "", Kind::Images) == Answer::Block,
images_sites: permissions.all().into_iter().filter(|(_, kind, _)| *kind == Kind::Images).map(|(host, _, decision)| (host, decision == Decision::Block)).collect(),
user_agent: user_agent.to_owned(),
http_allowed,
}
}
}
pub struct Hub {
pub events: RefCell<VecDeque<Event>>,
pub token: String,
pub config: RefCell<HubConfig>,
pub adblock: Arc<AdBlocker>,
/// Requests blocked per webview since its page started loading.
pub blocked: RefCell<HashMap<WebViewId, u32>>,
/// Total blocked this run (added to the saved total by the app).
pub blocked_total: RefCell<u64>,
pub net_log: RefCell<HashMap<WebViewId, VecDeque<NetEntry>>>,
/// Whether the Firefox user agent is in use (Google sign-in quirk).
pub ua_quirk_on: RefCell<bool>,
pub servo: RefCell<Option<servo::Servo>>,
/// The screen and window for `window.screen` and `outerWidth`; the app keeps it current. Without it Servo
/// reports a 0 x 0 screen.
pub screen: RefCell<Option<servo::ScreenGeometry>>,
}
/// Tracking parameters removed from links when "strip tracking parameters" is on.
const TRACKING_PARAMS: &[&str] = &[
"fbclid", "gclid", "dclid", "gbraid", "wbraid", "msclkid", "mc_eid", "mc_cid", "igshid", "yclid", "_hsenc", "_hsmi", "twclid", "ttclid", "li_fat_id", "oly_enc_id", "oly_anon_id", "vero_id", "wickedid", "_openstat", "mkt_tok", "s_cid", "srsltid", "rb_clickid", "epik", "ga_source",
];
const TRACKING_PREFIXES: &[&str] = &["utm_", "pk_", "mtm_", "hsa_"];
/// Headers every request carries for the privacy settings: Do Not Track with Global Privacy Control, and
/// Save-Data. Applied in the vendored servo-net (S023).
pub fn privacy_headers(settings: &Settings) -> Vec<(&'static str, &'static str)> {
let mut headers = Vec::new();
if settings.privacy.dnt {
headers.extend([("DNT", "1"), ("Sec-GPC", "1")]);
}
if settings.privacy.save_data {
headers.push(("Save-Data", "on"));
}
headers
}
/// The URL without tracking parameters, if it had any.
pub fn strip_tracking(url: &Url) -> Option<Url> {
url.query()?;
let pairs: Vec<(String, String)> = url.query_pairs().map(|(k, v)| (k.into_owned(), v.into_owned())).collect();
let keep: Vec<&(String, String)> = pairs.iter().filter(|(k, _)| { let k = k.to_ascii_lowercase(); !TRACKING_PARAMS.contains(&k.as_str()) && !TRACKING_PREFIXES.iter().any(|p| k.starts_with(p)) }).collect();
if keep.len() == pairs.len() {
return None;
}
let mut clean = url.clone();
if keep.is_empty() {
clean.set_query(None);
} else {
clean.query_pairs_mut().clear().extend_pairs(keep.iter().map(|(k, v)| (k.as_str(), v.as_str())));
}
Some(clean)
}
fn destination_name(d: &content_security_policy::Destination) -> String {
format!("{d:?}").to_ascii_lowercase()
}
impl Hub {
pub fn new(adblock: Arc<AdBlocker>) -> Rc<Hub> {
Rc::new(Hub {
events: RefCell::new(VecDeque::new()),
token: format!("\u{1}nacre-{}\u{1}", util::random_hex(12)),
config: RefCell::new(HubConfig::default()),
adblock,
blocked: RefCell::new(HashMap::new()),
blocked_total: RefCell::new(0),
net_log: RefCell::new(HashMap::new()),
ua_quirk_on: RefCell::new(false),
servo: RefCell::new(None),
screen: RefCell::new(None),
})
}
fn push(&self, event: Event) {
self.events.borrow_mut().push_back(event);
}
pub fn take_events(&self) -> Vec<Event> {
self.events.borrow_mut().drain(..).collect()
}
fn log_request(&self, webview: WebViewId, method: &str, url: &str, kind: &str, blocked: bool) {
let mut logs = self.net_log.borrow_mut();
let log = logs.entry(webview).or_default();
if log.len() >= NET_LOG_LEN {
log.pop_front();
}
log.push_back(NetEntry { time_ms: util::now_ms(), method: method.to_owned(), url: url.to_owned(), kind: kind.to_owned(), blocked });
}
pub fn forget(&self, webview: WebViewId) {
self.blocked.borrow_mut().remove(&webview);
self.net_log.borrow_mut().remove(&webview);
}
fn serve_page(load: WebResourceLoad, body: Vec<u8>) {
let url = load.request.url.clone();
let mut headers = HeaderMap::new();
headers.insert(http::header::CONTENT_TYPE, HeaderValue::from_static("text/html; charset=utf-8"));
headers.insert(http::header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
let mut intercepted = load.intercept(WebResourceResponse::new(url).headers(headers).status_code(StatusCode::OK));
intercepted.send_body_data(body);
intercepted.finish();
}
/// Switch the user agent for Google's sign-in pages and back.
fn google_quirk(&self, url: &Url) {
let want = self.config.borrow().google_signin && url.host_str().is_some_and(|h| h == "accounts.google.com");
if *self.ua_quirk_on.borrow() == want {
return;
}
*self.ua_quirk_on.borrow_mut() = want;
let ua = if want { inject::FIREFOX_UA.to_owned() } else { self.config.borrow().user_agent.clone() };
if let Some(servo) = self.servo.borrow().as_ref() {
servo.set_preference("user_agent", servo::PrefValue::Str(ua));
}
}
fn decide(&self, webview: Option<&WebView>, load: WebResourceLoad) {
let request = &load.request;
let url = request.url.clone();
let kind = destination_name(&request.destination);
let method = request.method.as_str().to_owned();
let page = webview.and_then(WebView::url);
let id = webview.map(WebView::id);
let is_document = request.is_for_main_frame;
let config = self.config.borrow();
if is_document && matches!(url.scheme(), "http" | "https") {
drop(config);
self.google_quirk(&url);
let config = self.config.borrow();
// HTTPS-only: upgrade plain http documents (not local addresses, not exceptions).
if config.https_only && url.scheme() == "http" {
let host = url.host_str().unwrap_or("").to_owned();
let excepted = crate::net::bridge::is_local_host(&host) || config.https_exceptions.iter().chain(&config.http_allowed).any(|h| util::host_matches(&host, h));
if !excepted {
let mut secure = url.clone();
if secure.set_scheme("https").is_ok() {
if secure.port() == Some(80) {
let _ = secure.set_port(None);
}
drop(config);
if let Some(id) = id {
self.push(Event::UpgradedToHttps(id, url.clone()));
}
Self::serve_page(load, inject::redirect_page(secure.as_str(), "Opening the secure version…"));
return;
}
}
}
if config.strip_params
&& let Some(clean) = strip_tracking(&url)
{
drop(config);
Self::serve_page(load, inject::redirect_page(clean.as_str(), "Removing tracking parameters…"));
return;
}
drop(config);
// A new page: count its blocked requests from zero. Here, not at LoadStatus::Started: the app
// sees that event after the page's first sub-resources were already decided and counted.
if let Some(id) = id {
self.blocked.borrow_mut().insert(id, 0);
self.log_request(id, &method, url.as_str(), &kind, false);
}
return;
}
// Sub-resources: the Images permission, then the ad blocker.
let page_url = page.as_ref().map(Url::as_str).unwrap_or("");
let page_host = util::host_of_str(page_url);
if kind == "image" && matches!(url.scheme(), "http" | "https") && !page_host.is_empty() && config.images_blocked(&page_host) {
drop(config);
load.intercept(WebResourceResponse::new(url).status_code(StatusCode::NO_CONTENT)).cancel();
return;
}
let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| util::host_matches(&page_host, h));
drop(config);
if !paused && matches!(url.scheme(), "http" | "https" | "ws" | "wss") {
match self.adblock.check(url.as_str(), page_url, &kind) {
Verdict::Allow => {},
Verdict::Block => {
if let Some(id) = id {
*self.blocked.borrow_mut().entry(id).or_insert(0) += 1;
self.log_request(id, &method, url.as_str(), &kind, true);
}
*self.blocked_total.borrow_mut() += 1;
load.intercept(WebResourceResponse::new(url).status_code(StatusCode::NO_CONTENT)).cancel();
return;
},
Verdict::Replace(mime, body) => {
if let Some(id) = id {
*self.blocked.borrow_mut().entry(id).or_insert(0) += 1;
self.log_request(id, &method, url.as_str(), &kind, true);
}
*self.blocked_total.borrow_mut() += 1;
let mut headers = HeaderMap::new();
if let Ok(value) = HeaderValue::from_str(&mime) {
headers.insert(http::header::CONTENT_TYPE, value);
}
let mut intercepted = load.intercept(WebResourceResponse::new(url).headers(headers));
intercepted.send_body_data(body);
intercepted.finish();
return;
},
}
}
if let Some(id) = id {
self.log_request(id, &method, url.as_str(), &kind, false);
}
// Dropping `load` lets it through.
}
}
impl WebViewDelegate for Hub {
fn screen_geometry(&self, _webview: WebView) -> Option<servo::ScreenGeometry> {
*self.screen.borrow()
}
fn notify_url_changed(&self, webview: WebView, url: Url) {
// Covers pages shown without a request (history) and downloads that kept the old page.
net::nacre::set_top_level_url(webview.id(), &servo::ServoUrl::from_url(url.clone()));
self.push(Event::UrlChanged(webview.id(), url));
}
fn notify_page_title_changed(&self, webview: WebView, title: Option<String>) {
self.push(Event::TitleChanged(webview.id(), title));
}
fn notify_status_text_changed(&self, webview: WebView, status: Option<String>) {
self.push(Event::StatusText(webview.id(), status));
}
fn notify_animating_changed(&self, webview: WebView, animating: bool) {
self.push(Event::Animating(webview.id(), animating));
}
fn notify_load_status_changed(&self, webview: WebView, status: LoadStatus) {
self.push(Event::LoadStatus(webview.id(), status));
}
fn notify_cursor_changed(&self, webview: WebView, cursor: Cursor) {
self.push(Event::Cursor(webview.id(), cursor));
}
fn notify_favicon_changed(&self, webview: WebView) {
self.push(Event::Favicon(webview.id()));
}
fn notify_new_frame_ready(&self, webview: WebView) {
self.push(Event::FrameReady(webview.id()));
}
fn notify_history_changed(&self, webview: WebView, entries: Vec<Url>, current: usize) {
self.push(Event::History(webview.id(), entries, current));
}
fn notify_closed(&self, webview: WebView) {
net::nacre::forget_webview(webview.id());
self.push(Event::Closed(webview.id()));
}
fn notify_crashed(&self, webview: WebView, reason: String, backtrace: Option<String>) {
self.push(Event::Crashed(webview.id(), reason, backtrace));
}
fn notify_media_session_event(&self, webview: WebView, event: MediaSessionEvent) {
self.push(Event::MediaSession(webview.id(), event));
}
fn notify_fullscreen_state_changed(&self, webview: WebView, fullscreen: bool) {
self.push(Event::Fullscreen(webview.id(), fullscreen));
}
fn request_navigation(&self, webview: WebView, request: NavigationRequest) {
self.push(Event::Navigation(webview.id(), request));
}
fn request_unload(&self, webview: WebView, request: AllowOrDenyRequest) {
self.push(Event::Unload(webview.id(), request));
}
fn request_resize_to(&self, webview: WebView, size: servo::DeviceIntSize) {
self.push(Event::ResizeTo(webview.id(), size));
}
fn request_protocol_handler(&self, webview: WebView, registration: servo::protocol_handler::ProtocolHandlerRegistration, request: AllowOrDenyRequest) {
self.push(Event::ProtocolHandler(webview.id(), registration, request));
}
fn request_create_new(&self, parent: WebView, request: CreateNewWebViewRequest) {
self.push(Event::CreateNew(parent.id(), request));
}
fn request_permission(&self, webview: WebView, request: PermissionRequest) {
self.push(Event::Permission(webview.id(), request));
}
fn request_authentication(&self, webview: WebView, request: AuthenticationRequest) {
self.push(Event::Auth(webview.id(), request));
}
fn show_bluetooth_device_dialog(&self, webview: WebView, request: BluetoothDeviceSelectionRequest) {
self.push(Event::Bluetooth(webview.id(), request));
}
fn show_embedder_control(&self, webview: WebView, control: EmbedderControl) {
self.push(Event::Control(webview.id(), control));
}
fn hide_embedder_control(&self, webview: WebView, id: EmbedderControlId) {
self.push(Event::HideControl(webview.id(), id));
}
fn load_web_resource(&self, webview: WebView, load: WebResourceLoad) {
self.decide(Some(&webview), load);
}
fn show_notification(&self, webview: WebView, notification: Notification) {
self.push(Event::Notification(Some(webview.id()), notification));
}
fn show_console_message(&self, webview: WebView, level: ConsoleLogLevel, message: String) {
if let Some(msg) = inject::parse_message(&self.token, &message) {
self.push(Event::Page(webview.id(), msg));
} else if !message.starts_with(&self.token) {
self.push(Event::Console(webview.id(), level, message));
}
}
}
impl ServoDelegate for Hub {
fn notify_error(&self, error: ServoError) {
self.push(Event::ServoError(format!("{error:?}")));
}
fn notify_devtools_server_started(&self, port: u16, token: String) {
self.push(Event::DevtoolsStarted(port, token));
}
fn request_devtools_connection(&self, request: AllowOrDenyRequest) {
self.push(Event::DevtoolsConnection(request));
}
fn load_web_resource(&self, load: WebResourceLoad) {
self.decide(None, load);
}
fn show_notification(&self, notification: Notification) {
self.push(Event::Notification(None, notification));
}
}
/// Gamepad rumble: gilrs can do force feedback on Linux; Nacre reports "not supported" for now
/// rather than pretending it played.
pub struct Gamepads;
impl servo::GamepadDelegate for Gamepads {
fn handle_haptic_effect_request(&self, request: servo::GamepadHapticEffectRequest) {
request.failed();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn privacy_language_list_is_firefox_style() {
assert_eq!(net::nacre::languages("en-US"), vec!["en-US", "en"]);
assert_eq!(net::nacre::languages("pt-BR"), vec!["pt-BR", "pt"]);
assert_eq!(net::nacre::languages("en"), vec!["en"]);
assert_eq!(net::nacre::accept_language(&net::nacre::languages("en-US")), "en-US,en;q=0.5");
assert_eq!(net::nacre::accept_language(&net::nacre::languages("de")), "de");
}
#[test]
fn privacy_headers_follow_the_settings_and_reach_requests() {
let mut settings = Settings::default();
settings.privacy.dnt = true;
settings.privacy.save_data = false;
assert_eq!(privacy_headers(&settings), vec![("DNT", "1"), ("Sec-GPC", "1")]);
settings.privacy.dnt = false;
settings.privacy.save_data = true;
assert_eq!(privacy_headers(&settings), vec![("Save-Data", "on")]);
// servo-net adds them to a request unless the page set the header itself.
net::nacre::set_extra_request_headers(&[("DNT", "1"), ("Sec-GPC", "1"), ("Bad Name", "x")]);
let mut headers = HeaderMap::new();
headers.insert("Sec-GPC", HeaderValue::from_static("0"));
net::nacre::append_extra_headers(&mut headers);
assert_eq!(headers.len(), 2);
assert_eq!(headers["dnt"], "1");
assert_eq!(headers["sec-gpc"], "0");
net::nacre::set_extra_request_headers(&[]);
}
#[test]
fn third_party_matching_keeps_same_site_subdomains() {
use net::nacre::{is_third_party, site_of_host};
let url = |s: &str| servo::ServoUrl::parse(s).unwrap();
assert_eq!(site_of_host("www.Example.com"), "example.com");
assert_eq!(site_of_host("a.b.example.co.uk"), "example.co.uk");
assert_eq!(site_of_host("site.nacre.test"), "nacre.test");
assert_eq!(site_of_host("127.0.0.1"), "127.0.0.1");
assert_eq!(site_of_host("[::1]"), "[::1]");
assert_eq!(site_of_host("localhost"), "localhost");
let top = site_of_host("www.example.com");
assert!(!is_third_party(&top, &url("https://login.example.com/x")));
assert!(!is_third_party(&top, &url("http://example.com:8080/")));
assert!(is_third_party(&top, &url("https://tracker.net/p.gif")));
assert!(is_third_party(&top, &url("https://example.co.uk/")));
// Different users' sites under one public suffix are different sites.
let top = site_of_host("alice.github.io");
assert!(is_third_party(&top, &url("https://bob.github.io/")));
assert!(!is_third_party(&top, &url("https://alice.github.io/repo")));
// IP addresses only match themselves; URLs without a host are never third-party.
let top = site_of_host("127.0.0.1");
assert!(is_third_party(&top, &url("http://127.0.0.2/")));
assert!(!is_third_party(&top, &url("data:text/plain,x")));
}
#[test]
fn images_follow_the_site_answer_then_the_default() {
let mut settings = Settings::default();
let mut permissions = Permissions::load(std::path::PathBuf::from("/nonexistent/permissions.json"), true);
assert!(!HubConfig::from_settings(&settings, &permissions, "", Vec::new()).images_blocked("a.example"));
permissions.set("a.example", Kind::Images, Some(Decision::Block));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && !config.images_blocked("b.example"));
settings.privacy.permission_defaults.insert("images".into(), crate::store::settings::PermissionDefault::Block);
permissions.set("b.example", Kind::Images, Some(Decision::Allow));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && config.images_blocked("c.example") && !config.images_blocked("b.example"));
}
#[test]
fn strips_tracking() {
let u = Url::parse("https://a.example/p?id=3&utm_source=x&fbclid=y").unwrap();
assert_eq!(strip_tracking(&u).unwrap().as_str(), "https://a.example/p?id=3");
let u = Url::parse("https://a.example/p?utm_medium=x").unwrap();
assert_eq!(strip_tracking(&u).unwrap().as_str(), "https://a.example/p");
assert!(strip_tracking(&Url::parse("https://a.example/p?q=1").unwrap()).is_none());
}
}