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]>
412 lines
17 KiB
Rust
412 lines
17 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::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,
|
|
pub user_agent: String,
|
|
/// Tabs where the user chose "open over http anyway" this session (host).
|
|
pub http_allowed: Vec<String>,
|
|
}
|
|
|
|
impl HubConfig {
|
|
pub fn from_settings(settings: &Settings, 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,
|
|
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>>,
|
|
}
|
|
|
|
/// 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_"];
|
|
|
|
/// 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),
|
|
})
|
|
}
|
|
|
|
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);
|
|
// The app resets the blocked count when the page starts loading (LoadStatus::Started).
|
|
if let Some(id) = id {
|
|
self.log_request(id, &method, url.as_str(), &kind, false);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Sub-resources: the ad blocker.
|
|
let page_url = page.as_ref().map(Url::as_str).unwrap_or("");
|
|
let page_host = util::host_of_str(page_url);
|
|
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 notify_url_changed(&self, webview: WebView, url: Url) {
|
|
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) {
|
|
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 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());
|
|
}
|
|
}
|