Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

feat: built-in ad and tracker blocking for runtime templates

Tw93793966578e89
diff --git a/filters/README.md b/filters/README.md
new file mode 100644
index 00000000..2a6eb3fa
--- /dev/null
+++ b/filters/README.md
@@ -0,0 +1,15 @@
+# Filter lists
+
+Runtime templates built with the `content-blocking` feature (which `runtime-template` turns on) embed these lists, unmodified and gzipped, for the `content_blocking` groups in `pake.json`. The npm package does not ship this folder, and the CLI never enables the feature.
+
+| Group | List | Authors | License |
+| --- | --- | --- | --- |
+| `ads` | EasyList | The EasyList authors (https://easylist.to/) | GPL-3.0-or-later or CC BY-SA 3.0 (https://easylist.to/pages/licence.html) |
+| `trackers` | EasyPrivacy | The EasyList authors (https://easylist.to/) | GPL-3.0-or-later or CC BY-SA 3.0 (https://easylist.to/pages/licence.html) |
+| `cookies` | AdGuard Cookie Notices filter | AdGuard (https://github.com/AdguardTeam/AdguardFilters) | GPL-3.0 |
+| `china` | EasyList China | The EasyList China authors (https://github.com/easylist/easylistchina) | GPL-3.0-or-later or CC BY-SA 3.0 (https://easylist.to/pages/licence.html) |
+| always | uBlock filters – Unbreak | uBlock Origin contributors (https://github.com/uBlockOrigin/uAssets) | GPL-3.0 |
+
+`sources.json` records each list's download URL, version and date. Refresh them with `node scripts/update-filter-lists.mjs` before a runtime release; `cargo test --features content-blocking content_blocking` then checks that every list unpacks and that all groups together still fit WebKit's 150,000-rule limit.
+
+The lists are matched by Brave's adblock-rust (https://github.com/brave/adblock-rust, MPL-2.0).
diff --git a/filters/ads.txt.gz b/filters/ads.txt.gz
new file mode 100644
index 00000000..f16e308f
Binary files /dev/null and b/filters/ads.txt.gz differ
diff --git a/filters/china.txt.gz b/filters/china.txt.gz
new file mode 100644
index 00000000..527562d1
Binary files /dev/null and b/filters/china.txt.gz differ
diff --git a/filters/cookies.txt.gz b/filters/cookies.txt.gz
new file mode 100644
index 00000000..7266356d
Binary files /dev/null and b/filters/cookies.txt.gz differ
diff --git a/filters/sources.json b/filters/sources.json
new file mode 100644
index 00000000..ab655e24
--- /dev/null
+++ b/filters/sources.json
@@ -0,0 +1,45 @@
+{
+ "fetched": "2026-11-15",
+ "lists": [
+ {
+ "group": "ads",
+ "title": "EasyList",
+ "version": "202611150427",
+ "url": "https://easylist.to/easylist/easylist.txt",
+ "license": "https://easylist.to/pages/licence.html",
+ "lines": 78503
+ },
+ {
+ "group": "trackers",
+ "title": "EasyPrivacy",
+ "version": "202611150427",
+ "url": "https://easylist.to/easylist/easyprivacy.txt",
+ "license": "https://easylist.to/pages/licence.html",
+ "lines": 57428
+ },
+ {
+ "group": "cookies",
+ "title": "AdGuard Cookie Notices filter",
+ "version": "2.0.99.53",
+ "url": "https://filters.adtidy.org/extension/ublock/filters/18.txt",
+ "license": "https://github.com/AdguardTeam/AdguardFilters/blob/master/LICENSE",
+ "lines": 23869
+ },
+ {
+ "group": "china",
+ "title": "EasyList China",
+ "version": "202611150422",
+ "url": "https://easylist-downloads.adblockplus.org/easylistchina.txt",
+ "license": "https://easylist.to/pages/licence.html",
+ "lines": 17961
+ },
+ {
+ "group": "unbreak",
+ "title": "uBlock filters – Unbreak",
+ "version": "Sat, 14 Nov 2026 04:57:45 +0000",
+ "url": "https://ublockorigin.github.io/uAssets/filters/unbreak.txt",
+ "license": "https://github.com/uBlockOrigin/uAssets/blob/master/LICENSE",
+ "lines": 6116
+ }
+ ]
+}
diff --git a/filters/trackers.txt.gz b/filters/trackers.txt.gz
new file mode 100644
index 00000000..057f41e1
Binary files /dev/null and b/filters/trackers.txt.gz differ
diff --git a/filters/unbreak.txt.gz b/filters/unbreak.txt.gz
new file mode 100644
index 00000000..19ea6fd5
Binary files /dev/null and b/filters/unbreak.txt.gz differ
diff --git a/scripts/update-filter-lists.mjs b/scripts/update-filter-lists.mjs
new file mode 100644
index 00000000..db6c6fd5
--- /dev/null
+++ b/scripts/update-filter-lists.mjs
@@ -0,0 +1,63 @@
+#!/usr/bin/env node
+// Downloads the filter lists that runtime templates built with the
+// `content-blocking` feature embed, and stores them gzipped under filters/.
+// Run it before a runtime release; the lists age within days of a download.
+import { gzipSync } from 'node:zlib';
+import { writeFileSync, mkdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..');
+const out = join(root, 'filters');
+
+// Group names are the values of `content_blocking` in pake.json.
+export const LISTS = [
+ { file: 'ads', url: 'https://easylist.to/easylist/easylist.txt' },
+ { file: 'trackers', url: 'https://easylist.to/easylist/easyprivacy.txt' },
+ {
+ file: 'cookies',
+ url: 'https://filters.adtidy.org/extension/ublock/filters/18.txt',
+ },
+ {
+ file: 'china',
+ url: 'https://easylist-downloads.adblockplus.org/easylistchina.txt',
+ },
+ // Always added to any selection: fixes for sites the other lists break.
+ {
+ file: 'unbreak',
+ url: 'https://ublockorigin.github.io/uAssets/filters/unbreak.txt',
+ },
+];
+
+function header(text, key) {
+ const line = text
+ .split('\n', 40)
+ .find((l) => l.toLowerCase().startsWith(`! ${key.toLowerCase()}:`));
+ return line ? line.slice(line.indexOf(':') + 1).trim() : '';
+}
+
+mkdirSync(out, { recursive: true });
+const sources = [];
+for (const { file, url } of LISTS) {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
+ const text = await response.text();
+ if (!text.includes('##') && !text.includes('||')) {
+ throw new Error(`${url} does not look like a filter list`);
+ }
+ // mtime 0 keeps the gzip bytes stable for the same text.
+ writeFileSync(join(out, `${file}.txt.gz`), gzipSync(text, { level: 9 }));
+ sources.push({
+ group: file,
+ title: header(text, 'Title'),
+ version: header(text, 'Version') || header(text, 'Last modified'),
+ url,
+ license: header(text, 'Licence') || header(text, 'License'),
+ lines: text.split('\n').length,
+ });
+ console.log(`${file}: ${text.length} bytes`);
+}
+writeFileSync(
+ join(out, 'sources.json'),
+ JSON.stringify({ fetched: new Date().toISOString().slice(0, 10), lists: sources }, null, 2) + '\n',
+);
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index f8a9a77c..312d280a 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2,6 +2,39 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "adblock"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a4c8558f27608dec74695c866f9a8ef897ec7a77cb826f8a5baf0b8ba461d2a"
+dependencies = [
+ "addr",
+ "arrayvec",
+ "base64 0.22.1",
+ "bitflags 2.11.0",
+ "flatbuffers",
+ "idna",
+ "itertools",
+ "memchr",
+ "percent-encoding",
+ "regex",
+ "rustc-hash",
+ "seahash",
+ "serde",
+ "serde_json",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "addr"
+version = "0.15.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a93b8a41dbe230ad5087cc721f8d41611de654542180586b315d9f4cf6b72bef"
+dependencies = [
+ "psl",
+ "psl-types",
+]
+
[[package]]
name = "adler2"
version = "2.0.1"
@@ -47,6 +80,12 @@ version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -767,7 +806,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
- "windows-sys 0.59.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -865,6 +904,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+[[package]]
+name = "either"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+
[[package]]
name = "embed-resource"
version = "3.0.6"
@@ -945,7 +990,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.59.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1000,6 +1045,16 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+[[package]]
+name = "flatbuffers"
+version = "25.12.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3"
+dependencies = [
+ "bitflags 2.11.0",
+ "rustc_version",
+]
+
[[package]]
name = "flate2"
version = "1.1.9"
@@ -1905,6 +1960,15 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.17"
@@ -2580,15 +2644,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
- "windows-sys 0.45.0",
+ "windows-sys 0.61.2",
]
[[package]]
name = "pake"
version = "3.19.0"
dependencies = [
+ "adblock",
"block2",
"dispatch",
+ "flate2",
"gtk",
"objc2",
"objc2-app-kit",
@@ -2608,6 +2674,7 @@ dependencies = [
"tauri-plugin-window-state",
"tokio",
"webkit2gtk",
+ "webkit2gtk-sys",
"webview2-com",
"windows-core 0.61.2",
"windows-sys 0.61.2",
@@ -3004,6 +3071,15 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "psl"
+version = "2.1.254"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb958e602bc5c9e07a3bdb78ce240402a490cd08f01e51deacfe637ed903d743"
+dependencies = [
+ "psl-types",
+]
+
[[package]]
name = "psl-types"
version = "2.0.11"
@@ -3091,7 +3167,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
- "windows-sys 0.59.0",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -3436,7 +3512,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
- "windows-sys 0.59.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -3552,6 +3628,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "seahash"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
+
[[package]]
name = "selectors"
version = "0.24.0"
@@ -4506,7 +4588,7 @@ dependencies = [
"getrandom 0.4.1",
"once_cell",
"rustix",
- "windows-sys 0.59.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -5320,7 +5402,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.59.0",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index ac0703ca..8e3d6a14 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -21,6 +21,14 @@ tauri-build = { version = "2.5.5", features = [] }
serde_json = "1.0.149"
serde = { version = "1.0.228", features = ["derive"] }
tokio = { version = "1.49.0", features = ["time", "fs"] }
+# Content blocking (feature `content-blocking`): Brave's filter engine, MPL-2.0.
+# Without single-thread its Engine is Send + Sync for the WebView2 handler.
+adblock = { version = "0.13.5", default-features = false, features = [
+ "content-blocking",
+ "embedded-domain-resolver",
+ "full-regex-handling",
+], optional = true }
+flate2 = { version = "1.1", optional = true }
tauri = { version = "2.10.2", features = [
"tray-icon",
"image-ico",
@@ -42,12 +50,17 @@ objc2 = "0.6"
objc2-app-kit = { version = "0.3", features = ["NSApplication", "NSDockTile", "NSWindow"] }
objc2-foundation = { version = "0.3", features = [
"NSArray",
+ "NSEnumerator",
+ "NSError",
"NSLocale",
"NSString",
"NSUserNotification",
] }
objc2-web-kit = { version = "0.3", default-features = false, features = [
"std",
+ "block2",
+ "WKContentRuleList",
+ "WKContentRuleListStore",
"WKUserContentController",
"WKWebViewConfiguration",
] }
@@ -63,6 +76,8 @@ gtk = "0.18"
# Reads the freedesktop color-scheme from the settings portal. Same version
# and features that tauri-plugin-opener and single-instance already lock.
zbus = "5.14"
+# WebKitGTK's content filter store, which the safe webkit2gtk crate leaves out.
+webkit2gtk-sys = { version = "=2.0.2", features = ["v2_40"], optional = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = [
@@ -84,7 +99,10 @@ native-download-probe = []
cli-build = []
# Prebuilt template that reads a pake-runtime folder at launch: Contents/Resources
# on macOS, next to the executable elsewhere. The CLI never enables it.
-runtime-template = []
+runtime-template = ["content-blocking"]
+# Ad, tracker and cookie-notice blocking with the lists in ../filters, which the
+# npm package does not ship; the CLI never enables it.
+content-blocking = ["dep:adblock", "dep:flate2", "dep:webkit2gtk-sys"]
# Tauri's macOS proxy APIs require macOS 14 or later. The CLI enables this
# feature only after checking the host Darwin version.
macos-proxy = ["tauri/macos-proxy"]
diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rs
index 644d3cc4..3aa6b311 100644
--- a/src-tauri/src/app/config.rs
+++ b/src-tauri/src/app/config.rs
@@ -133,6 +133,10 @@ pub struct PakeConfig {
/// login item in step at every start (see `autostart.rs`).
#[serde(default)]
pub launch_at_login: bool,
+ /// Built-in filter lists to block with: `ads`, `trackers`, `cookies`,
+ /// `china`. Only builds with the `content-blocking` feature read it.
+ #[serde(default)]
+ pub content_blocking: Vec<String>,
/// Replaces the compiled custom.js when a runtime override supplies one.
#[serde(skip)]
pub runtime_custom_js: Option<String>,
diff --git a/src-tauri/src/app/content_blocking.rs b/src-tauri/src/app/content_blocking.rs
new file mode 100644
index 00000000..f60c0a72
--- /dev/null
+++ b/src-tauri/src/app/content_blocking.rs
@@ -0,0 +1,881 @@
+//! Blocks ads, trackers and cookie notices with filter lists built into the
+//! runtime (the `content-blocking` feature, which `runtime-template` turns on).
+//!
+//! `content_blocking` in pake.json names the groups; none means off. macOS and
+//! Linux hand WebKit content rule lists converted from the filters, Windows
+//! matches each WebView2 request in process. Blocking fails open: an app whose
+//! lists cannot load runs unblocked and logs one line.
+
+use adblock::lists::{FilterSet, ParseOptions, RuleTypes};
+use std::io::Read;
+
+macro_rules! filter_list {
+ ($name:literal) => {
+ include_bytes!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../filters/",
+ $name,
+ ".txt.gz"
+ ))
+ };
+}
+
+/// The groups pake.json may name, in the order they are applied. The sources
+/// and licences of each list are in `filters/sources.json`.
+const GROUPS: [(&str, &[u8]); 4] = [
+ ("ads", filter_list!("ads")),
+ ("trackers", filter_list!("trackers")),
+ ("cookies", filter_list!("cookies")),
+ ("china", filter_list!("china")),
+];
+
+/// Fixes for sites the other lists break, added to every selection.
+const UNBREAK: &[u8] = filter_list!("unbreak");
+
+/// The known groups among `names`, in `GROUPS` order and without duplicates.
+pub fn selected_groups(names: &[String]) -> Vec<&'static str> {
+ GROUPS
+ .iter()
+ .map(|(group, _)| *group)
+ .filter(|group| names.iter().any(|name| name.trim() == *group))
+ .collect()
+}
+
+fn list_bytes(groups: &[&str]) -> Vec<&'static [u8]> {
+ GROUPS
+ .iter()
+ .filter(|(group, _)| groups.contains(group))
+ .map(|(_, bytes)| *bytes)
+ .chain(std::iter::once(UNBREAK))
+ .collect()
+}
+
+fn gunzip(bytes: &[u8]) -> Option<String> {
+ let mut text = String::new();
+ flate2::read::GzDecoder::new(bytes)
+ .read_to_string(&mut text)
+ .ok()?;
+ Some(text)
+}
+
+fn filter_set(groups: &[&str], rule_types: RuleTypes, debug: bool) -> FilterSet {
+ let mut set = FilterSet::new(debug);
+ for bytes in list_bytes(groups) {
+ match gunzip(bytes) {
+ Some(text) => {
+ set.add_filter_list(
+ text,
+ ParseOptions {
+ rule_types,
+ ..ParseOptions::default()
+ },
+ );
+ }
+ None => eprintln!("[Pake] A built-in filter list could not be read"),
+ }
+ }
+ set
+}
+
+/// FNV-1a, enough to tell one selection of embedded lists from another.
+#[cfg(any(target_os = "macos", target_os = "linux", test))]
+fn fingerprint(groups: &[&str]) -> u64 {
+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
+ let mut feed = |bytes: &[u8]| {
+ for byte in bytes {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ };
+ feed(env!("CARGO_PKG_VERSION").as_bytes());
+ for group in groups {
+ feed(group.as_bytes());
+ }
+ for bytes in list_bytes(groups) {
+ feed(bytes);
+ }
+ hash
+}
+
+/// WebKit compiles at most this many rules into one content rule list.
+#[cfg(any(target_os = "macos", target_os = "linux", test))]
+pub const WEBKIT_MAX_RULES: usize = 150_000;
+
+/// Each selection becomes two WebKit lists: requests to block with their
+/// exceptions, and elements to hide. `ignore-previous-rules` only reaches rules
+/// of its own list, so every list carries its own exceptions.
+#[cfg(any(target_os = "macos", target_os = "linux", test))]
+const WEBKIT_UNITS: [(&str, RuleTypes); 2] = [
+ ("network", RuleTypes::NetworkOnly),
+ ("cosmetic", RuleTypes::CosmeticOnly),
+];
+
+/// Identifiers start with this, so lists from older selections can be removed.
+#[cfg(any(target_os = "macos", target_os = "linux", test))]
+const IDENTIFIER_PREFIX: &str = "pake-blocking-";
+
+#[cfg(any(target_os = "macos", target_os = "linux", test))]
+fn webkit_identifier(groups: &[&str], unit: &str) -> String {
+ format!("{IDENTIFIER_PREFIX}{unit}-{:016x}", fingerprint(groups))
+}
+
+/// The rules of one WebKit unit, ready to serialize.
+#[cfg(any(target_os = "macos", target_os = "linux", test))]
+fn webkit_rules(groups: &[&str], rule_types: RuleTypes) -> Vec<adblock::content_blocking::CbRule> {
+ filter_set(groups, rule_types, true)
+ .into_content_blocking()
+ .map(|(rules, _)| rules)
+ .unwrap_or_default()
+}
+
+/// The JSON of one WebKit unit, or `None` when it has no rules or is too large.
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+fn webkit_json(groups: &[&str], unit: &str) -> Option<String> {
+ let rule_types = WEBKIT_UNITS
+ .iter()
+ .find(|(name, _)| *name == unit)
+ .map(|(_, types)| *types)?;
+ let rules = webkit_rules(groups, rule_types);
+ if rules.is_empty() || rules.len() > WEBKIT_MAX_RULES {
+ eprintln!(
+ "[Pake] Content blocking skipped the {unit} list: {} rules",
+ rules.len()
+ );
+ return None;
+ }
+ serde_json::to_string(&rules).ok()
+}
+
+/// Shared by macOS and Linux: look up compiled lists by identifier, convert and
+/// compile the ones missing, then add them to every webview's content manager.
+/// Everything here runs on the main thread except the conversion.
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+mod loader {
+ use super::platform::{add, compile, lookup, remove_stale, to_main, List, Target};
+ use super::{webkit_identifier, webkit_json, WEBKIT_UNITS};
+ use std::cell::RefCell;
+ use std::time::Duration;
+
+ /// How long the first page waits for the lists before it loads unblocked.
+ const READY_TIMEOUT: Duration = Duration::from_secs(10);
+
+ type Callback = Box<dyn FnOnce()>;
+
+ #[derive(Default)]
+ struct State {
+ started: bool,
+ ready: Option<Vec<List>>,
+ found: Vec<Option<List>>,
+ pending: usize,
+ waiting: Vec<Target>,
+ callbacks: Vec<Callback>,
+ }
+
+ thread_local! {
+ static STATE: RefCell<State> = RefCell::new(State::default());
+ }
+
+ /// Adds the lists to `target` now, or once they load.
+ pub fn attach(target: Target, groups: Vec<&'static str>) {
+ let first = STATE.with_borrow_mut(|state| {
+ if let Some(lists) = &state.ready {
+ for list in lists {
+ add(&target, list);
+ }
+ return false;
+ }
+ state.waiting.push(target);
+ !std::mem::replace(&mut state.started, true)
+ });
+ if first {
+ load(groups);
+ }
+ }
+
+ /// Runs `callback` once the lists are in place, or after `READY_TIMEOUT`
+ /// when loading takes longer, so a first page never waits for good.
+ pub fn when_ready(callback: Callback) {
+ let ready = STATE.with_borrow_mut(|state| {
+ if state.ready.is_some() {
+ return Some(callback);
+ }
+ state.callbacks.push(callback);
+ None
+ });
+ if let Some(callback) = ready {
+ callback();
+ return;
+ }
+ std::thread::spawn(|| {
+ std::thread::sleep(READY_TIMEOUT);
+ to_main(Box::new(|| {
+ let late = STATE.with_borrow_mut(|state| std::mem::take(&mut state.callbacks));
+ if !late.is_empty() {
+ eprintln!(
+ "[Pake] Content blocking is still loading; opening the page without it"
+ );
+ }
+ late.into_iter().for_each(|callback| callback());
+ }));
+ });
+ }
+
+ fn load(groups: Vec<&'static str>) {
+ let ids: Vec<String> = WEBKIT_UNITS
+ .iter()
+ .map(|(unit, _)| webkit_identifier(&groups, unit))
+ .collect();
+ STATE.with_borrow_mut(|state| {
+ state.found = ids.iter().map(|_| None).collect();
+ state.pending = ids.len();
+ });
+ for (index, id) in ids.iter().enumerate() {
+ let groups = groups.clone();
+ let ids = ids.clone();
+ lookup(
+ id,
+ Box::new(move |list| {
+ let done = STATE.with_borrow_mut(|state| {
+ state.found[index] = list;
+ state.pending -= 1;
+ state.pending == 0
+ });
+ if done {
+ compile_missing(groups, ids);
+ }
+ }),
+ );
+ }
+ }
+
+ fn compile_missing(groups: Vec<&'static str>, ids: Vec<String>) {
+ let missing: Vec<usize> = STATE.with_borrow(|state| {
+ (0..state.found.len())
+ .filter(|index| state.found[*index].is_none())
+ .collect()
+ });
+ if missing.is_empty() {
+ finish(ids);
+ return;
+ }
+ // Converting the lists takes a few hundred milliseconds; keep it off the main thread.
+ std::thread::spawn(move || {
+ let jsons: Vec<(usize, Option<String>)> = missing
+ .into_iter()
+ .map(|index| (index, webkit_json(&groups, WEBKIT_UNITS[index].0)))
+ .collect();
+ to_main(Box::new(move || {
+ let compiling: Vec<(usize, String)> = jsons
+ .into_iter()
+ .filter_map(|(index, json)| json.map(|json| (index, json)))
+ .collect();
+ if compiling.is_empty() {
+ finish(ids);
+ return;
+ }
+ STATE.with_borrow_mut(|state| state.pending = compiling.len());
+ for (index, json) in compiling {
+ let ids_after = ids.clone();
+ compile(
+ &ids[index],
+ json,
+ Box::new(move |list| {
+ let done = STATE.with_borrow_mut(|state| {
+ state.found[index] = list;
+ state.pending -= 1;
+ state.pending == 0
+ });
+ if done {
+ finish(ids_after);
+ }
+ }),
+ );
+ }
+ }));
+ });
+ }
+
+ fn finish(ids: Vec<String>) {
+ let callbacks = STATE.with_borrow_mut(|state| {
+ let lists: Vec<List> = state.found.drain(..).flatten().collect();
+ for target in state.waiting.drain(..) {
+ for list in &lists {
+ add(&target, list);
+ }
+ }
+ state.ready = Some(lists);
+ std::mem::take(&mut state.callbacks)
+ });
+ callbacks.into_iter().for_each(|callback| callback());
+ remove_stale(ids);
+ }
+}
+
+#[cfg(target_os = "macos")]
+mod platform {
+ use super::IDENTIFIER_PREFIX;
+ use block2::RcBlock;
+ use objc2::rc::Retained;
+ use objc2::MainThreadMarker;
+ use objc2_foundation::{NSArray, NSError, NSString};
+ use objc2_web_kit::{WKContentRuleList, WKContentRuleListStore, WKUserContentController};
+ use std::cell::Cell;
+
+ pub type Target = Retained<WKUserContentController>;
+ pub type List = Retained<WKContentRuleList>;
+ type Done = Box<dyn FnOnce(Option<List>)>;
+
+ fn store() -> Option<Retained<WKContentRuleListStore>> {
+ let mtm = MainThreadMarker::new()?;
+ unsafe { WKContentRuleListStore::defaultStore(mtm) }
+ }
+
+ fn completion(
+ id: String,
+ report: bool,
+ done: Done,
+ ) -> RcBlock<dyn Fn(*mut WKContentRuleList, *mut NSError)> {
+ let done = Cell::new(Some(done));
+ RcBlock::new(move |list: *mut WKContentRuleList, error: *mut NSError| {
+ let list = unsafe { Retained::retain(list) };
+ if report && list.is_none() {
+ let reason = unsafe { error.as_ref() }
+ .map(|error| error.localizedDescription().to_string())
+ .unwrap_or_default();
+ eprintln!("[Pake] Content blocking could not compile {id}: {reason}");
+ }
+ if let Some(done) = done.take() {
+ done(list);
+ }
+ })
+ }
+
+ pub fn lookup(id: &str, done: Done) {
+ let Some(store) = store() else {
+ return done(None);
+ };
+ let block = completion(id.to_owned(), false, done);
+ unsafe {
+ store.lookUpContentRuleListForIdentifier_completionHandler(
+ Some(&NSString::from_str(id)),
+ Some(&block),
+ );
+ }
+ }
+
+ pub fn compile(id: &str, json: String, done: Done) {
+ let Some(store) = store() else {
+ return done(None);
+ };
+ let block = completion(id.to_owned(), true, done);
+ unsafe {
+ store.compileContentRuleListForIdentifier_encodedContentRuleList_completionHandler(
+ Some(&NSString::from_str(id)),
+ Some(&NSString::from_str(&json)),
+ Some(&block),
+ );
+ }
+ }
+
+ pub fn add(target: &Target, list: &List) {
+ unsafe { target.addContentRuleList(list) };
+ }
+
+ pub fn to_main(task: Box<dyn FnOnce() + Send>) {
+ dispatch::Queue::main().exec_async(task);
+ }
+
+ /// Compiled lists from an earlier selection or Pake version take tens of MB.
+ pub fn remove_stale(keep: Vec<String>) {
+ let Some(store) = store() else { return };
+ let remover = store.clone();
+ let block = RcBlock::new(move |ids: *mut NSArray<NSString>| {
+ let Some(ids) = (unsafe { ids.as_ref() }) else {
+ return;
+ };
+ for id in ids.iter() {
+ let name = id.to_string();
+ if name.starts_with(IDENTIFIER_PREFIX) && !keep.contains(&name) {
+ let ignore = RcBlock::new(|_: *mut NSError| {});
+ unsafe {
+ remover.removeContentRuleListForIdentifier_completionHandler(
+ Some(&id),
+ Some(&ignore),
+ );
+ }
+ }
+ }
+ });
+ unsafe { store.getAvailableContentRuleListIdentifiers(Some(&block)) };
+ }
+
+ /// The content controller of a webview, which every list is added to.
+ pub fn target(webview: &tauri::webview::PlatformWebview) -> Option<Target> {
+ use objc2::msg_send;
+ use objc2::runtime::AnyObject;
+ use objc2_web_kit::WKWebViewConfiguration;
+
+ let view = webview.inner() as *mut AnyObject;
+ if view.is_null() {
+ return None;
+ }
+ let configuration: Option<Retained<WKWebViewConfiguration>> =
+ unsafe { msg_send![view, configuration] };
+ configuration.map(|configuration| unsafe { configuration.userContentController() })
+ }
+}
+
+#[cfg(target_os = "linux")]
+mod platform {
+ use super::IDENTIFIER_PREFIX;
+ use std::cell::{Cell, OnceCell};
+ use std::ffi::{c_char, CStr, CString};
+ use std::path::PathBuf;
+ use webkit2gtk::ffi;
+ use webkit2gtk::gio::ffi as gio;
+ use webkit2gtk::glib::ffi as glib;
+ use webkit2gtk::glib::gobject_ffi as gobject;
+ use webkit2gtk::glib::translate::ToGlibPtr;
+
+ pub type Target = webkit2gtk::UserContentManager;
+ pub struct List(*mut ffi::WebKitUserContentFilter);
+ type Done = Box<dyn FnOnce(Option<List>)>;
+
+ impl Drop for List {
+ fn drop(&mut self) {
+ unsafe { ffi::webkit_user_content_filter_unref(self.0) };
+ }
+ }
+
+ thread_local! {
+ static STORE: OnceCell<usize> = const { OnceCell::new() };
+ static STORE_DIR: Cell<Option<PathBuf>> = const { Cell::new(None) };
+ }
+
+ /// Where compiled lists are kept: the app's own data folder.
+ pub fn set_store_dir(dir: PathBuf) {
+ STORE_DIR.set(Some(dir));
+ }
+
+ fn store() -> *mut ffi::WebKitUserContentFilterStore {
+ STORE.with(|store| {
+ *store.get_or_init(|| {
+ let dir = STORE_DIR
+ .take()
+ .unwrap_or_else(std::env::temp_dir)
+ .join("ContentFilters");
+ let path = CString::new(dir.to_string_lossy().as_bytes()).unwrap_or_default();
+ unsafe { ffi::webkit_user_content_filter_store_new(path.as_ptr()) as usize }
+ })
+ }) as *mut ffi::WebKitUserContentFilterStore
+ }
+
+ type Finish = unsafe extern "C" fn(
+ *mut ffi::WebKitUserContentFilterStore,
+ *mut gio::GAsyncResult,
+ *mut *mut glib::GError,
+ ) -> *mut ffi::WebKitUserContentFilter;
+
+ struct Pending {
+ id: String,
+ report: bool,
+ finish: Finish,
+ done: Done,
+ }
+
+ unsafe extern "C" fn ready(
+ source: *mut gobject::GObject,
+ result: *mut gio::GAsyncResult,
+ data: glib::gpointer,
+ ) {
+ let pending = Box::from_raw(data as *mut Pending);
+ let mut error: *mut glib::GError = std::ptr::null_mut();
+ let filter = (pending.finish)(
+ source as *mut ffi::WebKitUserContentFilterStore,
+ result,
+ &mut error,
+ );
+ if !error.is_null() {
+ if pending.report {
+ let message = CStr::from_ptr((*error).message).to_string_lossy();
+ eprintln!(
+ "[Pake] Content blocking could not compile {}: {message}",
+ pending.id
+ );
+ }
+ glib::g_error_free(error);
+ }
+ (pending.done)((!filter.is_null()).then_some(List(filter)));
+ }
+
+ fn pending(id: &str, report: bool, finish: Finish, done: Done) -> glib::gpointer {
+ Box::into_raw(Box::new(Pending {
+ id: id.to_owned(),
+ report,
+ finish,
+ done,
+ })) as glib::gpointer
+ }
+
+ pub fn lookup(id: &str, done: Done) {
+ let Ok(name) = CString::new(id) else {
+ return done(None);
+ };
+ unsafe {
+ ffi::webkit_user_content_filter_store_load(
+ store(),
+ name.as_ptr(),
+ std::ptr::null_mut(),
+ Some(ready),
+ pending(
+ id,
+ false,
+ ffi::webkit_user_content_filter_store_load_finish,
+ done,
+ ),
+ );
+ }
+ }
+
+ pub fn compile(id: &str, json: String, done: Done) {
+ let Ok(name) = CString::new(id) else {
+ return done(None);
+ };
+ unsafe {
+ let bytes = glib::g_bytes_new(json.as_ptr() as glib::gconstpointer, json.len());
+ ffi::webkit_user_content_filter_store_save(
+ store(),
+ name.as_ptr(),
+ bytes,
+ std::ptr::null_mut(),
+ Some(ready),
+ pending(
+ id,
+ true,
+ ffi::webkit_user_content_filter_store_save_finish,
+ done,
+ ),
+ );
+ glib::g_bytes_unref(bytes);
+ }
+ }
+
+ pub fn add(target: &Target, list: &List) {
+ let manager: *mut ffi::WebKitUserContentManager = target.to_glib_none().0;
+ unsafe { ffi::webkit_user_content_manager_add_filter(manager, list.0) };
+ }
+
+ pub fn to_main(task: Box<dyn FnOnce() + Send>) {
+ webkit2gtk::glib::MainContext::default().invoke(task);
+ }
+
+ unsafe extern "C" fn identifiers_ready(
+ source: *mut gobject::GObject,
+ result: *mut gio::GAsyncResult,
+ data: glib::gpointer,
+ ) {
+ let keep = Box::from_raw(data as *mut Vec<String>);
+ let store = source as *mut ffi::WebKitUserContentFilterStore;
+ let ids = ffi::webkit_user_content_filter_store_fetch_identifiers_finish(store, result);
+ if ids.is_null() {
+ return;
+ }
+ let mut cursor = ids;
+ while !(*cursor).is_null() {
+ let name = CStr::from_ptr(*cursor).to_string_lossy().into_owned();
+ if name.starts_with(IDENTIFIER_PREFIX) && !keep.contains(&name) {
+ ffi::webkit_user_content_filter_store_remove(
+ store,
+ *cursor as *const c_char,
+ std::ptr::null_mut(),
+ None,
+ std::ptr::null_mut(),
+ );
+ }
+ cursor = cursor.add(1);
+ }
+ glib::g_strfreev(ids);
+ }
+
+ pub fn remove_stale(keep: Vec<String>) {
+ unsafe {
+ ffi::webkit_user_content_filter_store_fetch_identifiers(
+ store(),
+ std::ptr::null_mut(),
+ Some(identifiers_ready),
+ Box::into_raw(Box::new(keep)) as glib::gpointer,
+ );
+ }
+ }
+
+ pub fn target(webview: &tauri::webview::PlatformWebview) -> Option<Target> {
+ use webkit2gtk::WebViewExt;
+ webview.inner().user_content_manager()
+ }
+}
+
+/// Adds the selected lists to a WebKit webview, now or once they load.
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+pub fn install(webview: &tauri::webview::PlatformWebview, groups: Vec<&'static str>) {
+ match platform::target(webview) {
+ Some(target) => loader::attach(target, groups),
+ None => eprintln!("[Pake] Content blocking could not reach the webview"),
+ }
+}
+
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+pub use loader::when_ready;
+
+#[cfg(target_os = "linux")]
+pub use platform::set_store_dir;
+
+#[cfg(target_os = "windows")]
+mod windows {
+ use super::{filter_set, selected_groups};
+ use adblock::lists::RuleTypes;
+ use adblock::request::Request;
+ use adblock::Engine;
+ use std::collections::HashMap;
+ use std::sync::{Mutex, OnceLock};
+ use webview2_com::Microsoft::Web::WebView2::Win32::*;
+ use webview2_com::{
+ take_pwstr, AddScriptToExecuteOnDocumentCreatedCompletedHandler,
+ ContentLoadingEventHandler, ExecuteScriptCompletedHandler,
+ WebResourceRequestedEventHandler,
+ };
+ use windows_core::{Interface, HSTRING, PWSTR};
+
+ struct Blocker {
+ engine: Engine,
+ /// Element hiding that applies on every site.
+ generic_css: String,
+ }
+
+ // The engine is built once per selection; a process has one selection.
+ static BLOCKERS: OnceLock<Mutex<HashMap<Vec<&'static str>, &'static Blocker>>> =
+ OnceLock::new();
+
+ fn blocker(groups: Vec<&'static str>) -> &'static Blocker {
+ let map = BLOCKERS.get_or_init(|| Mutex::new(HashMap::new()));
+ let mut map = map.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ map.entry(groups.clone()).or_insert_with(|| {
+ let engine = Engine::new_with_filter_set(filter_set(&groups, RuleTypes::All, false));
+ let generic = generic_selectors(&groups);
+ Box::leak(Box::new(Blocker {
+ engine,
+ generic_css: css(generic.iter().map(String::as_str)),
+ }))
+ })
+ }
+
+ /// Selectors of the hiding rules with no site condition, taken from the
+ /// WebKit conversion so both platforms hide the same generic elements.
+ fn generic_selectors(groups: &[&str]) -> Vec<String> {
+ let Ok((rules, _)) =
+ filter_set(groups, RuleTypes::CosmeticOnly, true).into_content_blocking()
+ else {
+ return Vec::new();
+ };
+ rules
+ .into_iter()
+ .filter(|rule| {
+ rule.trigger.if_domain.is_none()
+ && rule.trigger.unless_domain.is_none()
+ && rule.trigger.url_filter == ".*"
+ })
+ .filter_map(|rule| rule.action.selector)
+ .collect()
+ }
+
+ /// One rule per selector: a selector the browser rejects only drops its own rule.
+ fn css<'a>(selectors: impl Iterator<Item = &'a str>) -> String {
+ selectors
+ .filter(|selector| !selector.contains(['{', '}', '<']))
+ .map(|selector| format!("{selector}{{display:none!important}}"))
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+
+ fn style_script(css: &str) -> String {
+ let css = serde_json::to_string(css).unwrap_or_else(|_| "\"\"".into());
+ format!(
+ "(()=>{{const s=document.createElement('style');s.setAttribute('data-pake-blocking','');s.textContent={css};(document.head||document.documentElement).appendChild(s);}})();"
+ )
+ }
+
+ fn request_type(context: COREWEBVIEW2_WEB_RESOURCE_CONTEXT) -> Option<&'static str> {
+ Some(match context {
+ // Never block the page itself; a blocked page is a blank window.
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT => return None,
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_STYLESHEET => "stylesheet",
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_IMAGE => "image",
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_MEDIA => "media",
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_FONT => "font",
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_SCRIPT => "script",
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_XML_HTTP_REQUEST
+ | COREWEBVIEW2_WEB_RESOURCE_CONTEXT_FETCH
+ | COREWEBVIEW2_WEB_RESOURCE_CONTEXT_EVENT_SOURCE => "xmlhttprequest",
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_WEBSOCKET => "websocket",
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_PING => "ping",
+ _ => "other",
+ })
+ }
+
+ /// Hosts Tauri and Wry answer themselves.
+ fn is_local(url: &str) -> bool {
+ url.split_once("://")
+ .map(|(_, rest)| rest.split(['/', ':', '?', '#']).next().unwrap_or(""))
+ .is_some_and(|host| host == "localhost" || host.ends_with(".localhost"))
+ }
+
+ /// Installs request blocking and element hiding on a WebView2. Call it
+ /// before the first navigation: WebView2 only raises the event for
+ /// filters added before then.
+ pub fn install(webview: &tauri::webview::PlatformWebview, names: &[String]) {
+ let groups = selected_groups(names);
+ if groups.is_empty() {
+ return;
+ }
+ let blocker = blocker(groups);
+ let environment = webview.environment();
+ let result = unsafe {
+ (|| -> windows_core::Result<()> {
+ let core = webview.controller().CoreWebView2()?;
+ let filtered = core.cast::<ICoreWebView2_22>()?;
+ for pattern in ["http://*", "https://*"] {
+ filtered.AddWebResourceRequestedFilterWithRequestSourceKinds(
+ &HSTRING::from(pattern),
+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL,
+ COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL,
+ )?;
+ }
+ let mut token = 0;
+ core.add_WebResourceRequested(
+ &WebResourceRequestedEventHandler::create(Box::new(move |sender, args| {
+ let (Some(sender), Some(args)) = (sender, args) else {
+ return Ok(());
+ };
+ let mut context = COREWEBVIEW2_WEB_RESOURCE_CONTEXT_OTHER;
+ args.ResourceContext(&mut context)?;
+ let Some(kind) = request_type(context) else {
+ return Ok(());
+ };
+ let mut uri = PWSTR::null();
+ args.Request()?.Uri(&mut uri)?;
+ let url = take_pwstr(uri);
+ if is_local(&url) {
+ return Ok(());
+ }
+ let mut source = PWSTR::null();
+ sender.Source(&mut source)?;
+ let source = take_pwstr(source);
+ let Ok(request) = Request::new(&url, &source, kind, "GET") else {
+ return Ok(());
+ };
+ if blocker
+ .engine
+ .check_network_request(&request)
+ .should_block()
+ {
+ let response = environment.CreateWebResourceResponse(
+ None,
+ 403,
+ &HSTRING::from("Blocked"),
+ &HSTRING::new(),
+ )?;
+ args.SetResponse(&response)?;
+ }
+ Ok(())
+ })),
+ &mut token,
+ )?;
+
+ if !blocker.generic_css.is_empty() {
+ core.AddScriptToExecuteOnDocumentCreated(
+ &HSTRING::from(style_script(&blocker.generic_css)),
+ &AddScriptToExecuteOnDocumentCreatedCompletedHandler::create(Box::new(
+ |_, _| Ok(()),
+ )),
+ )?;
+ }
+
+ let mut loading = 0;
+ core.add_ContentLoading(
+ &ContentLoadingEventHandler::create(Box::new(move |sender, _| {
+ let Some(sender) = sender else { return Ok(()) };
+ let mut source = PWSTR::null();
+ sender.Source(&mut source)?;
+ let resources = blocker.engine.url_cosmetic_resources(&take_pwstr(source));
+ let site = css(resources.hide_selectors.iter().map(String::as_str));
+ if !site.is_empty() {
+ sender.ExecuteScript(
+ &HSTRING::from(style_script(&site)),
+ &ExecuteScriptCompletedHandler::create(Box::new(|_, _| Ok(()))),
+ )?;
+ }
+ Ok(())
+ })),
+ &mut loading,
+ )?;
+ Ok(())
+ })()
+ };
+ if let Err(error) = result {
+ eprintln!("[Pake] Content blocking could not be installed: {error}");
+ }
+ }
+}
+
+#[cfg(target_os = "windows")]
+pub use windows::install;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn selection_keeps_known_groups_in_order() {
+ let names = ["china", "ads", "nope", "ads", " trackers "].map(String::from);
+ assert_eq!(selected_groups(&names), vec!["ads", "trackers", "china"]);
+ assert!(selected_groups(&[]).is_empty());
+ }
+
+ #[test]
+ fn every_embedded_list_unpacks() {
+ for (group, bytes) in GROUPS.iter().chain([("unbreak", UNBREAK)].iter()) {
+ let text = gunzip(bytes).unwrap_or_else(|| panic!("{group} is not gzip text"));
+ assert!(text.lines().count() > 1000, "{group} looks truncated");
+ }
+ }
+
+ #[test]
+ fn identifiers_change_with_the_selection() {
+ let ads = webkit_identifier(&["ads"], "network");
+ assert!(ads.starts_with(IDENTIFIER_PREFIX));
+ assert_ne!(ads, webkit_identifier(&["ads", "trackers"], "network"));
+ assert_ne!(ads, webkit_identifier(&["ads"], "cosmetic"));
+ assert_eq!(ads, webkit_identifier(&["ads"], "network"));
+ }
+
+ /// WebKit refuses a whole list over its rule limit, so the largest
+ /// selection has to fit in each unit with room for list growth.
+ #[test]
+ fn every_group_together_fits_webkit() {
+ let all: Vec<&str> = GROUPS.iter().map(|(group, _)| *group).collect();
+ for (unit, rule_types) in WEBKIT_UNITS {
+ let count = webkit_rules(&all, rule_types).len();
+ assert!(count > 1000, "{unit} has only {count} rules");
+ assert!(
+ count < WEBKIT_MAX_RULES * 9 / 10,
+ "{unit} has {count} rules, too close to WebKit's {WEBKIT_MAX_RULES}"
+ );
+ }
+ }
+
+ #[test]
+ fn rules_serialize_to_webkit_json() {
+ let rules = webkit_rules(&["ads"], RuleTypes::NetworkOnly);
+ let json = serde_json::to_string(&rules).expect("rules serialize");
+ assert!(json.starts_with('[') && json.contains("\"url-filter\""));
+ }
+}
diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs
index eca8e346..a619375b 100644
--- a/src-tauri/src/app/mod.rs
+++ b/src-tauri/src/app/mod.rs
@@ -4,6 +4,8 @@ pub mod autostart;
#[cfg(any(target_os = "linux", test))]
pub mod color_scheme;
pub mod config;
+#[cfg(feature = "content-blocking")]
+pub mod content_blocking;
#[cfg(target_os = "windows")]
pub mod download;
pub mod invoke;
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 1b5050c0..eafe3489 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -548,6 +548,27 @@ fn build_window(
url
};
+ // With content blocking the main window starts blank, like the auth
+ // delegate above, and opens its page once the rule lists are in place.
+ #[cfg(all(
+ any(target_os = "macos", target_os = "linux"),
+ feature = "content-blocking"
+ ))]
+ let blocking_groups = crate::app::content_blocking::selected_groups(&config.content_blocking);
+ #[cfg(all(
+ any(target_os = "macos", target_os = "linux"),
+ feature = "content-blocking"
+ ))]
+ let (url, blocked_target) = match web_target(&url) {
+ Some(target) if label == "pake" && !blocking_groups.is_empty() => (
+ WebviewUrl::CustomProtocol(
+ Url::parse("about:blank").expect("about:blank must be a valid URL"),
+ ),
+ Some(target),
+ ),
+ _ => (url, None),
+ };
+
let user_agent = config.user_agent.get();
let config_script = format!(
@@ -964,6 +985,18 @@ fn build_window(
}
}
+ // Before download::install navigates: WebView2 only raises request events
+ // for filters added ahead of the first navigation.
+ #[cfg(all(target_os = "windows", feature = "content-blocking"))]
+ if !config.content_blocking.is_empty() {
+ let names = config.content_blocking.clone();
+ if let Err(error) = window.with_webview(move |webview| {
+ crate::app::content_blocking::install(&webview, &names);
+ }) {
+ eprintln!("[Pake] Failed to access WebView2 for content blocking: {error}");
+ }
+ }
+
#[cfg(target_os = "windows")]
crate::app::download::install(&window, download_target)?;
@@ -976,6 +1009,33 @@ fn build_window(
eprintln!("[Pake] Failed to access WebKitGTK for media permissions and recovery: {error}");
}
+ // Every webview passes here, popups included, whose content controller
+ // macOS replaces (prepare_macos_new_window_configuration), so each gets the lists.
+ #[cfg(all(
+ any(target_os = "macos", target_os = "linux"),
+ feature = "content-blocking"
+ ))]
+ if !blocking_groups.is_empty() {
+ #[cfg(target_os = "linux")]
+ if let Ok(directory) = app.path().app_data_dir() {
+ crate::app::content_blocking::set_store_dir(directory);
+ }
+ let groups = blocking_groups.clone();
+ let opener = window.clone();
+ if let Err(error) = window.with_webview(move |webview| {
+ crate::app::content_blocking::install(&webview, groups);
+ if let Some(target) = blocked_target {
+ crate::app::content_blocking::when_ready(Box::new(move || {
+ if let Err(error) = opener.navigate(target) {
+ eprintln!("[Pake] Failed to open the page: {error}");
+ }
+ }));
+ }
+ }) {
+ eprintln!("[Pake] Failed to access the webview for content blocking: {error}");
+ }
+ }
+
#[cfg(target_os = "windows")]
if let Err(error) = window.with_webview(|webview| {
crate::app::recovery::install(&webview);
@@ -1035,7 +1095,11 @@ fn build_window(
let prompt_for_basic_auth = config.basic_auth;
let allow_invalid_certificates = window_config.ignore_certificate_errors;
let auth_window = window.clone();
- Queue::main().exec_async(move || {
+ #[cfg(feature = "content-blocking")]
+ let wait_for_lists = !blocking_groups.is_empty();
+ #[cfg(not(feature = "content-blocking"))]
+ let wait_for_lists = false;
+ let navigate = move || {
if let Err(error) = auth_window.with_webview(move |webview| {
if !crate::app::auth::install_auth_delegate_and_navigate(
webview.inner(),
@@ -1049,12 +1113,35 @@ fn build_window(
}) {
eprintln!("[Pake] Failed to access the macOS webview: {error}");
}
+ };
+ Queue::main().exec_async(move || {
+ #[cfg(feature = "content-blocking")]
+ if wait_for_lists {
+ crate::app::content_blocking::when_ready(Box::new(navigate));
+ return;
+ }
+ let _ = wait_for_lists;
+ navigate();
});
}
Ok(window)
}
+/// The http or https page a window opens, whichever way its URL is held.
+#[cfg(all(
+ any(target_os = "macos", target_os = "linux"),
+ feature = "content-blocking"
+))]
+fn web_target(url: &WebviewUrl) -> Option<Url> {
+ let target = match url {
+ WebviewUrl::External(target) => Some(target.clone()),
+ WebviewUrl::App(path) => path.to_str().and_then(|path| Url::parse(path).ok()),
+ _ => None,
+ }?;
+ matches!(target.scheme(), "http" | "https").then_some(target)
+}
+
pub fn save_last_url(app: &AppHandle) {
let Some(window) = app.get_webview_window("pake") else {
return;