Nacre/src/store/settings.rs
astar76 68346f0edb S024: privacy mode that holds up (R1-16)
Firefox-consistent anti-fingerprinting script (canvas/WebGL/audio/font noise per run and site; common screen,
CPU, platform, touch and WebGL values; frames covered), paused per site, on in incognito. Privacy mode also
switches third-party cookie blocking and a Firefox-style Accept-Language in the vendored servo-net;
document.cookie is emptied in cross-site frames. Engine gaps fixed on the way: screen geometry (was 0x0),
document.fonts.check, a pass-through DynamicsCompressorNode. Settings sub-page and shield flyout explain it.
Tests: unit tests, privacy-mode/incognito/net smokes, Cover Your Tracks run recorded in
docs/engine/privacy-mode.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 17:13:08 -06:00

659 lines
23 KiB
Rust

//! Every setting, with its default. Saved as `settings.json` in the profile's config folder.
//!
//! Missing keys take their default, unknown keys are kept out, so files from older and newer
//! versions both load.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::util;
/// Declares a setting enum with the labels shown in settings. The first variant is the default.
macro_rules! choices {
($(#[$meta:meta])* $name:ident { $first:ident = $first_label:literal $(, $variant:ident = $label:literal)* $(,)? }) => {
$(#[$meta])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum $name {
#[default]
$first,
$($variant,)*
}
impl $name {
pub const ALL: &'static [($name, &'static str)] = &[($name::$first, $first_label) $(, ($name::$variant, $label))*];
pub fn label(self) -> &'static str {
Self::ALL.iter().find(|(v, _)| *v == self).map(|(_, l)| *l).unwrap_or("")
}
}
};
}
choices!(StartupMode { NewTab = "New tab", Restore = "Restore", Home = "Home page" });
choices!(ThemeMode { System = "System", Light = "Light", Dark = "Dark" });
choices!(ColourSource { Website = "Website", System = "System accent", Palette = "Palette", Custom = "Custom" });
choices!(ColourFallback { System = "System accent", Palette = "Palette" });
choices!(WebScheme { Auto = "Like Nacre", Light = "Light", Dark = "Dark" });
choices!(Motion { Normal = "Normal", Off = "Off", Fast = "Fast", Slow = "Slow" });
choices!(Roundness { Normal = "Default", Subtle = "Subtle", Round = "Round" });
choices!(BookmarksBar { NewTab = "New tab only", Always = "Always", Never = "Never" });
choices!(AutoOnOff { Auto = "Auto", On = "On", Off = "Off" });
choices!(EnergySaver { Off = "Off", Battery = "On battery", On = "Always" });
choices!(MediaButton { Auto = "When playing", Always = "Always", Never = "Never" });
choices!(Visualizer { Auto = "Auto", Simulated = "Simulated", Off = "Off" });
choices!(VpnProvider { Tor = "Tor", Custom = "Custom proxy" });
choices!(DohProvider { Off = "Off", Cloudflare = "Cloudflare", Quad9 = "Quad9", Google = "Google", Mullvad = "Mullvad", Adguard = "AdGuard", Custom = "Custom" });
choices!(RpcTarget { Arrpc = "arRPC", Discord = "Discord" });
choices!(RpcBrowsing { Off = "Off", Site = "Site name", Title = "Page title" });
choices!(RpcBrowseType { Watch = "Watching", Listen = "Listening" });
choices!(RpcDisplay { Details = "Details", Name = "Name", State = "State" });
choices!(PermissionDefault { Ask = "Ask", Allow = "Allow", Block = "Block" });
choices!(NtpBackground { Shapes = "Shapes", Off = "None", Blobs = "Blobs", Particles = "Constellation", Waves = "Waves", Dots = "Dot grid" });
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Theme {
pub mode: ThemeMode,
pub source: ColourSource,
pub fallback: ColourFallback,
pub preset: String,
pub custom: String,
/// Scheme style: tonal_spot, vibrant, expressive, neutral, monochrome, fidelity, content.
pub variant: String,
pub contrast: f32,
}
impl Default for Theme {
fn default() -> Self {
Self {
mode: ThemeMode::System,
source: ColourSource::Website,
fallback: ColourFallback::System,
preset: "#6750A4".to_owned(),
custom: "#3F6EE8".to_owned(),
variant: "tonal_spot".to_owned(),
contrast: 0.0,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Ui {
pub motion: Motion,
pub roundness: Roundness,
/// Draw our own title bar instead of the system's (restart to apply).
pub custom_title_bar: bool,
/// Page shown as a rounded card with a margin.
pub floating_card: bool,
pub bookmarks_bar: BookmarksBar,
/// Toolbar buttons that are shown, by key (see `ui::chrome::TOOLBAR_BUTTONS`).
pub toolbar: Vec<String>,
/// Interface scale; 1.0 follows the system.
pub scale: f32,
}
impl Default for Ui {
fn default() -> Self {
Self {
motion: Motion::Normal,
roundness: Roundness::Normal,
custom_title_bar: false,
floating_card: true,
bookmarks_bar: BookmarksBar::NewTab,
toolbar: ["back", "forward", "reload", "home", "incognito", "passwords", "history", "downloads", "qr", "devtools", "adblock", "media"].iter().map(|s| (*s).to_owned()).collect(),
scale: 1.0,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Web {
pub force_dark: bool,
pub smooth_scroll: bool,
/// Look up the addresses of links on a page ahead of time.
pub preload: bool,
pub scheme: WebScheme,
/// Hardware acceleration (restart to apply). Off uses software GL.
pub gpu: AutoOnOff,
/// Default page zoom and per-site zoom (host -> factor).
pub zoom: f32,
pub zoom_sites: BTreeMap<String, f32>,
/// Empty = Nacre's own user agent.
pub user_agent: String,
/// Firefox remote debugging (about:debugging → localhost:6080), restart to apply.
pub remote_debugging: bool,
}
impl Default for Web {
fn default() -> Self {
Self { force_dark: false, smooth_scroll: true, preload: true, scheme: WebScheme::Auto, gpu: AutoOnOff::Auto, zoom: 1.0, zoom_sites: BTreeMap::new(), user_agent: String::new(), remote_debugging: false }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Startup {
pub mode: StartupMode,
pub home_url: String,
pub search_engine: String,
/// Search engines added by the user: (name, URL with %s).
pub custom_engines: Vec<(String, String)>,
pub search_suggestions: bool,
pub welcome_done: bool,
pub import_offered: bool,
pub import_done: Vec<String>,
}
impl Default for Startup {
fn default() -> Self {
Self {
mode: StartupMode::NewTab,
home_url: "nacre://newtab".to_owned(),
search_engine: "duckduckgo".to_owned(),
custom_engines: Vec::new(),
search_suggestions: true,
welcome_done: false,
import_offered: false,
import_done: Vec::new(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Perf {
/// Low-memory mode: fewer processes and threads, tabs rest sooner, lighter pages.
pub lite: AutoOnOff,
pub energy: EnergySaver,
pub still_ntp: bool,
/// Hosts whose tabs are never frozen or unloaded.
pub keep_active: Vec<String>,
pub lazy_restore: bool,
/// Freeze hidden, silent tabs after this many minutes (0 = never).
pub freeze_min: u32,
/// Unload them after this many minutes (0 = never).
pub discard_min: u32,
}
impl Default for Perf {
fn default() -> Self {
Self { lite: AutoOnOff::Auto, energy: EnergySaver::Off, still_ntp: false, keep_active: Vec::new(), lazy_restore: true, freeze_min: 5, discard_min: 60 }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct AdBlock {
pub enabled: bool,
/// Keys of the built-in lists that are on (see `adblock::LISTS`).
pub lists: Vec<String>,
/// Extra list URLs.
pub custom: Vec<String>,
/// The user's own filter rules, one per line.
pub own_rules: String,
pub cosmetic: bool,
pub youtube: bool,
pub animate: bool,
/// Days between list updates; 0 = manual only.
pub update_days: u32,
/// Hosts where blocking is paused.
pub allow: Vec<String>,
pub total: u64,
pub last_update: u64,
}
impl Default for AdBlock {
fn default() -> Self {
Self {
enabled: true,
lists: ["easylist", "ublock", "pgl", "easyprivacy", "ublock_privacy", "ublock_badware", "urlhaus", "ublock_quick", "ublock_unbreak", "cookies"].iter().map(|s| (*s).to_owned()).collect(),
custom: Vec::new(),
own_rules: String::new(),
cosmetic: true,
youtube: true,
animate: true,
update_days: 7,
allow: Vec::new(),
total: 0,
last_update: 0,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Privacy {
/// Send Do Not Track and Global Privacy Control.
pub dnt: bool,
/// 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,
/// Hosts the user chose to open over http anyway.
pub https_exceptions: Vec<String>,
pub doh: DohProvider,
pub doh_custom: String,
pub save_data: bool,
/// Look like Firefox on accounts.google.com so Google lets you sign in.
pub google_signin: bool,
/// Default answer per permission (missing = ask). Keys are `store::permissions::Kind` names.
pub permission_defaults: BTreeMap<String, PermissionDefault>,
/// Clear these when the browser closes: history, cookies, cache, downloads.
pub clear_on_exit: Vec<String>,
}
impl Default for Privacy {
fn default() -> Self {
Self {
dnt: true,
mode: false,
mode_incognito: true,
mode_off: Vec::new(),
block_third_party: true,
strip_params: true,
https_only: false,
https_exceptions: Vec::new(),
doh: DohProvider::Off,
doh_custom: String::new(),
save_data: false,
google_signin: true,
permission_defaults: BTreeMap::new(),
clear_on_exit: Vec::new(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Downloads {
pub dir: PathBuf,
pub ask: bool,
/// Show the downloads list when a download starts.
pub auto_open: bool,
/// "builtin" or a key from `net::dlm::MANAGERS`: where new downloads go.
pub manager: String,
/// Managers turned on in settings.
pub managers: Vec<String>,
pub abdm_port: u16,
pub aria2_port: u16,
pub aria2_secret: String,
pub jd_port: u16,
pub fdm_path: String,
pub idm_path: String,
}
impl Default for Downloads {
fn default() -> Self {
Self {
dir: dirs::download_dir().or_else(|| dirs::home_dir().map(|h| h.join("Downloads"))).unwrap_or_else(|| PathBuf::from(".")),
ask: false,
auto_open: true,
manager: "builtin".to_owned(),
managers: Vec::new(),
abdm_port: 15151,
aria2_port: 6800,
aria2_secret: String::new(),
jd_port: 9666,
fdm_path: String::new(),
idm_path: String::new(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Vpn {
pub enabled: bool,
pub provider: VpnProvider,
/// socks5://host:port or http://host:port
pub custom: String,
}
impl Default for Vpn {
fn default() -> Self {
Self { enabled: false, provider: VpnProvider::Tor, custom: String::new() }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Media {
pub button: MediaButton,
pub visualizer: Visualizer,
pub spin: bool,
/// Hosts muted with "Mute site".
pub muted_sites: Vec<String>,
}
impl Default for Media {
fn default() -> Self {
Self { button: MediaButton::Auto, visualizer: Visualizer::Auto, spin: true, muted_sites: Vec::new() }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Rpc {
pub enabled: bool,
pub target: RpcTarget,
/// Discord application ID (discord.com/developers -> New Application).
pub client_id: String,
/// Extra media sites to report.
pub custom: Vec<String>,
/// Supported sites switched off.
pub disabled_sites: Vec<String>,
/// Site -> its own Discord application ID.
pub site_ids: BTreeMap<String, String>,
pub browsing: RpcBrowsing,
pub browse_type: RpcBrowseType,
pub display: RpcDisplay,
pub button: bool,
pub show_paused: bool,
}
impl Default for Rpc {
fn default() -> Self {
Self {
enabled: false,
target: RpcTarget::Arrpc,
// Nacre's own Discord application; users can put their own in settings.
client_id: "1560319659872485462".to_owned(),
custom: Vec::new(),
disabled_sites: Vec::new(),
site_ids: BTreeMap::new(),
browsing: RpcBrowsing::Off,
browse_type: RpcBrowseType::Watch,
display: RpcDisplay::Details,
button: true,
show_paused: true,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Spell {
pub enabled: bool,
/// e.g. ["en_US"]; empty = the system language.
pub langs: Vec<String>,
}
impl Default for Spell {
fn default() -> Self {
Self { enabled: true, langs: Vec::new() }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Update {
/// Release repository for the update check (a Forgejo/Gitea, GitLab or GitHub repo URL).
pub repo: String,
pub last_check: u64,
pub auto_check: bool,
/// Newest version seen, so the notice survives a restart.
pub available: String,
}
impl Default for Update {
fn default() -> Self {
Self { repo: "https://archlinux.tail7c4f5e.ts.net/git/astar76/Nacre".to_owned(), last_check: 0, auto_check: true, available: String::new() }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct VaultSettings {
/// Offer to save passwords and fill them in.
pub enabled: bool,
/// Fill automatically when a site has exactly one saved login.
pub autofill: bool,
/// Suggest saved addresses and cards.
pub autofill_forms: bool,
/// Master-password mode: lock after this many idle minutes (0 = never).
pub autolock_min: u32,
/// Ask for the master password again before revealing saved passwords.
pub reauth: bool,
pub reauth_min: u32,
pub gen_length: u32,
pub gen_symbols: bool,
/// Seconds before a copied password is wiped from the clipboard (0 = never).
pub clipboard_clear: u32,
}
impl Default for VaultSettings {
fn default() -> Self {
Self { enabled: true, autofill: true, autofill_forms: true, autolock_min: 15, reauth: true, reauth_min: 5, gen_length: 20, gen_symbols: true, clipboard_clear: 30 }
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Ntp {
pub bg: NtpBackground,
pub bg_density: String,
pub bg_speed: String,
pub bg_mouse: bool,
/// Image file in the data folder shown as the new tab background.
pub bg_image: String,
pub bg_dim: f32,
pub bg_blur: f32,
/// Elements on the new tab page, in order, each on or off.
pub elements: Vec<(String, bool)>,
pub clock24: bool,
pub seconds: bool,
pub name: String,
pub city: String,
pub city_loc: Option<(f64, f64)>,
pub units: String,
pub notes: String,
/// (title, url)
pub shortcuts: Vec<(String, String)>,
}
impl Default for Ntp {
fn default() -> Self {
// The order of the page in the user's recording (docs/UI-BRIEF.md); "recent" is the Top sites card.
let elements = [("greeting", true), ("clock", true), ("shortcuts", true), ("media", true), ("weather", true), ("search", true), ("notes", true), ("reading", true), ("recent", true)];
let shortcuts = [
("YouTube", "https://www.youtube.com"),
("GitHub", "https://github.com"),
("Reddit", "https://www.reddit.com"),
("Wikipedia", "https://wikipedia.org"),
("Arch Wiki", "https://wiki.archlinux.org"),
("YT Music", "https://music.youtube.com"),
];
Self {
bg: NtpBackground::Shapes,
bg_density: "medium".to_owned(),
bg_speed: "normal".to_owned(),
bg_mouse: true,
bg_image: String::new(),
bg_dim: 0.35,
bg_blur: 0.0,
elements: elements.iter().map(|(k, on)| ((*k).to_owned(), *on)).collect(),
clock24: false,
seconds: true,
name: String::new(),
city: String::new(),
city_loc: None,
units: "auto".to_owned(),
notes: String::new(),
shortcuts: shortcuts.iter().map(|(t, u)| ((*t).to_owned(), (*u).to_owned())).collect(),
}
}
}
/// Size and place of the last window, restored on start.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct WindowState {
pub width: u32,
pub height: u32,
pub maximized: bool,
}
impl Default for WindowState {
fn default() -> Self {
Self { width: 1280, height: 820, maximized: false }
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Settings {
pub theme: Theme,
pub ui: Ui,
pub web: Web,
pub startup: Startup,
pub perf: Perf,
pub adblock: AdBlock,
pub privacy: Privacy,
pub downloads: Downloads,
pub vpn: Vpn,
pub media: Media,
pub rpc: Rpc,
pub spell: Spell,
pub update: Update,
pub vault: VaultSettings,
pub ntp: Ntp,
pub window: WindowState,
/// Keyboard shortcut overrides: action name -> shortcut text ("Ctrl+Shift+T"), "" = unbound.
pub keys: BTreeMap<String, String>,
}
/// A built-in search engine.
pub struct SearchEngine {
pub key: &'static str,
pub name: &'static str,
/// Search URL; `%s` is the query.
pub url: &'static str,
/// Suggestions endpoint returning OpenSearch JSON (`["q", ["s1", "s2"]]`), or "".
pub suggest: &'static str,
}
pub const SEARCH_ENGINES: &[SearchEngine] = &[
SearchEngine { key: "duckduckgo", name: "DuckDuckGo", url: "https://duckduckgo.com/?q=%s", suggest: "https://duckduckgo.com/ac/?q=%s&type=list" },
SearchEngine { key: "google", name: "Google", url: "https://www.google.com/search?q=%s", suggest: "https://suggestqueries.google.com/complete/search?client=firefox&q=%s" },
SearchEngine { key: "bing", name: "Bing", url: "https://www.bing.com/search?q=%s", suggest: "https://api.bing.com/osjson.aspx?query=%s" },
SearchEngine { key: "brave", name: "Brave Search", url: "https://search.brave.com/search?q=%s", suggest: "https://search.brave.com/api/suggest?q=%s" },
SearchEngine { key: "startpage", name: "Startpage", url: "https://www.startpage.com/sp/search?query=%s", suggest: "" },
SearchEngine { key: "ecosia", name: "Ecosia", url: "https://www.ecosia.org/search?q=%s", suggest: "https://ac.ecosia.org/autocomplete?q=%s&type=list" },
SearchEngine { key: "qwant", name: "Qwant", url: "https://www.qwant.com/?q=%s", suggest: "" },
SearchEngine { key: "kagi", name: "Kagi", url: "https://kagi.com/search?q=%s", suggest: "" },
SearchEngine { key: "wikipedia", name: "Wikipedia", url: "https://en.wikipedia.org/wiki/Special:Search?search=%s", suggest: "https://en.wikipedia.org/w/api.php?action=opensearch&search=%s" },
];
impl Settings {
pub fn load(path: &Path) -> Settings {
util::load_json(path)
}
pub fn save(&self, path: &Path) {
if let Err(error) = util::save_json(path, self) {
log::error!("could not save settings: {error}");
}
}
/// All search engines: built-in ones, then the user's. (key, name, url template, suggest url)
pub fn search_engines(&self) -> Vec<(String, String, String, String)> {
let mut out: Vec<_> = SEARCH_ENGINES.iter().map(|e| (e.key.to_owned(), e.name.to_owned(), e.url.to_owned(), e.suggest.to_owned())).collect();
for (name, url) in &self.startup.custom_engines {
out.push((format!("custom:{name}"), name.clone(), url.clone(), String::new()));
}
out
}
/// URL template of the chosen search engine.
pub fn search_template(&self) -> String {
let key = &self.startup.search_engine;
self.search_engines().into_iter().find(|(k, ..)| k == key).map(|(_, _, url, _)| url).filter(|u| u.contains("%s")).unwrap_or_else(|| SEARCH_ENGINES[0].url.to_owned())
}
pub fn search_suggest_template(&self) -> Option<String> {
if !self.startup.search_suggestions {
return None;
}
let key = &self.startup.search_engine;
self.search_engines().into_iter().find(|(k, ..)| k == key).map(|(.., suggest)| suggest).filter(|s| !s.is_empty())
}
pub fn search_engine_name(&self) -> String {
let key = &self.startup.search_engine;
self.search_engines().into_iter().find(|(k, ..)| k == key).map(|(_, name, ..)| name).unwrap_or_else(|| SEARCH_ENGINES[0].name.to_owned())
}
/// Zoom factor for a host: its own, or the default.
pub fn zoom_for(&self, host: &str) -> f32 {
self.web.zoom_sites.get(host).copied().unwrap_or(self.web.zoom).clamp(0.25, 5.0)
}
pub fn set_zoom_for(&mut self, host: &str, zoom: f32) {
if host.is_empty() {
return;
}
if (zoom - self.web.zoom).abs() < 0.005 {
self.web.zoom_sites.remove(host);
} else {
self.web.zoom_sites.insert(host.to_owned(), zoom);
}
}
pub fn adblock_paused_on(&self, host: &str) -> bool {
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))
}
pub fn site_muted(&self, host: &str) -> bool {
self.media.muted_sites.iter().any(|h| util::host_matches(host, h))
}
pub fn toolbar_has(&self, key: &str) -> bool {
self.ui.toolbar.iter().any(|k| k == key)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_file_gives_defaults() {
let s: Settings = serde_json::from_str("{}").unwrap();
assert_eq!(s, Settings::default());
assert!(s.adblock.enabled);
assert_eq!(s.search_template(), "https://duckduckgo.com/?q=%s");
}
#[test]
fn partial_file_keeps_other_defaults() {
let s: Settings = serde_json::from_str(r#"{"privacy":{"https_only":true},"unknown":1}"#).unwrap();
assert!(s.privacy.https_only);
assert!(s.privacy.dnt);
}
#[test]
fn round_trip() {
let mut s = Settings::default();
s.vpn.enabled = true;
s.privacy.doh = DohProvider::Quad9;
let text = serde_json::to_string(&s).unwrap();
let back: Settings = serde_json::from_str(&text).unwrap();
assert_eq!(s, back);
assert!(text.contains("\"quad9\""));
}
}