Merge branch 'main' into s022-mse-proto

# Conflicts:
#	CLAUDE.md
This commit is contained in:
astar76 2026-11-12 19:41:47 -06:00
commit bef559fa89
11 changed files with 3103 additions and 153 deletions

View file

@ -2451,6 +2451,8 @@ impl App {
}
let scripts_changed = old.privacy.mode != new.privacy.mode
|| old.privacy.mode_incognito != new.privacy.mode_incognito
|| old.privacy.mode_off != new.privacy.mode_off
|| old.privacy.block_third_party != new.privacy.block_third_party
|| old.privacy.dnt != new.privacy.dnt
|| old.privacy.save_data != new.privacy.save_data
|| old.privacy.google_signin != new.privacy.google_signin
@ -2478,6 +2480,8 @@ impl App {
servo.set_preference("user_agent", servo::PrefValue::Str(ua.clone()));
*self.shared.user_agent.borrow_mut() = ua.clone();
crate::net::fetch::set_user_agent(&ua);
// Privacy mode's navigator values follow the user agent.
self.install_page_scripts();
}
if old.spell.langs != new.spell.langs || (!old.spell.enabled && new.spell.enabled) {
self.load_speller();

View file

@ -383,6 +383,8 @@ impl App {
prefs.shell_background_color_rgba = if dark { [0.1, 0.1, 0.1, 1.0] } else { [1.0, 1.0, 1.0, 1.0] };
let opts = Opts { config_dir: Some(self.shared.paths.engine()), temporary_storage: self.shared.incognito, multiprocess: false, ..Opts::default() };
let _ = std::fs::create_dir_all(self.shared.paths.engine());
// Cookies are kept encrypted by Nacre, not in Servo's plain cookie_jar.json (R1-19).
crate::store::cookies::start(&self.shared.paths.data, &self.shared.paths.engine(), self.shared.incognito);
let servo = ServoBuilder::default().opts(opts).preferences(prefs).event_loop_waker(Box::new(Waker(self.proxy.clone()))).build();
servo.set_delegate(self.hub.clone());
servo.setup_logging();
@ -396,6 +398,27 @@ impl App {
pub fn refresh_hub_config(&self) {
let settings = self.shared.settings.borrow();
*self.hub.config.borrow_mut() = HubConfig::from_settings(&settings, &self.shared.permissions.borrow(), &self.shared.user_agent.borrow(), self.shared.http_allowed.borrow().clone());
// Request headers and the cookie policy live in the vendored servo-net (S023).
net::nacre::set_extra_request_headers(&crate::hub::privacy_headers(&settings));
net::nacre::set_block_third_party_cookies(settings.privacy.block_third_party || self.privacy_mode_on(&settings));
net::nacre::set_language_list(self.privacy_mode_on(&settings));
}
/// What pages see as the screen and their window (`window.screen`, `outerWidth`, `screenX`): the monitor and
/// window of the last focused, moved or resized window. Wayland doesn't tell windows where they are (0, 0).
fn update_screen(&self, window_id: WindowId) {
let Some(win) = self.windows.get(&window_id) else { return };
let outer = win.window.outer_size();
let pos = win.window.outer_position().unwrap_or_default();
let monitor = win.window.current_monitor().map(|m| m.size()).filter(|s| s.width > 0 && s.height > 0).unwrap_or(outer);
let size = servo::DeviceIntSize::new(monitor.width as i32, monitor.height as i32);
let window_rect = servo::DeviceIntRect::from_origin_and_size(servo::DeviceIntPoint::new(pos.x, pos.y), servo::DeviceIntSize::new(outer.width as i32, outer.height as i32));
*self.hub.screen.borrow_mut() = Some(servo::ScreenGeometry { size, available_size: size, window_rect });
}
/// Privacy mode: on everywhere, or in incognito windows when the user chose that.
fn privacy_mode_on(&self, s: &Settings) -> bool {
s.privacy.mode || (self.shared.incognito && s.privacy.mode_incognito)
}
/// (Re)build the scripts every page gets. Applies on each page's next load.
@ -405,11 +428,15 @@ impl App {
ucm.remove_script(script);
}
let s = self.shared.settings.borrow().clone();
let privacy = s.privacy.mode || (self.shared.incognito && s.privacy.mode_incognito);
let privacy = self.privacy_mode_on(&s);
let options = inject::Options {
token: &self.hub.token,
privacy_mode: privacy,
seed: &self.shared.seed,
user_agent: &self.shared.user_agent.borrow(),
privacy_paused: &s.privacy.mode_off,
languages: &net::nacre::languages(&net::nacre::locale()),
block_third_party: s.privacy.block_third_party || privacy,
dnt: s.privacy.dnt,
force_dark: s.web.force_dark,
smooth_scroll: s.web.smooth_scroll && !crate::perf::lite(&s),
@ -1351,6 +1378,7 @@ impl App {
self.start_servo();
}
self.windows.insert(id, win);
self.update_screen(id);
if kind == Kind::Normal {
self.last_window = Some(id);
}
@ -1762,7 +1790,9 @@ impl ApplicationHandler<AppEvent> for App {
WindowEvent::CloseRequested => {
self.close_window(window_id);
},
WindowEvent::Moved(_) => self.update_screen(window_id),
WindowEvent::Resized(size) => {
self.update_screen(window_id);
let pip = self.windows.get(&window_id).and_then(|w| if let Kind::Pip { window, tab } = w.kind { Some((window, tab)) } else { None });
if let Some(win) = self.windows.get_mut(&window_id) {
win.resized(*size);
@ -1784,6 +1814,9 @@ impl ApplicationHandler<AppEvent> for App {
self.redraw(window_id);
},
WindowEvent::Focused(focused) => {
if *focused {
self.update_screen(window_id);
}
if let Some(win) = self.windows.get_mut(&window_id) {
win.focused = *focused;
let _ = win.egui.on_window_event(&win.window, &event);

View file

@ -117,6 +117,9 @@ pub struct Hub {
/// 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.
@ -125,6 +128,19 @@ const TRACKING_PARAMS: &[&str] = &[
];
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()?;
@ -158,6 +174,7 @@ impl Hub {
net_log: RefCell::new(HashMap::new()),
ua_quirk_on: RefCell::new(false),
servo: RefCell::new(None),
screen: RefCell::new(None),
})
}
@ -303,7 +320,13 @@ impl Hub {
}
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>) {
@ -331,6 +354,7 @@ impl WebViewDelegate for Hub {
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>) {
@ -419,6 +443,60 @@ impl servo::GamepadDelegate for Gamepads {
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();

View file

@ -8,7 +8,7 @@
//! Servo injects user scripts into every document before the page's own scripts run. Settings
//! that change them take effect on the next page load (Servo's rule for user content).
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::util;
@ -33,6 +33,14 @@ pub struct Options<'a> {
pub token: &'a str,
pub privacy_mode: bool,
pub seed: &'a str,
/// The user agent pages see, for privacy mode's matching `navigator` values.
pub user_agent: &'a str,
/// Sites where privacy mode is paused.
pub privacy_paused: &'a [String],
/// `navigator.languages` in privacy mode, matching its Accept-Language (`net::nacre::languages`).
pub languages: &'a [String],
/// Third-party cookies are blocked (the setting or privacy mode): `document.cookie` in cross-site frames too.
pub block_third_party: bool,
pub dnt: bool,
pub force_dark: bool,
pub smooth_scroll: bool,
@ -51,12 +59,15 @@ pub struct Options<'a> {
/// Nacre's own scripts run inside one closure with the private `__send`, so pages can call the
/// functions on `window.__nacre` (find, media controls, ...) but can never send a message as Nacre.
pub fn page_scripts(o: &Options) -> Vec<String> {
let mut modules: Vec<String> = vec![MEDIA_JS.to_owned(), FIND_JS.to_owned(), PIP_JS.to_owned(), META_JS.to_owned(), SVG_COLOR_JS.to_owned()];
let mut modules: Vec<String> = vec![MEDIA_JS.to_owned(), FIND_JS.to_owned(), PIP_JS.to_owned(), META_JS.to_owned(), SVG_COLOR_JS.to_owned(), FONTS_CHECK_JS.to_owned(), COMPRESSOR_JS.to_owned()];
if o.dnt {
modules.push(DNT_JS.to_owned());
}
if o.privacy_mode {
modules.push(PRIVACY_JS.replace("__SEED__", &util::js_string(o.seed)));
modules.push(privacy_script(o.seed, o.user_agent, o.languages, o.privacy_paused));
}
if o.block_third_party {
modules.push(FRAME_COOKIE_JS.to_owned());
}
if o.force_dark {
modules.push(FORCE_DARK_JS.to_owned());
@ -119,6 +130,10 @@ const BRIDGE_JS: &str = r#"if (window.__nacre) return;
if (r && r.startContainer.nodeType === 3) { const s = r.startContainer.data, i = r.startOffset;
const m = /[\p{L}'’-]*$/u.exec(s.slice(0, i))[0] + /^[\p{L}'’-]*/u.exec(s.slice(i))[0]; word = m; } } catch (e) {}
const field = t && t.closest && t.closest('input,textarea,[contenteditable=""],[contenteditable=true]');
// Servo has no caretRangeFromPoint, and text fields have no text node anyway: the spell check's mirror
// underlines the misspelled words, so the one under the pointer is the one clicked.
if (!word && field) for (const u of document.querySelectorAll('.__nacre_spell_mirror u'))
for (const r of u.getClientRects()) if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) word = u.textContent;
__send('context', { selection: sel.slice(0, 2000), word, editable: !!field,
media: media ? { src: media.currentSrc || media.src || '', kind: media.tagName.toLowerCase() } : null,
x: e.clientX, y: e.clientY });
@ -335,38 +350,200 @@ const DNT_JS: &str = r#"(() => { try {
} catch (e) {} })();"#;
/// Privacy mode: fingerprint noise seeded per site and per run, common values for the rest.
const PRIVACY_JS: &str = r#"(() => { if (window.__nacrePriv) return; window.__nacrePriv = 1;
const SEED = __SEED__ + location.hostname;
let h = 2166136261; for (let i = 0; i < SEED.length; i++) { h ^= SEED.charCodeAt(i); h = Math.imul(h, 16777619); }
const rnd = () => { h ^= h << 13; h ^= h >>> 17; h ^= h << 5; return ((h >>> 0) % 1000) / 1000; };
const def = (o, k, v) => { try { Object.defineProperty(o, k, { get: () => v, configurable: true }); } catch (e) {} };
def(Navigator.prototype, 'hardwareConcurrency', 8);
def(Navigator.prototype, 'deviceMemory', 8);
const round = (v, step) => Math.ceil(v / step) * step;
try { const s = screen; const w = round(s.width, 200), hgt = round(s.height, 100);
def(Screen.prototype, 'width', w); def(Screen.prototype, 'height', hgt);
def(Screen.prototype, 'availWidth', w); def(Screen.prototype, 'availHeight', hgt);
def(Screen.prototype, 'colorDepth', 24); def(Screen.prototype, 'pixelDepth', 24); } catch (e) {}
// Canvas: flip the lowest bit of a few pixels, the same pixels every time on this site.
const noise = (ctx, w, hh) => { try { if (!w || !hh) return; const img = ctx.getImageData(0, 0, w, hh);
for (let i = 0; i < 12; i++) { const p = Math.floor(rnd() * w * hh) * 4; img.data[p] ^= 1; img.data[p + 1] ^= 1; }
ctx.putImageData(img, 0, 0); } catch (e) {} };
const toURL = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = function () { const c = this.getContext && this.getContext('2d');
if (c) noise(c, this.width, this.height); return toURL.apply(this, arguments); };
const toBlob = HTMLCanvasElement.prototype.toBlob;
if (toBlob) HTMLCanvasElement.prototype.toBlob = function () { const c = this.getContext && this.getContext('2d');
if (c) noise(c, this.width, this.height); return toBlob.apply(this, arguments); };
const gid = CanvasRenderingContext2D.prototype.getImageData;
CanvasRenderingContext2D.prototype.getImageData = function () { const d = gid.apply(this, arguments);
for (let i = 0; i < Math.min(8, d.data.length / 4); i++) { const p = Math.floor(rnd() * d.data.length / 4) * 4; d.data[p] ^= 1; } return d; };
for (const G of [window.WebGLRenderingContext, window.WebGL2RenderingContext]) { if (!G) continue;
const gp = G.prototype.getParameter;
G.prototype.getParameter = function (p) { if (p === 37445) return 'Intel Inc.'; if (p === 37446) return 'Intel Iris OpenGL Engine';
return gp.apply(this, arguments); }; }
try { const gc = AudioBuffer.prototype.getChannelData;
AudioBuffer.prototype.getChannelData = function () { const d = gc.apply(this, arguments);
for (let i = 0; i < d.length; i += 100) d[i] += (rnd() - 0.5) * 1e-7; return d; }; } catch (e) {}
/// What `navigator` reports about the system in Firefox with this user agent. Servo answers "Linux" and "4.0",
/// which no Firefox does, so privacy mode makes them agree with the user agent.
#[derive(Debug, PartialEq, Serialize)]
pub struct FirefoxNavigator {
pub platform: String,
pub oscpu: String,
#[serde(rename = "appVersion")]
pub app_version: String,
}
/// `None` for a user agent that isn't Firefox on Windows, macOS or Linux (then Servo's own values stay).
pub fn firefox_navigator(ua: &str) -> Option<FirefoxNavigator> {
if !ua.contains("Firefox/") {
return None;
}
// "Mozilla/5.0 (X11; Linux x86_64; rv:153.0) ..." -> "X11; Linux x86_64"
let inside = ua.split_once('(')?.1.split_once(')')?.0;
let os = inside.split("; ").filter(|part| !part.starts_with("rv:")).collect::<Vec<_>>().join("; ");
let (platform, oscpu, app) = if os.starts_with("Windows") {
("Win32".to_owned(), os.clone(), "Windows")
} else if let Some(mac) = os.strip_prefix("Macintosh; ") {
("MacIntel".to_owned(), mac.to_owned(), "Macintosh")
} else if let Some(linux) = os.strip_prefix("X11; ").filter(|rest| rest.starts_with("Linux") || rest.starts_with("Ubuntu")) {
let linux = linux.rsplit("; ").next().unwrap_or(linux).to_owned();
(linux.clone(), linux, "X11")
} else {
return None;
};
Some(FirefoxNavigator { platform, oscpu, app_version: format!("5.0 ({app})") })
}
/// Privacy mode's page script for this run's seed, user agent, language list and paused sites.
pub fn privacy_script(seed: &str, user_agent: &str, languages: &[String], paused: &[String]) -> String {
let nav = firefox_navigator(user_agent).map(|n| serde_json::to_string(&n).unwrap_or_default()).unwrap_or_else(|| "null".to_owned());
PRIVACY_JS
.replace("__SEED__", &util::js_string(seed))
.replace("__NAV__", &nav)
.replace("__LANGS__", &serde_json::to_string(languages).unwrap_or_else(|_| "[]".to_owned()))
.replace("__PAUSED__", &serde_json::to_string(paused).unwrap_or_else(|_| "[]".to_owned()))
}
/// Privacy mode: hide the browser's fingerprint (what coveryourtracks.eff.org measures), after the original
/// Nacre's privacy.py. Brave-style noise plus common values:
/// - canvas, WebGL pixels, audio and canvas text widths get tiny noise seeded per top-level site and per run,
/// so values differ on every site and after every restart but stay stable inside one site;
/// - text-width noise makes every font in a probe list measure as "installed", the same for every user;
/// - WebGL vendor/renderer say "Mozilla" (as Firefox does) instead of "Mozilla/Servo";
/// - screen size is the smallest common size that holds the window, colour depth 24, position 0,0;
/// - CPU cores read 8; platform, oscpu and appVersion match the user agent (`firefox_navigator`);
/// - WEBGL_debug_renderer_info exists (answering "Mozilla"); no touch points and `createEvent('TouchEvent')`
/// fails, as in desktop Firefox;
/// - `navigator.languages` is Firefox's list for the locale, the same as Accept-Language (`net::nacre`).
/// Not changed: time zone and locale (real, and consistent with each other: Servo reads both from the system),
/// the user agent itself, DOM-measured fonts, web workers. Paused sites (and every frame on their pages) keep
/// the engine's values except the language list. Same-origin frames made by script get the same treatment through
/// `contentWindow`, as Servo only injects scripts into documents it parses.
const PRIVACY_JS: &str = r#"(() => {
if (location.protocol === 'nacre:' || window.__nacrePriv) return;
const SEED = __SEED__, NAV = __NAV__, LANGS = __LANGS__, PAUSED = __PAUSED__;
const matches = (h, d) => { h = h.replace(/^www\./, ''); d = d.replace(/^www\./, ''); return !!d && (h === d || h.endsWith('.' + d)); };
// The top-level page's host: readable when same-origin, else from the referrer (the frame's parent page).
let top = ''; try { top = window.top.location.hostname; } catch (e) { try { top = new URL(document.referrer).hostname; } catch (e2) {} }
const host = top || location.hostname;
// Paused sites keep the engine's values, except the language list: it has to match Accept-Language, which is
// the same for every request.
const paused = PAUSED.some(d => matches(host, d));
const site = /^[\d.]+$|:/.test(host) ? host : host.split('.').slice(-2).join('.');
let H = 2166136261;
for (const c of SEED + '|' + site) { H ^= c.charCodeAt(0); H = Math.imul(H, 16777619); }
const hash = i => { let x = (H ^ Math.imul(i + 1, 0x9E3779B1)) >>> 0;
x ^= x >>> 16; x = Math.imul(x, 0x85EBCA6B); x ^= x >>> 13; x = Math.imul(x, 0xC2B2AE35); return (x ^ (x >>> 16)) >>> 0; };
const hashText = t => { let x = H; for (let i = 0; i < t.length; i++) { x ^= t.charCodeAt(i); x = Math.imul(x, 16777619); } return hash(x >>> 0); };
const natives = new WeakMap();
function install(W) {
if (!W || W.__nacrePriv) return; try { Object.defineProperty(W, '__nacrePriv', { value: true }); } catch (e) { return; }
if (LANGS.length) try { const list = Object.freeze(LANGS.slice());
Object.defineProperty(W.Navigator.prototype, 'languages', { get: () => list, configurable: true, enumerable: true }); } catch (e) {}
if (paused) return;
// Replaced functions still print as native code.
const fnToString = W.Function.prototype.toString;
const toStr = function toString() { return natives.has(this) ? natives.get(this) : fnToString.call(this); };
natives.set(toStr, 'function toString() {\n [native code]\n}');
W.Function.prototype.toString = toStr;
const native = (f, name) => { natives.set(f, `function ${name}() {\n [native code]\n}`); return f; };
const wrap = (obj, name, make) => { const d = obj && Object.getOwnPropertyDescriptor(obj, name);
if (!d || typeof d.value !== 'function') return; const orig = d.value, f = make(orig);
Object.defineProperty(f, 'name', { value: name }); Object.defineProperty(f, 'length', { value: orig.length });
d.value = native(f, name); Object.defineProperty(obj, name, d); };
// A getter that replaces the native one, or a new one where the engine has none (Firefox has oscpu).
const getter = (obj, name, fn) => { if (!obj) return; const d = Object.getOwnPropertyDescriptor(obj, name) || { configurable: true, enumerable: true };
if (d.value !== undefined || d.configurable === false) return; const orig = d.get;
d.get = native({ [`get ${name}`]() { return fn.call(this, orig); } }[`get ${name}`], `get ${name}`);
Object.defineProperty(obj, name, d); };
// Pixels: flip the low bits of ~1 in 40 colour values, chosen by the site hash (same picture -> same output).
const noisePixels = data => { for (let i = 0; i < data.length; i++) {
if ((i & 3) !== 3) { const r = hash(i); if (r % 40 === 0) data[i] ^= 1 + ((r >>> 8) & 1); } } };
const CR = W.CanvasRenderingContext2D && W.CanvasRenderingContext2D.prototype;
const getImageData = CR && CR.getImageData;
wrap(CR, 'getImageData', orig => function () { const d = orig.apply(this, arguments); noisePixels(d.data); return d; });
// Text widths: a few millionths of a pixel per font and text, so font probes find every font "installed".
wrap(CR, 'measureText', orig => function (text) { const m = orig.apply(this, arguments);
try { const w = m.width + ((hashText(this.font + '|' + text) % 2001) - 1000) * 1e-6;
Object.defineProperty(m, 'width', { value: w, enumerable: true }); } catch (e) {} return m; });
const noisyCopy = canvas => { const w = canvas.width, h = canvas.height; if (!w || !h) return null;
const c = W.document.createElement('canvas'); c.width = w; c.height = h;
const x = c.getContext('2d'); x.drawImage(canvas, 0, 0); const d = getImageData.call(x, 0, 0, w, h);
noisePixels(d.data); x.putImageData(d, 0, 0); return c; };
const CP = W.HTMLCanvasElement && W.HTMLCanvasElement.prototype;
for (const m of ['toDataURL', 'toBlob']) wrap(CP, m, orig => function () {
let c = null; try { c = noisyCopy(this); } catch (e) {} return orig.apply(c || this, arguments); });
for (const P of [W.WebGLRenderingContext, W.WebGL2RenderingContext]) { if (!P) continue;
wrap(P.prototype, 'getParameter', orig => function (p) {
if (p === 0x1F00 || p === 0x1F01 || p === 0x9245 || p === 0x9246) return 'Mozilla'; return orig.apply(this, arguments); });
wrap(P.prototype, 'readPixels', orig => function () { const r = orig.apply(this, arguments);
const a = arguments[6]; if (a && a.length) noisePixels(a); return r; });
// Servo has no WEBGL_debug_renderer_info; Firefox has it and answers "Mozilla" (getParameter above).
const DEBUG = 'WEBGL_debug_renderer_info', info = Object.freeze({ UNMASKED_VENDOR_WEBGL: 0x9245, UNMASKED_RENDERER_WEBGL: 0x9246 });
wrap(P.prototype, 'getExtension', orig => function (name) { const r = orig.apply(this, arguments); return r || name !== DEBUG ? r : info; });
wrap(P.prototype, 'getSupportedExtensions', orig => function () { const r = orig.apply(this, arguments);
return r && !r.includes(DEBUG) ? r.concat([DEBUG]) : r; }); }
// Audio: tiny deterministic noise once per buffer.
const seen = new WeakSet();
wrap(W.AudioBuffer && W.AudioBuffer.prototype, 'getChannelData', orig => function () { const d = orig.apply(this, arguments);
if (!seen.has(d)) { seen.add(d); for (let i = 0; i < d.length; i += 97) d[i] += ((hash(i) % 1000) - 500) * 1e-9; }
return d; });
wrap(W.AnalyserNode && W.AnalyserNode.prototype, 'getFloatFrequencyData', orig => function (a) { orig.apply(this, arguments);
for (let i = 0; i < a.length; i++) a[i] += ((hash(i) % 100) - 50) * 1e-5; });
// Screen: the smallest common size that holds the browser window (the top window's, in frames too).
const SIZES = [[1366, 768], [1536, 864], [1920, 1080], [2560, 1440], [3840, 2160]];
const size = () => { const w = W.outerWidth || W.innerWidth || 1366, h = W.outerHeight || W.innerHeight || 768;
return SIZES.find(s => s[0] >= w && s[1] >= h) || SIZES[SIZES.length - 1]; };
const SP = W.Screen && W.Screen.prototype;
getter(SP, 'width', () => size()[0]); getter(SP, 'height', () => size()[1]);
getter(SP, 'availWidth', () => size()[0]); getter(SP, 'availHeight', () => size()[1]);
getter(SP, 'availLeft', () => 0); getter(SP, 'availTop', () => 0);
getter(SP, 'colorDepth', () => 24); getter(SP, 'pixelDepth', () => 24);
// Window position: Servo keeps Window's attributes on the window itself or its prototype.
for (const k of ['screenX', 'screenY', 'screenLeft', 'screenTop'])
getter(Object.getOwnPropertyDescriptor(W, k) ? W : W.Window && W.Window.prototype, k, () => 0);
const NP = W.Navigator && W.Navigator.prototype;
getter(NP, 'hardwareConcurrency', () => 8);
// Desktop Firefox: no touch points, and touch events can't be created (Servo has touch events but no
// maxTouchPoints, a rare combination). The TouchEvent globals stay: removing them breaks pages (Wikipedia's
// search field, media documents).
getter(NP, 'maxTouchPoints', () => 0);
wrap(W.Document && W.Document.prototype, 'createEvent', orig => function (type) {
if (/^touchevents?$/i.test(String(type))) throw new W.DOMException('Unsupported event type', 'NotSupportedError');
return orig.apply(this, arguments); });
if (NAV) { getter(NP, 'platform', () => NAV.platform); getter(NP, 'oscpu', () => NAV.oscpu); getter(NP, 'appVersion', () => NAV.appVersion); }
// Same-origin frames made by script never get injected scripts: cover them when the page reaches in.
for (const [P, prop] of [[W.HTMLIFrameElement, 'contentWindow'], [W.HTMLIFrameElement, 'contentDocument'], [W.HTMLFrameElement, 'contentWindow']])
getter(P && P.prototype, prop, function (orig) { const r = orig.call(this);
try { install(prop === 'contentDocument' ? r && r.defaultView : r); } catch (e) {} return r; });
}
install(window);
})();"#;
/// Servo 0.7's `document.fonts` has no `check()`, and scripts that call it stop there (Cover Your Tracks never
/// sends its fingerprint). Per the spec: false only when a face of a named family is in the set and not loaded yet.
const FONTS_CHECK_JS: &str = r#"(() => { const P = window.FontFaceSet && FontFaceSet.prototype; if (!P || P.check) return;
Object.defineProperty(P, 'check', { configurable: true, writable: true, value: function check(font) {
const m = /(?:^|\s)[\d.]+(?:px|pt|em|rem|%)(?:\s*\/\s*\S+)?\s+(.+)$/.exec(String(font));
if (!m) throw new DOMException('Invalid font', 'SyntaxError');
const names = m[1].split(',').map(f => f.trim().replace(/^["']|["']$/g, '').toLowerCase());
let ok = true;
try { this.forEach(face => { if (names.includes(face.family.replace(/^["']|["']$/g, '').toLowerCase()) && face.status !== 'loaded') ok = false; }); } catch (e) {}
return ok; } });
})();"#;
/// Servo 0.7 has no DynamicsCompressorNode; audio fingerprint scripts (Fingerprint2, Cover Your Tracks) and some
/// players throw at `createDynamicsCompressor`. This stand-in passes the sound through unchanged: a GainNode with
/// the compressor's parameters (real AudioParams, so automation calls work) and `reduction` 0.
const COMPRESSOR_JS: &str = r#"(() => { const B = window.BaseAudioContext || window.AudioContext; const P = B && B.prototype;
if (!P || P.createDynamicsCompressor || !P.createGain) return;
const PARAMS = { threshold: -24, knee: 30, ratio: 12, attack: 0.003, release: 0.25 };
Object.defineProperty(P, 'createDynamicsCompressor', { configurable: true, writable: true, value: function createDynamicsCompressor() {
const node = this.createGain();
for (const [k, v] of Object.entries(PARAMS)) { const param = this.createGain().gain; param.value = v; Object.defineProperty(node, k, { value: param, enumerable: true }); }
Object.defineProperty(node, 'reduction', { value: 0, enumerable: true });
return node; } });
})();"#;
/// Third-party cookie blocking for scripts: servo-net blocks the cookies of cross-site requests (S023), but a
/// cross-site frame's `document.cookie` goes through the script thread, which doesn't say which page it is on.
/// A frame whose top page is another site gets an empty, write-only-to-nowhere `document.cookie`. The top page
/// is known when same-origin, else from the referrer; with neither, the frame counts as cross-site.
const FRAME_COOKIE_JS: &str = r#"(() => { if (window.top === window || !location.hostname) return;
let top = null; try { top = window.top.location.hostname; } catch (e) {}
if (top === null) { try { top = new URL(document.referrer).hostname; } catch (e) { top = ''; } }
const site = h => /^[\d.]+$|:/.test(h) ? h : h.split('.').slice(-2).join('.');
if (top && site(top) === site(location.hostname)) return;
const d = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie'); if (!d || !d.configurable) return;
Object.defineProperty(Document.prototype, 'cookie', { get() { return ''; }, set(v) {}, configurable: true, enumerable: d.enumerable });
try { if ('cookieStore' in window) Object.defineProperty(window, 'cookieStore', { value: undefined }); } catch (e) {}
})();"#;
/// Dark pages for sites that have no dark style of their own.
@ -577,6 +754,40 @@ mod tests {
assert_eq!(mainstream_ua(&ua), ua);
}
#[test]
fn navigator_values_match_the_user_agent() {
let linux = firefox_navigator("Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
assert_eq!(linux, FirefoxNavigator { platform: "Linux x86_64".into(), oscpu: "Linux x86_64".into(), app_version: "5.0 (X11)".into() });
let ubuntu = firefox_navigator("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0").unwrap();
assert_eq!(ubuntu.platform, "Linux x86_64");
let windows = firefox_navigator("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
assert_eq!(windows, FirefoxNavigator { platform: "Win32".into(), oscpu: "Windows NT 10.0; Win64; x64".into(), app_version: "5.0 (Windows)".into() });
let mac = firefox_navigator("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
assert_eq!(mac, FirefoxNavigator { platform: "MacIntel".into(), oscpu: "Intel Mac OS X 10.15".into(), app_version: "5.0 (Macintosh)".into() });
// Not Firefox, or an OS Firefox's form isn't known for: Servo's values stay.
assert!(firefox_navigator("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36").is_none());
assert!(firefox_navigator("Mozilla/5.0 (Android 14; Mobile; rv:140.0) Gecko/140.0 Firefox/140.0").is_none());
// The script gets the default user agent's values (consistency with what Nacre sends).
let ua = mainstream_ua("Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Servo/0.7.0 Firefox/153.0");
assert_eq!(firefox_navigator(&ua).unwrap().app_version, "5.0 (X11)");
}
#[test]
fn privacy_script_fills_every_value() {
let paused = vec!["example.com".to_owned(), "a\"b".to_owned()];
let langs = vec!["en-US".to_owned(), "en".to_owned()];
let js = privacy_script("se\"ed", "Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0", &langs, &paused);
assert!(!js.contains("__SEED__") && !js.contains("__NAV__") && !js.contains("__LANGS__") && !js.contains("__PAUSED__"));
assert!(js.contains(r#"const SEED = "se\"ed", NAV = {"platform":"Linux x86_64","oscpu":"Linux x86_64","appVersion":"5.0 (X11)"}, LANGS = ["en-US","en"], PAUSED = ["example.com","a\"b"];"#));
assert!(privacy_script("s", "Custom agent", &[], &[]).contains("NAV = null, LANGS = [], PAUSED = [];"));
// Off by default; cookie-blocking module only with blocking on.
let mut o = Options { token: "t", privacy_mode: false, seed: "s", user_agent: "", privacy_paused: &[], languages: &[], block_third_party: false, dnt: false, force_dark: false, smooth_scroll: false, preload: false, save_data: false, cosmetic: false, animate_removal: false, youtube_ads: false, autofill: false, spell: false, google_signin: false };
assert!(!page_scripts(&o)[0].contains("__nacrePriv") && !page_scripts(&o)[0].contains("'cookie'"));
o.privacy_mode = true;
o.block_third_party = true;
assert!(page_scripts(&o)[0].contains("__nacrePriv") && page_scripts(&o)[0].contains("'cookie'"));
}
#[test]
fn messages() {
let m = parse_message("abc", r#"abc{"t":"media","d":{"title":"x"}}"#).unwrap();

View file

@ -28,6 +28,7 @@
//! install_script <url> (a .user.js / .user.css), open_app [id] (default: the first installed app),
//! navigate <typed text>, mute, pin
//! js <script> run JavaScript in the current tab; the result goes to the log
//! save <name> <js> run JavaScript in the current tab and write its string result to <name>.json
//! assert <js expression> the expression must give true, else `ASSERT FAILED` in the log fails the smoke run
//! expect <pointer> <json> a value of the `status` JSON must equal json (e.g. `expect /tabs/1/pinned true`;
//! `/active/...` is the active tab, `/tab_count` the number of tabs; `> n` a number above n)
@ -438,6 +439,27 @@ impl App {
}
});
},
"save" => {
let (name, script) = rest.split_once(' ').unwrap_or((rest, "null"));
let Some(web) = self.windows.get(&window).and_then(|w| w.active_webview()).cloned() else {
self.selftest_log(&format!("ASSERT FAILED (no page): save {name}"));
return;
};
let (log_path, out) = (dir.join("selftest.log"), dir.join(format!("{name}.json")));
web.evaluate_javascript(script.to_owned(), move |result| {
use std::io::Write as _;
let line = match result {
Ok(servo::JSValue::String(text)) => match std::fs::write(&out, text) {
Ok(()) => format!("saved {}", out.display()),
Err(error) => format!("ASSERT FAILED (save): {error}"),
},
other => format!("ASSERT FAILED (save gave {other:?})"),
};
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&log_path) {
let _ = writeln!(f, "{line}");
}
});
},
"pagescroll" => {
// Turn the wheel over the page at x,y (page pixels, as `click`) by dy pixels, through `window_input`.
let mut parts = rest.split_whitespace().filter_map(|p| p.parse::<f64>().ok());
@ -719,7 +741,7 @@ impl App {
.map(|(i, t)| {
serde_json::json!({
"active": i == w.active, "url": t.shown_url(), "title": t.display_title(), "loading": t.loading(),
"load_status": format!("{:?}", t.load_status), "has_web": t.web.is_some(), "blocked": t.blocked,
"load_status": format!("{:?}", t.load_status), "has_web": t.web.is_some(), "frozen": t.frozen, "blocked": t.blocked,
"hidden_elements": t.hidden_elements, "pinned": t.pinned, "muted": t.muted, "zoom": t.zoom,
"favicon": t.favicon.is_some(), "crashed": t.crashed, "can_back": t.can_go_back(), "can_forward": t.can_go_forward(),
"history_len": t.back_forward.len(), "find": [t.find.index, t.find.count], "prompts": t.prompts.len(),
@ -745,6 +767,7 @@ impl App {
serde_json::json!({
"windows": self.windows.len(),
"tab_count": tabs.len(),
"cookies": crate::store::cookies::keeping().map(|k| format!("{k:?}")),
"active_index": self.windows.get(&window).map(|w| w.active),
"fullscreen": self.windows.get(&window).map(|w| w.fullscreen),
"frames": frames,

271
src/store/cookies.rs Normal file
View file

@ -0,0 +1,271 @@
//! Cookies encrypted at rest (R1-19).
//!
//! Servo 0.7 keeps its cookie jar as plain JSON (`engine/cookie_jar.json`), which an infostealer copying the profile
//! can replay to take over signed-in sessions. The vendored servo-net hands the jar to Nacre instead
//! (`net::nacre::set_cookie_persistence`); Nacre keeps it in `cookies.bin`, sealed like the vault
//! (XChaCha20-Poly1305) with a 256-bit key held in the OS keyring: Secret Service (GNOME Keyring, KWallet) on Linux,
//! Credential Manager on Windows. The file alone is useless without the user's unlocked keyring.
//!
//! - Loaded before Servo starts; saved every few seconds when the jar changed, and when Servo exits.
//! - A plain cookie_jar.json from older builds is read once and deleted after the first encrypted save reads back.
//! - No keyring: cookies stay in memory for this run only (nothing plain is written); Settings says so.
//! - A file that doesn't decrypt (key gone, keyring reset) is moved to `cookies-unreadable-<time>.bin`, never
//! deleted; it opens again if the old key comes back into the keyring.
//! - Incognito: nothing is read or written.
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;
use crate::store::vault::{seal, unseal};
use crate::util;
pub const FILE: &str = "cookies.bin";
/// The plain jar Servo writes into its config dir.
pub const PLAIN_FILE: &str = "cookie_jar.json";
const MAGIC: &[u8] = b"NACRECK1";
const AAD: &[u8] = b"nacre-cookies-v1";
const KEYRING_SERVICE: &str = "Nacre";
const SAVE_EVERY: Duration = Duration::from_secs(5);
static KEEPING: OnceLock<Keeping> = OnceLock::new();
/// How this run keeps cookies between restarts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Keeping {
Encrypted,
NoKeyring,
Incognito,
}
impl Keeping {
pub fn describe(self) -> &'static str {
match self {
Keeping::Encrypted => "Encrypted on disk with a key in your system keyring",
Keeping::NoKeyring => "No system keyring found: cookies are kept until Nacre closes, never written unencrypted",
Keeping::Incognito => "Incognito: cookies are never written to disk",
}
}
}
/// How cookies are kept in this run (`None` before the engine started).
pub fn keeping() -> Option<Keeping> {
KEEPING.get().copied()
}
pub fn encrypt(key: &[u8; 32], json: &[u8]) -> Vec<u8> {
let mut out = MAGIC.to_vec();
out.extend(seal(key, AAD, json));
out
}
pub fn decrypt(key: &[u8; 32], bytes: &[u8]) -> Option<Vec<u8>> {
unseal(key, AAD, bytes.strip_prefix(MAGIC)?)
}
fn digest(json: &[u8]) -> u64 {
let mut hasher = DefaultHasher::new();
json.hash(&mut hasher);
hasher.finish()
}
#[derive(Default)]
struct SaveState {
/// Digest of the jar last written, to skip unchanged saves.
last: Option<u64>,
/// A plain jar still waiting to be deleted once the encrypted copy is safe.
plain: Option<PathBuf>,
/// Servo has exited and the final jar is written: later saves would be older.
closed: bool,
}
pub struct CookieStore {
path: PathBuf,
key: [u8; 32],
state: Mutex<SaveState>,
}
impl CookieStore {
/// Opens `dir/cookies.bin` and returns the jar to start with: the decrypted file, or else the plain jar at
/// `plain` (migration). A file that doesn't decrypt is moved aside.
pub fn open(dir: &Path, plain: &Path, key: [u8; 32]) -> (CookieStore, Option<Vec<u8>>) {
let path = dir.join(FILE);
let mut initial = None;
match std::fs::read(&path) {
Ok(bytes) => match decrypt(&key, &bytes) {
Some(json) => initial = Some(json),
None => {
let aside = dir.join(format!("cookies-unreadable-{}.bin", util::now()));
log::warn!("cookies: {} doesn't decrypt with the keyring key; moved to {}", path.display(), aside.display());
if let Err(e) = std::fs::rename(&path, &aside) {
log::warn!("cookies: could not move it aside: {e}");
}
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => log::warn!("cookies: can't read {}: {e}", path.display()),
}
let plain = plain.exists().then(|| plain.to_path_buf());
if let (None, Some(plain)) = (&initial, &plain) {
log::info!("cookies: moving the plain cookie jar into the encrypted store");
initial = std::fs::read(plain).ok();
}
let state = SaveState { plain, ..SaveState::default() };
(CookieStore { path, key, state: Mutex::new(state) }, initial)
}
/// Writes the jar if it changed. True when written.
pub fn save(&self, json: &[u8]) -> bool {
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
let digest = digest(json);
if state.closed || state.last == Some(digest) {
return false;
}
if let Err(e) = util::write_atomic(&self.path, &encrypt(&self.key, json), true) {
log::warn!("cookies: not saved: {e}");
return false;
}
state.last = Some(digest);
if let Some(plain) = state.plain.take() {
let reads_back = std::fs::read(&self.path).ok().and_then(|b| decrypt(&self.key, &b)).is_some_and(|b| b == json);
if reads_back && std::fs::remove_file(&plain).is_ok() {
log::info!("cookies: plain cookie jar deleted");
} else {
state.plain = Some(plain);
}
}
true
}
/// The last save (Servo's exit): nothing after it may overwrite the file.
pub fn close(&self) {
self.state.lock().unwrap_or_else(|e| e.into_inner()).closed = true;
}
fn closed(&self) -> bool {
self.state.lock().unwrap_or_else(|e| e.into_inner()).closed
}
}
/// The cookie key from the OS keyring, made on first use. `None` when there is no usable keyring.
fn keyring_key(account: &str) -> Option<[u8; 32]> {
let entry = keyring::Entry::new(KEYRING_SERVICE, account).map_err(|e| log::warn!("cookies: no keyring: {e}")).ok()?;
let text = match entry.get_password() {
Ok(text) => text,
Err(keyring::Error::NoEntry) => {
let mut key = [0u8; 32];
util::random_bytes(&mut key);
let text = B64.encode(key);
if let Err(e) = entry.set_password(&text) {
log::warn!("cookies: keyring refused the key: {e}");
return None;
}
log::info!("cookies: new key stored in the keyring");
// Read it back: a keyring that drops what it is given would lose every cookie at the next start.
entry.get_password().ok().filter(|t| *t == text)?
}
Err(e) => {
log::warn!("cookies: keyring unavailable: {e}");
return None;
}
};
B64.decode(text.trim()).ok()?.try_into().ok()
}
/// Wires Servo's cookie jar to Nacre before Servo starts (see the module docs). `data` is the profile's data folder,
/// `engine` Servo's config dir (where the plain jar may be).
pub fn start(data: &Path, engine: &Path, incognito: bool) -> Keeping {
let keeping = if incognito {
net::nacre::set_cookie_persistence(None, Box::new(|_| {}));
Keeping::Incognito
} else if let Some(key) = keyring_key(&format!("cookies {}", data.display())) {
let (store, initial) = CookieStore::open(data, &engine.join(PLAIN_FILE), key);
let store = Arc::new(store);
let at_exit = store.clone();
net::nacre::set_cookie_persistence(
initial,
Box::new(move |json| {
at_exit.save(json);
at_exit.close();
}),
);
let _ = std::thread::Builder::new().name("cookie-saver".into()).spawn(move || {
while !store.closed() {
std::thread::sleep(SAVE_EVERY);
if let Some(json) = net::nacre::cookie_jar_snapshot() {
store.save(&json);
}
}
});
Keeping::Encrypted
} else {
// Use the old plain jar for this run, but write nothing.
net::nacre::set_cookie_persistence(std::fs::read(engine.join(PLAIN_FILE)).ok(), Box::new(|_| {}));
Keeping::NoKeyring
};
let _ = KEEPING.set(keeping);
log::info!("cookies: {keeping:?}");
keeping
}
#[cfg(test)]
mod tests {
use super::*;
const JAR: &[u8] = br#"{"version":1,"cookies_map":{"example.com":[]},"max_per_host":150}"#;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("nacre-cookies-{name}-{}", util::random_hex(6)));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn round_trip() {
let dir = temp_dir("round");
let key = [7u8; 32];
let (store, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), key);
assert!(initial.is_none());
assert!(store.save(JAR));
assert!(!store.save(JAR), "unchanged jar is not written again");
let bytes = std::fs::read(dir.join(FILE)).unwrap();
assert!(!bytes.windows(11).any(|w| w == b"example.com"), "no plain text on disk");
assert!(decrypt(&[8u8; 32], &bytes).is_none(), "unreadable without the key");
let (_, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), key);
assert_eq!(initial.as_deref(), Some(JAR));
store.close();
assert!(!store.save(b"{}"), "nothing after the exit save");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn migrates_plain_jar() {
let dir = temp_dir("migrate");
let plain = dir.join(PLAIN_FILE);
std::fs::write(&plain, JAR).unwrap();
let (store, initial) = CookieStore::open(&dir, &plain, [1u8; 32]);
assert_eq!(initial.as_deref(), Some(JAR));
assert!(plain.exists(), "plain jar kept until the encrypted copy is saved");
assert!(store.save(JAR));
assert!(!plain.exists());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn wrong_key_moves_file_aside() {
let dir = temp_dir("aside");
let (store, _) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), [1u8; 32]);
store.save(JAR);
let (_, initial) = CookieStore::open(&dir, &dir.join(PLAIN_FILE), [2u8; 32]);
assert!(initial.is_none());
assert!(!dir.join(FILE).exists());
let aside: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.file_name().to_string_lossy().starts_with("cookies-unreadable-")).collect();
assert_eq!(aside.len(), 1, "the unreadable file is kept");
let _ = std::fs::remove_dir_all(dir);
}
}

View file

@ -2,6 +2,7 @@
pub mod apps;
pub mod bookmarks;
pub mod cookies;
pub mod downloads;
pub mod history;
pub mod permissions;

View file

@ -231,6 +231,8 @@ pub struct Privacy {
/// Privacy mode: fingerprint noise and tracking cuts.
pub mode: bool,
pub mode_incognito: bool,
/// Sites where privacy mode's fingerprint protection is paused (it breaks something there).
pub mode_off: Vec<String>,
pub block_third_party: bool,
pub strip_params: bool,
pub https_only: bool,
@ -253,6 +255,7 @@ impl Default for Privacy {
dnt: true,
mode: false,
mode_incognito: true,
mode_off: Vec::new(),
block_third_party: true,
strip_params: true,
https_only: false,
@ -607,6 +610,10 @@ impl Settings {
self.adblock.allow.iter().any(|h| util::host_matches(host, h))
}
pub fn privacy_paused_on(&self, host: &str) -> bool {
self.privacy.mode_off.iter().any(|h| util::host_matches(host, h))
}
pub fn keeps_active(&self, host: &str) -> bool {
self.perf.keep_active.iter().any(|h| util::host_matches(host, h))
}

View file

@ -123,22 +123,24 @@ impl std::fmt::Display for VaultError {
}
}
fn seal(key: &[u8; 32], plain: &[u8]) -> Vec<u8> {
/// XChaCha20-Poly1305 with a fresh random nonce: nonce || ciphertext. `aad` names what is sealed. Also used by the
/// cookie store.
pub(crate) fn seal(key: &[u8; 32], aad: &[u8], plain: &[u8]) -> Vec<u8> {
let cipher = XChaCha20Poly1305::new(chacha20poly1305::Key::from_slice(key));
let mut nonce = [0u8; 24];
util::random_bytes(&mut nonce);
let sealed = cipher.encrypt(XNonce::from_slice(&nonce), Payload { msg: plain, aad: AAD }).expect("encryption with a valid key cannot fail");
let sealed = cipher.encrypt(XNonce::from_slice(&nonce), Payload { msg: plain, aad }).expect("encryption with a valid key cannot fail");
let mut out = nonce.to_vec();
out.extend(sealed);
out
}
fn unseal(key: &[u8; 32], blob: &[u8]) -> Option<Vec<u8>> {
pub(crate) fn unseal(key: &[u8; 32], aad: &[u8], blob: &[u8]) -> Option<Vec<u8>> {
if blob.len() < 24 + 16 {
return None;
}
let cipher = XChaCha20Poly1305::new(chacha20poly1305::Key::from_slice(key));
cipher.decrypt(XNonce::from_slice(&blob[..24]), Payload { msg: &blob[24..], aad: AAD }).ok()
cipher.decrypt(XNonce::from_slice(&blob[..24]), Payload { msg: &blob[24..], aad }).ok()
}
fn password_key(password: &str, salt: &[u8]) -> [u8; 32] {
@ -211,7 +213,7 @@ impl Vault {
self.contents = Contents::default();
} else {
let blob = B64.decode(&self.meta.data).map_err(|e| VaultError::Damaged(e.to_string()))?;
let plain = unseal(&key, &blob).ok_or(VaultError::WrongPassword)?;
let plain = unseal(&key, AAD, &blob).ok_or(VaultError::WrongPassword)?;
self.contents = serde_json::from_slice(&plain).map_err(|e| VaultError::Damaged(e.to_string()))?;
}
self.key = Some(key);
@ -235,7 +237,7 @@ impl Vault {
let salt = B64.decode(&self.meta.salt).map_err(|e| VaultError::Damaged(e.to_string()))?;
let wrapped = B64.decode(&self.meta.wrapped).map_err(|e| VaultError::Damaged(e.to_string()))?;
let kek = password_key(password, &salt);
let key_bytes = unseal(&kek, &wrapped).ok_or(VaultError::WrongPassword)?;
let key_bytes = unseal(&kek, AAD, &wrapped).ok_or(VaultError::WrongPassword)?;
let key = <[u8; 32]>::try_from(key_bytes.as_slice()).map_err(|_| VaultError::Damaged("bad key".into()))?;
self.unlock_with(key)?;
self.last_auth = util::now();
@ -249,7 +251,7 @@ impl Vault {
}
let Ok(salt) = B64.decode(&self.meta.salt) else { return false };
let Ok(wrapped) = B64.decode(&self.meta.wrapped) else { return false };
let ok = unseal(&password_key(password, &salt), &wrapped).is_some();
let ok = unseal(&password_key(password, &salt), AAD, &wrapped).is_some();
if ok {
self.last_auth = util::now();
}
@ -286,7 +288,7 @@ impl Vault {
return Ok(());
}
let plain = serde_json::to_vec(&self.contents).map_err(|e| VaultError::Io(e.to_string()))?;
self.meta.data = B64.encode(seal(&key, &plain));
self.meta.data = B64.encode(seal(&key, AAD, &plain));
util::save_json_private(&self.path, &self.meta).map_err(|e| VaultError::Io(e.to_string()))
}
@ -297,7 +299,7 @@ impl Vault {
util::random_bytes(&mut salt);
let kek = password_key(password, &salt);
self.meta.salt = B64.encode(salt);
self.meta.wrapped = B64.encode(seal(&kek, &key));
self.meta.wrapped = B64.encode(seal(&kek, AAD, &key));
self.meta.mode = Mode::Master;
self.save()?;
if !self.read_only {

View file

@ -853,7 +853,27 @@ fn shield_body(ui: &mut Ui, f: &mut Frame) {
});
let on = if incognito { &mut settings.privacy.mode_incognito } else { &mut settings.privacy.mode };
line(ui, "Hide this browser's fingerprint", |ui| switch(ui, on));
text(ui, if incognito { "Incognito windows: canvas, WebGL, screen and hardware details, from the next page load" } else { "Canvas, WebGL, screen and hardware details, from the next page load" }, true);
let on = *on;
if on && !host.is_empty() {
let mut on_here = !settings.privacy_paused_on(&host);
line(ui, &format!("On {}", util::ellipsize(&host, 30)), |ui| {
if switch(ui, &mut on_here) {
if on_here {
settings.privacy.mode_off.retain(|h| !util::host_matches(&host, h));
} else {
settings.privacy.mode_off.push(host.clone());
}
}
});
}
let what = if on {
"Canvas, WebGL, audio and fonts get noise; screen, CPU and system read common values; third-party cookies are blocked. Time zone and language stay real. From the next page load"
} else if incognito {
"Incognito windows: noise on canvas, WebGL, audio and fonts, common screen and hardware values, no third-party cookies"
} else {
"Noise on canvas, WebGL, audio and fonts, common screen and hardware values, no third-party cookies"
};
text(ui, what, true);
ui.add_space(theme::GAP_S);
divider(ui);

View file

@ -41,6 +41,7 @@ const SUBPAGES: &[(&str, &str, &str)] = &[
("keys", "Keyboard shortcuts", "general"),
("import", "Import from another browser", "general"),
("newtab", "New tab page", "general"),
("privacy_mode", "Privacy mode", "privacy"),
("permissions", "Site permissions", "privacy"),
("lists", "Filter lists", "adblock"),
("managers", "Download managers", "downloads"),
@ -261,6 +262,7 @@ fn section_keywords(key: &str) -> &'static str {
"about" => "version update",
"newtab" => "new tab page clock greeting weather background shortcuts customize",
"keys" => "hotkeys keybindings",
"privacy_mode" => "fingerprint canvas webgl audio fonts screen incognito cover your tracks",
_ => "",
}
}
@ -345,6 +347,7 @@ fn draw_section(ui: &mut Ui, f: &mut Frame, s: &mut Settings, key: &str) {
"keys" => keys(ui, f, s),
"import" => import(ui, f, s),
"newtab" => newtab(ui, f, s),
"privacy_mode" => privacy_mode(ui, f, s),
"permissions" => permissions(ui, f, s),
"lists" => lists(ui, f, s),
"managers" => managers(ui, f, s),
@ -717,7 +720,7 @@ fn performance(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
switch_row(ui, "Preload pages", "Looks up the addresses of links on a page ahead of time", &mut s.web.preload);
switch_row(ui, "Smooth scrolling", "Animated scrolling (off in low-memory mode)", &mut s.web.smooth_scroll);
switch_row(ui, "Still new tab background", "No animation on the new tab page", &mut s.perf.still_ntp);
limited_row(ui, "Save data", "Tells pages to be lighter and stops videos preloading", "Servo can't send the Save-Data header", |ui| switch(ui, &mut s.privacy.save_data));
switch_row(ui, "Save data", "Sends Save-Data so pages can be lighter, and stops videos preloading", &mut s.privacy.save_data);
row(ui, "Hardware acceleration", "Use the GPU. Turn off if pages show up black or blank; Off uses software rendering (restart to apply)", |ui| segmented(ui, &mut s.web.gpu, AutoOnOff::ALL));
});
}
@ -751,11 +754,17 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
});
section(ui, "Tracking and fingerprinting");
card(ui, |ui| {
row(ui, "Privacy mode", "Hides your browser's fingerprint (canvas, WebGL, screen and hardware details)", |ui| switch(ui, &mut s.privacy.mode));
switch_row(ui, "Privacy mode in incognito windows", "", &mut s.privacy.mode_incognito);
limited_row(ui, "Send Do Not Track and Global Privacy Control", "Pages see navigator.globalPrivacyControl", "Servo can't add the request headers yet", |ui| switch(ui, &mut s.privacy.dnt));
let state = match (s.privacy.mode, s.privacy.mode_incognito) {
(true, _) => "On: fingerprint hidden, third-party cookies blocked",
(false, true) => "On in incognito windows only",
(false, false) => "Off: sites can fingerprint this browser",
};
if icon_link_row(ui, icons::FINGERPRINT, "Privacy mode", state) {
open(f, "privacy_mode");
}
switch_row(ui, "Send Do Not Track and Global Privacy Control", "Asks every site not to sell or share your data (DNT and Sec-GPC headers)", &mut s.privacy.dnt);
switch_row(ui, "Remove tracking parameters", "Strips utm_, fbclid, gclid and similar from links before they load", &mut s.privacy.strip_params);
unavailable_row(ui, "Block third-party cookies", "Servo 0.7 has no cookie policy setting");
switch_row(ui, "Block third-party cookies", "Sites inside a page (ads, trackers) can't send or store cookies; always on in privacy mode", &mut s.privacy.block_third_party);
switch_row(ui, "Google sign-in", "Looks like Firefox on accounts.google.com so Google lets you sign in", &mut s.privacy.google_signin);
});
section(ui, "Site data");
@ -766,6 +775,9 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
if icon_row(ui, icons::DELETE, "Delete browsing data", "History, cookies, cache and more", |ui| button(ui, ButtonKind::Tonal, None, "Delete…").clicked()) {
f.send(Command::ShowPage(Page::ClearData));
}
if let Some(keeping) = crate::store::cookies::keeping() {
icon_row(ui, icons::COOKIE, "Cookies on disk", keeping.describe(), |_| {});
}
wide_row(ui, "Delete when Nacre closes", "", |ui| {
toggle_chips(ui, &mut s.privacy.clear_on_exit, &[("history", "History"), ("cookies", "Cookies"), ("cache", "Cache"), ("downloads", "Downloads list")]);
});
@ -778,6 +790,34 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
});
}
fn privacy_mode(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
intro(ui, "Hides what makes this browser stand out from others, so sites can't recognise you without cookies. Applies from each page's next load.");
card(ui, |ui| {
icon_row(ui, icons::FINGERPRINT, "Use privacy mode", "Some canvas-based tools can look slightly different; pause it on a site from the shield menu", |ui| switch(ui, &mut s.privacy.mode));
icon_row(ui, icons::DOMINO_MASK, "Always on in incognito windows", "Incognito windows use privacy mode even when it's off here", |ui| switch(ui, &mut s.privacy.mode_incognito));
});
section(ui, "What it hides");
card(ui, |ui| {
icon_row(ui, icons::PALETTE, "Canvas, WebGL and audio fingerprints", "Tiny noise, different on every site and after every restart, stable within a site", |_| {});
icon_row(ui, icons::MEMORY, "Graphics, screen size and CPU", "Sites see common values: a common screen size, 8 cores, \"Mozilla\" graphics", |_| {});
icon_row(ui, icons::TEXTURE, "Installed fonts", "Font probes on canvas see every font as installed", |_| {});
icon_row(ui, icons::DEVICES, "System details", "Platform and version match the user agent, as in Firefox", |_| {});
icon_row(ui, icons::COOKIE, "Third-party cookies", "Ads and trackers inside pages can't set or read cookies", |_| {});
});
section(ui, "Not hidden");
card(ui, |ui| {
icon_row(ui, icons::SCHEDULE, "Time zone and language", "Changing them breaks clocks, calendars and sites in your language; they stay consistent with each other", |_| {});
icon_row(ui, icons::INFO, "Limits of the engine", "Fonts measured in the page layout, scripts in web workers, plugins list and the engine's own features (no WebRTC, no battery)", |_| {});
});
section(ui, "Sites");
card(ui, |ui| {
wide_row(ui, "Sites where privacy mode is paused", "", |ui| host_chips(ui, &mut s.privacy.mode_off, "Use privacy mode here again", "None"));
if icon_row(ui, icons::OPEN_IN_NEW, "Check your fingerprint", "EFF's Cover Your Tracks test", |ui| button(ui, ButtonKind::Tonal, None, "Test it").clicked()) {
f.send(Command::Open { url: "https://coveryourtracks.eff.org/".into(), how: crate::actions::Disposition::NewForegroundTab, from: None });
}
});
}
fn adblock(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
section(ui, "Blocking");
card(ui, |ui| {