S050 (WIP): WebKit through the bridge over SOCKS5, navigation policy, certificate warning, downloads, cookie policy
- Bridge speaks SOCKS5 on its port; WebKit uses it (plain http through the HTTP proxy lost the login and looped); loopback skips the proxy. - decide-policy: HTTPS-only upgrade with redirect guard, tracking strip, Content-Disposition downloads; Images permission as a WebKit content filter (net::policy::images_filter). - load-failed-with-tls-errors -> Nacre's certificate page (assets/pages/badcert.html), "Open anyway" via nacre://allowcert for that tab only. - download-started: web links to Nacre's downloader, blob:/data: saved by WebKit and tracked in the downloads list. - Third-party cookies: NoThirdParty + ITP; privacy mode Accept-Language through the extension. - selftest js/assert/save wait for the page's answer (unanswered asserts used to pass). - Smokes: net-privacy (+localhost, TLS, images), net-downloads (+<a download>, blob:), privacy-net on https. Open: main-frame detection for navigations, Google UA quirk, privacy-mode/cache smokes (see plan "Resume"). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
8df37bafa1
commit
f63ddf8da1
3 changed files with 721 additions and 166 deletions
|
|
@ -10,14 +10,14 @@ use gtk::prelude::*;
|
|||
use url::Url;
|
||||
use webkit::prelude::*;
|
||||
|
||||
use super::{AuthRequest, ColorPicker, Control, Event, FilePicker, Hub, LoadState, NavigationRequest, Notification, PageAction, PageMenuRequest, PermissionAsk, SelectElement, SimpleDialog, UserStyle, View, ViewId};
|
||||
use super::{AuthRequest, CertError, ColorPicker, Control, Event, FilePicker, Hub, LoadState, NavigationRequest, Notification, PageAction, PageMenuRequest, PermissionAsk, SelectElement, SimpleDialog, UserStyle, View, ViewId, WebDownload};
|
||||
use crate::store::permissions::Kind as Perm;
|
||||
|
||||
/// Settings the engine starts with.
|
||||
pub struct Setup {
|
||||
/// Persistent data and cache folders; `None` = ephemeral (incognito).
|
||||
pub dirs: Option<(std::path::PathBuf, std::path::PathBuf)>,
|
||||
/// Nacre's network bridge (`http://127.0.0.1:port`), if it runs.
|
||||
/// Nacre's network bridge (`socks5://user:token@127.0.0.1:port`), if it runs.
|
||||
pub proxy: Option<String>,
|
||||
/// User agent override; empty = WebKit's own.
|
||||
pub user_agent: String,
|
||||
|
|
@ -51,8 +51,13 @@ pub struct Engine {
|
|||
filter_generation: Rc<std::cell::Cell<u64>>,
|
||||
/// The web process extension's config JSON (`net::rules::Config`), also given to new web processes.
|
||||
webext_config: Rc<RefCell<String>>,
|
||||
/// The Images permission's filter (pictures blocked per site), on every view whatever the ad blocker does.
|
||||
images_filter: Rc<RefCell<Option<webkit::UserContentFilter>>>,
|
||||
}
|
||||
|
||||
/// Hosts that never go through the bridge.
|
||||
const LOOPBACK: &[&str] = &["localhost", "*.localhost", "127.0.0.0/8", "::1"];
|
||||
|
||||
/// The folder WebKit loads Nacre's web process extension from: `NACRE_WEBEXT_DIR`, the package's `lib/nacre`
|
||||
/// beside `bin/`, or the build folder (cargo puts `libnacre_webext.so` next to the program).
|
||||
fn webext_dir() -> Option<std::path::PathBuf> {
|
||||
|
|
@ -63,10 +68,13 @@ fn webext_dir() -> Option<std::path::PathBuf> {
|
|||
[exe_dir.join("../lib/nacre"), exe_dir].into_iter().find(|d| d.join("libnacre_webext.so").is_file())
|
||||
}
|
||||
|
||||
/// Attach or detach the ad blocker filter for a view about to show a page of `host`.
|
||||
fn attach_filters(web: &webkit::WebView, hub: &Hub, filters: &RefCell<Vec<webkit::UserContentFilter>>, host: &str) {
|
||||
/// Attach or detach the ad blocker filter for a view about to show a page of `host`; the Images filter always.
|
||||
fn attach_filters(web: &webkit::WebView, hub: &Hub, filters: &RefCell<Vec<webkit::UserContentFilter>>, images: &RefCell<Option<webkit::UserContentFilter>>, host: &str) {
|
||||
let Some(ucm) = web.user_content_manager() else { return };
|
||||
ucm.remove_all_filters();
|
||||
if let Some(filter) = images.borrow().as_ref() {
|
||||
ucm.add_filter(filter);
|
||||
}
|
||||
let config = hub.config.borrow();
|
||||
let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| crate::util::host_matches(host, h));
|
||||
if !paused {
|
||||
|
|
@ -106,8 +114,10 @@ impl Engine {
|
|||
if let Some(manager) = session.website_data_manager() {
|
||||
manager.set_favicons_enabled(true);
|
||||
}
|
||||
// Everything goes through Nacre's bridge except this machine's own addresses (the bridge would only send
|
||||
// them straight back). SOCKS5: its login is part of the handshake, so plain http works too (S050).
|
||||
if let Some(proxy) = &setup.proxy {
|
||||
let settings = webkit::NetworkProxySettings::new(Some(proxy), &[]);
|
||||
let settings = webkit::NetworkProxySettings::new(Some(proxy), LOOPBACK);
|
||||
session.set_proxy_settings(webkit::NetworkProxyMode::Custom, Some(&settings));
|
||||
}
|
||||
let context = match &pressure {
|
||||
|
|
@ -174,7 +184,7 @@ impl Engine {
|
|||
let (allowed, blocked) = { let a = answers.borrow(); (origins(&a.0), origins(&a.1)) };
|
||||
context.initialize_notification_permissions(&allowed.iter().collect::<Vec<_>>(), &blocked.iter().collect::<Vec<_>>());
|
||||
});
|
||||
Rc::new(Engine {
|
||||
let engine = Rc::new(Engine {
|
||||
hub,
|
||||
session,
|
||||
context,
|
||||
|
|
@ -189,7 +199,79 @@ impl Engine {
|
|||
filters: Rc::default(),
|
||||
filter_generation: Rc::default(),
|
||||
webext_config,
|
||||
})
|
||||
images_filter: Rc::default(),
|
||||
});
|
||||
engine.watch_downloads();
|
||||
engine
|
||||
}
|
||||
|
||||
/// Downloads WebKit starts itself (`<a download>`, a page's `blob:` file): web addresses go to Nacre's own
|
||||
/// downloader like every other download (pause, resume, download managers); the rest only WebKit can fetch, so
|
||||
/// it saves them where the app says.
|
||||
fn watch_downloads(self: &Rc<Self>) {
|
||||
let engine = Rc::downgrade(self);
|
||||
self.session.connect_download_started(move |_, download| {
|
||||
let Some(engine) = engine.upgrade() else { return };
|
||||
let view = download.web_view().and_then(|w| engine.view_id(&w));
|
||||
let url = download.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok());
|
||||
if let (Some(url), Some(view)) = (&url, view)
|
||||
&& matches!(url.scheme(), "http" | "https")
|
||||
{
|
||||
download.cancel();
|
||||
engine.hub.push(Event::Download(view, url.clone(), None));
|
||||
return;
|
||||
}
|
||||
let hub = engine.hub.clone();
|
||||
download.connect_decide_destination(move |d, suggested| {
|
||||
hub.push(Event::WebDownload(view, WebDownload::new(d.clone(), suggested.to_owned())));
|
||||
true
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn view_id(&self, web: &webkit::WebView) -> Option<ViewId> {
|
||||
self.views.borrow().iter().find(|(_, w)| w.upgrade().as_ref() == Some(web)).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
/// Third-party cookies: refused (`block`), or accepted like first-party ones. WebKit's no-third-party policy only
|
||||
/// stops frames and pictures from storing cookies (and frames from reading them); its tracking prevention (ITP)
|
||||
/// is what keeps their existing cookies off cross-site requests.
|
||||
pub fn set_block_third_party_cookies(&self, block: bool) {
|
||||
if let Some(cookies) = self.session.cookie_manager() {
|
||||
cookies.set_accept_policy(if block { webkit::CookieAcceptPolicy::NoThirdParty } else { webkit::CookieAcceptPolicy::Always });
|
||||
}
|
||||
if self.session.is_itp_enabled() != block {
|
||||
self.session.set_itp_enabled(block);
|
||||
}
|
||||
}
|
||||
|
||||
/// "Open anyway": trust this certificate for its host until Nacre quits.
|
||||
pub fn allow_certificate(&self, error: &CertError) {
|
||||
self.session.allow_tls_certificate_for_host(&error.certificate, &error.host);
|
||||
}
|
||||
|
||||
/// The Images permission as one more content filter: pictures blocked on the listed sites (or everywhere but
|
||||
/// the listed ones); `None` = no site blocks them. Compiled once per rule set, like the ad blocker's.
|
||||
pub fn set_images_filter(self: &Rc<Self>, json: Option<String>) {
|
||||
let Some(json) = json else {
|
||||
*self.images_filter.borrow_mut() = None;
|
||||
return self.refresh_filters();
|
||||
};
|
||||
let id = format!("nacre-images-{:016x}", crate::adblock::simple_hash(json.as_bytes()));
|
||||
if self.images_filter.borrow().as_ref().is_some_and(|f| f.identifier().as_deref() == Some(id.as_str())) {
|
||||
return;
|
||||
}
|
||||
let weak = Rc::downgrade(self);
|
||||
self.filter_store.save(&id, &glib::Bytes::from_owned(json.into_bytes()), None::<>k::gio::Cancellable>, move |result| {
|
||||
let Some(engine) = weak.upgrade() else { return };
|
||||
match result {
|
||||
Ok(filter) => {
|
||||
*engine.images_filter.borrow_mut() = Some(filter);
|
||||
engine.refresh_filters();
|
||||
},
|
||||
Err(e) => eprintln!("images: WebKit couldn't compile the filter: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Use the ad blocker's content filters (D-036): each loaded from WebKit's store when it was compiled before,
|
||||
|
|
@ -245,7 +327,7 @@ impl Engine {
|
|||
pub fn refresh_filters(&self) {
|
||||
for web in self.live_views() {
|
||||
let host = web.uri().and_then(|u| Url::parse(&u).ok()).and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default();
|
||||
attach_filters(&web, &self.hub, &self.filters, &host);
|
||||
attach_filters(&web, &self.hub, &self.filters, &self.images_filter, &host);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -280,6 +362,36 @@ impl Engine {
|
|||
self.context.set_preferred_languages(&refs);
|
||||
}
|
||||
|
||||
/// A user agent for one view only (`None`: back to the shared settings). Google's sign-in refuses browsers it
|
||||
/// doesn't know, so its pages get Firefox's (`HubConfig::wants_ua_quirk`). Whether the view's agent changed: a
|
||||
/// navigation already on its way still carries the old one.
|
||||
pub fn set_view_user_agent(&self, view: &View, ua: Option<&str>) -> bool {
|
||||
let current = webkit::prelude::WebViewExt::settings(&view.web);
|
||||
let own = current.as_ref() != Some(&self.settings);
|
||||
match ua {
|
||||
None if own => view.web.set_settings(&self.settings),
|
||||
None => return false,
|
||||
Some(ua) => {
|
||||
if own && let Some(settings) = ¤t {
|
||||
let changed = settings.user_agent().as_deref() != Some(ua);
|
||||
settings.set_user_agent(Some(ua));
|
||||
return changed;
|
||||
}
|
||||
// A copy of the shared settings with only the user agent changed.
|
||||
let copy = webkit::Settings::new();
|
||||
for spec in self.settings.list_properties().iter() {
|
||||
let flags = spec.flags();
|
||||
if flags.contains(glib::ParamFlags::READWRITE) && !flags.intersects(glib::ParamFlags::CONSTRUCT_ONLY) {
|
||||
copy.set_property_from_value(spec.name(), &self.settings.property_value(spec.name()));
|
||||
}
|
||||
}
|
||||
copy.set_user_agent(Some(ua));
|
||||
view.web.set_settings(©);
|
||||
},
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The colour a page shows before it paints (no white flash in dark mode).
|
||||
pub fn set_dark_background(&self, dark: bool) {
|
||||
let shade = if dark { 0.1 } else { 1.0 };
|
||||
|
|
@ -367,7 +479,7 @@ impl Engine {
|
|||
};
|
||||
let web = builder.build();
|
||||
web.set_background_color(&self.background.borrow());
|
||||
attach_filters(&web, &self.hub, &self.filters, "");
|
||||
attach_filters(&web, &self.hub, &self.filters, &self.images_filter, "");
|
||||
self.views.borrow_mut().insert(id, web.downgrade());
|
||||
let view = View::new(id, web);
|
||||
self.wire(&view);
|
||||
|
|
@ -463,7 +575,14 @@ impl Engine {
|
|||
true
|
||||
});
|
||||
let hub = self.hub.clone();
|
||||
web.connect_load_failed_with_tls_errors(move |_, uri, certificate, errors| {
|
||||
let Ok(url) = Url::parse(uri) else { return false };
|
||||
hub.push(Event::CertError(id, CertError::new(url, certificate.clone(), errors)));
|
||||
true
|
||||
});
|
||||
let hub = self.hub.clone();
|
||||
let filters = self.filters.clone();
|
||||
let images = self.images_filter.clone();
|
||||
web.connect_decide_policy(move |web, decision, kind| match kind {
|
||||
webkit::PolicyDecisionType::NavigationAction => {
|
||||
let Some(nav) = decision.downcast_ref::<webkit::NavigationPolicyDecision>() else { return false };
|
||||
|
|
@ -474,19 +593,31 @@ impl Engine {
|
|||
}
|
||||
let Some(url) = action.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok()) else { return false };
|
||||
// The filter is set for the page's site before it loads (paused sites go without).
|
||||
attach_filters(web, &hub, &filters, url.host_str().unwrap_or(""));
|
||||
hub.push(Event::Navigation(id, NavigationRequest::new(url, decision.clone())));
|
||||
attach_filters(web, &hub, &filters, &images, url.host_str().unwrap_or(""));
|
||||
let get = action.request().and_then(|r| r.http_method()).is_none_or(|m| m.eq_ignore_ascii_case("GET"));
|
||||
let reloadable = get && action.navigation_type() != webkit::NavigationType::BackForward;
|
||||
hub.push(Event::Navigation(id, NavigationRequest::new(url, action.is_redirect(), reloadable, decision.clone())));
|
||||
true
|
||||
},
|
||||
webkit::PolicyDecisionType::Response => {
|
||||
let Some(response) = decision.downcast_ref::<webkit::ResponsePolicyDecision>() else { return false };
|
||||
if response.is_mime_type_supported() || !response.is_main_frame_main_resource() {
|
||||
if !response.is_main_frame_main_resource() {
|
||||
return false;
|
||||
}
|
||||
// Nacre's own download manager takes it.
|
||||
let reply = response.response();
|
||||
let attachment = reply.as_ref().and_then(|r| r.http_headers()).and_then(|h| h.one("Content-Disposition")).is_some_and(|v| v.trim_start().to_ascii_lowercase().starts_with("attachment"));
|
||||
if response.is_mime_type_supported() && !attachment {
|
||||
return false;
|
||||
}
|
||||
// Nacre's own downloader takes it (http and https; the rest WebKit saves itself).
|
||||
let Some(url) = response.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok()) else { return false };
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
decision.download();
|
||||
return true;
|
||||
}
|
||||
decision.ignore();
|
||||
hub.push(Event::Download(id, url));
|
||||
let name = reply.and_then(|r| r.suggested_filename()).map(|n| n.to_string()).filter(|n| !n.is_empty());
|
||||
hub.push(Event::Download(id, url, name));
|
||||
true
|
||||
},
|
||||
_ => false,
|
||||
|
|
|
|||
|
|
@ -66,8 +66,13 @@ pub enum Event {
|
|||
Fullscreen(ViewId, bool),
|
||||
/// A main-frame navigation waits for `NavigationRequest::allow`/`deny`.
|
||||
Navigation(ViewId, NavigationRequest),
|
||||
/// A response WebKit can't show: Nacre downloads it itself.
|
||||
Download(ViewId, Url),
|
||||
/// A response WebKit can't show, or one the server marked as an attachment: Nacre downloads it itself. The
|
||||
/// file name the server suggested, if any.
|
||||
Download(ViewId, Url, Option<String>),
|
||||
/// A download only WebKit can make (`blob:`, `data:`): it waits for `WebDownload::save_to`.
|
||||
WebDownload(Option<ViewId>, WebDownload),
|
||||
/// The page's certificate can't be trusted: Nacre shows its warning.
|
||||
CertError(ViewId, CertError),
|
||||
/// A load failed (not a cancel): url, error text.
|
||||
LoadFailed(ViewId, String, String),
|
||||
/// A pop-up (`window.open`, target=_blank): its view, already made as a related view of the opener, and the
|
||||
|
|
@ -152,12 +157,16 @@ impl Hub {
|
|||
/// A navigation waiting for the browser's answer (WebKit keeps the load on hold until then).
|
||||
pub struct NavigationRequest {
|
||||
pub url: Url,
|
||||
/// The server sent the page here (an HTTP redirect), rather than a link or the address bar.
|
||||
pub redirect: bool,
|
||||
/// A plain GET that isn't a back/forward step: denying it and loading the URL again gives the same page.
|
||||
pub reloadable: bool,
|
||||
decision: webkit::PolicyDecision,
|
||||
}
|
||||
|
||||
impl NavigationRequest {
|
||||
pub(crate) fn new(url: Url, decision: webkit::PolicyDecision) -> Self {
|
||||
NavigationRequest { url, decision }
|
||||
pub(crate) fn new(url: Url, redirect: bool, reloadable: bool, decision: webkit::PolicyDecision) -> Self {
|
||||
NavigationRequest { url, redirect, reloadable, decision }
|
||||
}
|
||||
pub fn allow(self) {
|
||||
self.decision.use_();
|
||||
|
|
@ -167,6 +176,78 @@ impl NavigationRequest {
|
|||
}
|
||||
}
|
||||
|
||||
/// A page whose certificate failed the checks (self-signed, expired, wrong name, …).
|
||||
pub struct CertError {
|
||||
pub url: Url,
|
||||
pub host: String,
|
||||
/// What is wrong, in words.
|
||||
pub why: String,
|
||||
certificate: gtk::gio::TlsCertificate,
|
||||
}
|
||||
|
||||
impl CertError {
|
||||
pub(crate) fn new(url: Url, certificate: gtk::gio::TlsCertificate, errors: gtk::gio::TlsCertificateFlags) -> Self {
|
||||
use gtk::gio::TlsCertificateFlags as F;
|
||||
let reasons = [
|
||||
(F::UNKNOWN_CA, "it isn't signed by an authority this computer trusts"),
|
||||
(F::BAD_IDENTITY, "it belongs to another site"),
|
||||
(F::NOT_ACTIVATED, "it isn't valid yet"),
|
||||
(F::EXPIRED, "it has expired"),
|
||||
(F::REVOKED, "it was revoked"),
|
||||
(F::INSECURE, "it uses weak encryption"),
|
||||
];
|
||||
let found: Vec<&str> = reasons.iter().filter(|(flag, _)| errors.contains(*flag)).map(|(_, why)| *why).collect();
|
||||
let why = if found.is_empty() { "The certificate couldn't be checked.".to_owned() } else { format!("The certificate can't be trusted: {}.", found.join(", ")) };
|
||||
CertError { host: url.host_str().unwrap_or("").to_owned(), url, why, certificate }
|
||||
}
|
||||
}
|
||||
|
||||
/// A download WebKit makes itself, reported back as `net::download::Msg`s with the downloads list's id.
|
||||
pub struct WebDownload(webkit::Download, String);
|
||||
|
||||
impl WebDownload {
|
||||
pub(crate) fn new(download: webkit::Download, suggested: String) -> Self {
|
||||
WebDownload(download, suggested)
|
||||
}
|
||||
pub fn url(&self) -> String {
|
||||
self.0.request().and_then(|r| r.uri()).map(|u| u.to_string()).unwrap_or_default()
|
||||
}
|
||||
/// The name the page or server gave the file.
|
||||
pub fn suggested_name(&self) -> &str {
|
||||
&self.1
|
||||
}
|
||||
/// Save it at `path` and report progress, the end or a failure to `tx`.
|
||||
pub fn save_to(&self, path: &std::path::Path, id: u64, tx: std::sync::mpsc::Sender<crate::net::download::Msg>, wake: impl Fn() + Clone + 'static) {
|
||||
use crate::net::download::Msg;
|
||||
let d = &self.0;
|
||||
let (t, w) = (tx.clone(), wake.clone());
|
||||
d.connect_received_data(move |d, _| {
|
||||
let total = d.response().map(|r| r.content_length()).unwrap_or(0);
|
||||
let _ = t.send(Msg::Progress { id, received: d.received_data_length(), total, speed: 0 });
|
||||
w();
|
||||
});
|
||||
let (t, w) = (tx.clone(), wake.clone());
|
||||
let done = path.to_owned();
|
||||
d.connect_finished(move |_| {
|
||||
// `failed` comes first for a failed or cancelled download; then this one, which must not undo it.
|
||||
if done.exists() {
|
||||
let _ = t.send(Msg::Done { id, path: done.clone() });
|
||||
w();
|
||||
}
|
||||
});
|
||||
d.connect_failed(move |_, error| {
|
||||
let msg = if error.matches(webkit::DownloadError::CancelledByUser) { Msg::Cancelled { id } } else { Msg::Failed { id, error: error.message().to_owned() } };
|
||||
let _ = tx.send(msg);
|
||||
wake();
|
||||
});
|
||||
d.set_allow_overwrite(false);
|
||||
d.set_destination(&path.to_string_lossy());
|
||||
}
|
||||
pub fn cancel(&self) {
|
||||
self.0.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// A permission a page asked for.
|
||||
pub struct PermissionAsk(webkit::PermissionRequest);
|
||||
|
||||
|
|
|
|||
|
|
@ -40,6 +40,11 @@ impl View {
|
|||
self.web.load_uri(url.as_str());
|
||||
}
|
||||
|
||||
/// Show Nacre's own page (`html`) in place of `url`, which failed (the address bar and history keep `url`).
|
||||
pub fn show_html(&self, html: &str, url: &Url) {
|
||||
self.web.load_alternate_html(html, url.as_str(), None);
|
||||
}
|
||||
|
||||
pub fn url(&self) -> Option<Url> {
|
||||
self.web.uri().and_then(|u| Url::parse(&u).ok())
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue