Nacre/webext/src/rules.rs

152 lines
6.1 KiB
Rust

//! What the web process extension does to each request, without any WebKit: the config the browser sends it, the
//! ad blocker's redirect rules and the tracking-parameter strip. Shared by the extension (`webext/`) and the
//! browser (`nacre::net::rules`, which builds the config and tests these).
use serde::{Deserialize, Serialize};
use url::Url;
/// Tracking parameters removed from links when "strip tracking parameters" is on.
pub 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",
];
pub const TRACKING_PREFIXES: &[&str] = &["utm_", "pk_", "mtm_", "hsa_"];
/// The URI scheme redirect rules point at; the browser serves the stand-ins (`adblock::resource`).
pub const RESOURCE_SCHEME: &str = "nacre-resource";
/// The user message the extension sends its page's view for each request the content filter blocked
/// (parameter: the blocked URL).
pub const BLOCKED_MESSAGE: &str = "nacre-blocked";
/// The user message that carries a new `Config` (parameter: its JSON) to every extension.
pub const CONFIG_MESSAGE: &str = "nacre-config";
/// The extension's settings, sent as JSON at web process start and on every change.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Config {
/// Added to every request (DNT, Sec-GPC, Save-Data).
#[serde(default)]
pub headers: Vec<(String, String)>,
/// Remove tracking parameters from sub-resource URLs.
#[serde(default)]
pub strip: bool,
/// The ad blocker is on (redirect rules apply).
#[serde(default)]
pub adblock: bool,
/// Sites the ad blocker is paused on (host suffixes).
#[serde(default)]
pub paused: Vec<String>,
#[serde(default)]
pub redirects: Vec<Redirect>,
}
/// An ad blocker rule that serves a harmless stand-in instead of blocking (`$redirect=noopjs`), in WebKit's
/// content-blocker terms (the trigger of the converted rule).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Redirect {
/// WebKit's url-filter regex (its small dialect, which `regex_lite` reads too).
pub url: String,
#[serde(default)]
pub case: bool,
/// Page hosts it applies to / not to; "*host" also covers subdomains.
#[serde(default)]
pub if_domain: Vec<String>,
#[serde(default)]
pub unless_domain: Vec<String>,
/// Some(true): only third-party requests; Some(false): only first-party.
#[serde(default)]
pub third_party: Option<bool>,
/// The stand-in's name (`noopjs`, `1x1.gif`, …).
pub resource: String,
}
/// Whether `host` is `domain` or below it.
pub fn host_matches(host: &str, domain: &str) -> bool {
host == domain || (host.len() > domain.len() && host.ends_with(domain) && host.as_bytes()[host.len() - domain.len() - 1] == b'.')
}
/// The last two labels of a host: a rough site for the third-party test (the extension has no public suffix list).
fn site(host: &str) -> &str {
let mut dots = host.rmatch_indices('.');
match (dots.next(), dots.next()) {
(Some(_), Some((i, _))) => &host[i + 1..],
_ => host,
}
}
fn domain_listed(list: &[String], host: &str) -> bool {
list.iter().any(|d| match d.strip_prefix('*') {
Some(d) => host_matches(host, d),
None => host == d,
})
}
/// Redirect rules with their regexes compiled once.
pub struct Redirects {
rules: Vec<(Redirect, regex_lite::Regex)>,
}
impl Redirects {
pub fn new(rules: &[Redirect]) -> Redirects {
let rules = rules
.iter()
.filter_map(|r| regex_lite::RegexBuilder::new(&r.url).case_insensitive(!r.case).build().ok().map(|re| (r.clone(), re)))
.collect();
Redirects { rules }
}
pub fn len(&self) -> usize {
self.rules.len()
}
/// The stand-in for this request on a page of `page_host`, if a rule takes it.
pub fn find(&self, url: &str, host: &str, page_host: &str) -> Option<&str> {
let third = site(host) != site(page_host);
self.rules
.iter()
.find(|(r, re)| {
r.third_party.is_none_or(|t| t == third)
&& (r.if_domain.is_empty() || domain_listed(&r.if_domain, page_host))
&& !domain_listed(&r.unless_domain, page_host)
&& re.is_match(url)
})
.map(|(r, _)| r.resource.as_str())
}
}
/// 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)
}
/// What the extension does with one request: the URL to load instead, if any.
pub fn rewrite(config: &Config, redirects: &Redirects, url: &str, page_url: &str) -> Option<String> {
let parsed = Url::parse(url).ok()?;
if !matches!(parsed.scheme(), "http" | "https") {
return None;
}
let host = parsed.host_str().unwrap_or("");
let page_host = Url::parse(page_url).ok().and_then(|u| u.host_str().map(str::to_owned)).unwrap_or_default();
if config.adblock
&& !page_host.is_empty()
&& !config.paused.iter().any(|p| host_matches(&page_host, p))
&& let Some(resource) = redirects.find(url, host, &page_host)
{
return Some(format!("{RESOURCE_SCHEME}:{resource}"));
}
if config.strip {
return strip_tracking(&parsed).map(String::from);
}
None
}