S008: R1-20 per-site memory and permissions enforced (images, sound), restart smoke

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 11:18:39 -06:00
commit 6a092f950d
11 changed files with 223 additions and 13 deletions

View file

@ -17,6 +17,7 @@ Verify passwords/vault and autofill, permissions prompts, history/bookmarks/down
- [ ] History, bookmarks (add, folder, bookmarks bar, import/export HTML), downloads page lists entries
- [ ] User scripts/styles apply on matching pages; install a site as an app and launch it
- [ ] Importer: build a fake old-Nacre profile from `~/Documents/Apps/Nacre` config format in a temp dir (never the user's real profile) and import it
- [x] R1-20 per-site memory and enforcement: set per-site zoom, ad blocker on/off, privacy-mode flag (flag persistence only; internals are D-011) and other per-site choices; set per-site permissions (camera, mic, location, notifications, pop-ups, autoplay, …); quit, relaunch with `SMOKE_HOME=<first outdir>/home`, check values are in the stores and apply again on reopening the site; check each permission is enforced (blocked/allowed/asked per its stored value), not only stored; fix what is not
- [ ] Change a sample of settings via `set` and via clicks; check `settings.json` and the effect; mark FEATURES rows
- [ ] PROGRESS entry, INDEX line, commit `S008: …` and push

View file

@ -2422,6 +2422,12 @@ impl App {
/// The UI edits settings in place; this notices and applies what changed.
pub fn apply_settings_if_changed(&mut self) {
let revision = self.shared.permissions.borrow().revision();
if revision != self.permissions_seen {
self.permissions_seen = revision;
self.shared.permissions.borrow_mut().flush();
self.refresh_hub_config();
}
let current = self.shared.settings.borrow().clone();
if current == self.applied {
return;

View file

@ -182,6 +182,8 @@ pub struct App {
pub gilrs: Option<gilrs::Gilrs>,
pub gamepads: HashMap<gilrs::GamepadId, usize>,
pub applied: Settings,
/// `Permissions::revision` the hub and the file were last updated for.
pub permissions_seen: u64,
pub exiting: bool,
last_tick: Instant,
last_save: Instant,
@ -307,6 +309,7 @@ impl App {
gilrs: None,
gamepads: HashMap::new(),
applied: settings,
permissions_seen: 0,
exiting: false,
last_tick: Instant::now(),
last_save: Instant::now(),
@ -392,7 +395,7 @@ 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.user_agent.borrow(), self.shared.http_allowed.borrow().clone());
*self.hub.config.borrow_mut() = HubConfig::from_settings(&settings, &self.shared.permissions.borrow(), &self.shared.user_agent.borrow(), self.shared.http_allowed.borrow().clone());
}
/// (Re)build the scripts every page gets. Applies on each page's next load.
@ -540,13 +543,16 @@ impl App {
}
}
self.check_app_scope(window, id, &url);
if host_changed {
let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url));
if let Some(tab) = self.tab_mut(id) {
tab.zoom = zoom;
if let Some(web) = &tab.web {
web.webview.set_page_zoom(zoom);
}
// A zoom change is saved for the site at once, so the site's value is always the right one. Not only
// when the host changed: a new tab already holds its address when the first event arrives.
let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url));
if let Some(tab) = self.tab_mut(id) {
let differs = (tab.zoom - zoom).abs() > 0.001;
tab.zoom = zoom;
if (host_changed || differs)
&& let Some(web) = &tab.web
{
web.webview.set_page_zoom(zoom);
}
}
self.redraw(window);
@ -810,7 +816,7 @@ impl App {
}
// Mute state survives navigation.
let shared = self.shared.clone();
let muted = self.tab_mut(id).map(|t| t.muted || shared.settings.borrow().site_muted(&util::host_of_str(&t.url))).unwrap_or(false);
let muted = self.tab_mut(id).map(|t| t.muted || shared.settings.borrow().site_muted(&util::host_of_str(&t.url)) || shared.permissions.borrow().answer(&shared.settings.borrow(), &util::host_of_str(&t.url), crate::store::permissions::Kind::Sound) == crate::store::permissions::Answer::Block).unwrap_or(false);
if muted && let Some(tab) = self.tab_mut(id) {
tab.muted = true;
if let Some(web) = &tab.web {

View file

@ -15,6 +15,7 @@ use url::Url;
use crate::adblock::{AdBlocker, Verdict};
use crate::inject::{self, PageMessage};
use crate::store::permissions::{Answer, Decision, Kind, Permissions};
use crate::store::settings::Settings;
use crate::util;
@ -73,13 +74,21 @@ pub struct HubConfig {
pub https_exceptions: Vec<String>,
pub strip_params: bool,
pub google_signin: bool,
/// Images permission: blocked unless a site says otherwise, and the sites that differ (host, blocked).
pub images_block_default: bool,
pub images_sites: Vec<(String, bool)>,
pub user_agent: String,
/// Tabs where the user chose "open over http anyway" this session (host).
pub http_allowed: Vec<String>,
}
impl HubConfig {
pub fn from_settings(settings: &Settings, user_agent: &str, http_allowed: Vec<String>) -> HubConfig {
/// Whether pictures are blocked on pages of this host.
pub fn images_blocked(&self, host: &str) -> bool {
self.images_sites.iter().find(|(h, _)| h == host).map(|(_, block)| *block).unwrap_or(self.images_block_default)
}
pub fn from_settings(settings: &Settings, permissions: &Permissions, user_agent: &str, http_allowed: Vec<String>) -> HubConfig {
HubConfig {
adblock_enabled: settings.adblock.enabled,
adblock_allow: settings.adblock.allow.clone(),
@ -87,6 +96,8 @@ impl HubConfig {
https_exceptions: settings.privacy.https_exceptions.clone(),
strip_params: settings.privacy.strip_params,
google_signin: settings.privacy.google_signin,
images_block_default: permissions.answer(settings, "", Kind::Images) == Answer::Block,
images_sites: permissions.all().into_iter().filter(|(_, kind, _)| *kind == Kind::Images).map(|(host, _, decision)| (host, decision == Decision::Block)).collect(),
user_agent: user_agent.to_owned(),
http_allowed,
}
@ -245,9 +256,14 @@ impl Hub {
return;
}
// Sub-resources: the ad blocker.
// Sub-resources: the Images permission, then the ad blocker.
let page_url = page.as_ref().map(Url::as_str).unwrap_or("");
let page_host = util::host_of_str(page_url);
if kind == "image" && matches!(url.scheme(), "http" | "https") && !page_host.is_empty() && config.images_blocked(&page_host) {
drop(config);
load.intercept(WebResourceResponse::new(url).status_code(StatusCode::NO_CONTENT)).cancel();
return;
}
let paused = !config.adblock_enabled || config.adblock_allow.iter().any(|h| util::host_matches(&page_host, h));
drop(config);
if !paused && matches!(url.scheme(), "http" | "https" | "ws" | "wss") {
@ -403,6 +419,20 @@ impl servo::GamepadDelegate for Gamepads {
mod tests {
use super::*;
#[test]
fn images_follow_the_site_answer_then_the_default() {
let mut settings = Settings::default();
let mut permissions = Permissions::load(std::path::PathBuf::from("/nonexistent/permissions.json"), true);
assert!(!HubConfig::from_settings(&settings, &permissions, "", Vec::new()).images_blocked("a.example"));
permissions.set("a.example", Kind::Images, Some(Decision::Block));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && !config.images_blocked("b.example"));
settings.privacy.permission_defaults.insert("images".into(), crate::store::settings::PermissionDefault::Block);
permissions.set("b.example", Kind::Images, Some(Decision::Allow));
let config = HubConfig::from_settings(&settings, &permissions, "", Vec::new());
assert!(config.images_blocked("a.example") && config.images_blocked("c.example") && !config.images_blocked("b.example"));
}
#[test]
fn strips_tracking() {
let u = Url::parse("https://a.example/p?id=3&utm_source=x&fbclid=y").unwrap();

View file

@ -10,6 +10,8 @@
//! resize <w> <h> resize the window (logical pixels)
//! status <name> save tabs, downloads, VPN, ad blocker and so on as <name>.json
//! set <json pointer> <json> change a setting, e.g. `set /privacy/https_only true`
//! perm <host> <kind> allow|block|default store a site's answer for a permission (kinds: store::permissions::Kind keys)
//! prompt allow|deny [remember] answer the active tab's first permission prompt
//! flyout <name> main, downloads, shield, vpn, media, siteinfo, profiles, apps, qr, tabmenu, back,
//! bookmark (edit the current page's bookmark), none
//! type <text> put text in the address bar with its suggestions open
@ -271,6 +273,27 @@ impl App {
}
self.apply_settings_if_changed();
},
"perm" => {
let parts: Vec<&str> = rest.split_whitespace().collect();
let kind = parts.get(1).and_then(|k| crate::store::permissions::Kind::ALL.iter().find(|x| x.key() == *k));
let decision = match parts.get(2).copied() {
Some("allow") => Some(Some(crate::store::permissions::Decision::Allow)),
Some("block") => Some(Some(crate::store::permissions::Decision::Block)),
Some("default") => Some(None),
_ => None,
};
match (parts.first(), kind, decision) {
(Some(host), Some(kind), Some(decision)) => self.shared.permissions.borrow_mut().set(host, *kind, decision),
_ => self.selftest_log(&format!("perm: bad line {rest}")),
}
self.refresh_hub_config();
},
"prompt" => {
let remember = rest.contains("remember");
let answer = if rest.starts_with("allow") { crate::actions::PromptAnswer::Allow { remember } } else { crate::actions::PromptAnswer::Deny { remember } };
let tab = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.id).unwrap_or(0);
self.run_in(window, Command::Prompt { tab, answer });
},
"flyout" => {
let url = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.url.clone()).unwrap_or_default();
let tab = self.windows.get(&window).and_then(|w| w.tab()).map(|t| t.id).unwrap_or(0);
@ -676,6 +699,11 @@ impl App {
"route": self.shared.bridge.as_ref().map(|b| format!("{:?}", b.route())),
"bridge_bytes": self.shared.bridge.as_ref().map(|b| b.bytes.load(std::sync::atomic::Ordering::Relaxed)),
"adblock": {"ready": self.shared.adblock.ready(), "rules": self.shared.adblock.rule_count(), "status": self.shared.adblock_status.borrow().clone(), "total": settings.adblock.total},
"permissions": self.shared.permissions.borrow().all().iter().fold(serde_json::Map::new(), |mut m, (host, kind, decision)| {
m.entry(host.clone()).or_insert_with(|| serde_json::json!({})).as_object_mut().expect("object").insert(kind.key().to_owned(), serde_json::json!(format!("{decision:?}").to_lowercase()));
m
}),
"site_state": {"zoom_sites": settings.web.zoom_sites, "adblock_allow": settings.adblock.allow, "keep_active": settings.perf.keep_active, "muted_sites": settings.media.muted_sites, "https_exceptions": settings.privacy.https_exceptions},
"history": self.shared.history.borrow().len(),
"bookmarks": self.shared.bookmarks.borrow().all().len(),
"logins": self.shared.vault.borrow().contents.logins.len(),

View file

@ -120,6 +120,18 @@ impl Kind {
}
}
/// Why Nacre can't enforce this one: Servo 0.7 has no per-site switch for it. Those rows show as unavailable.
pub fn engine_limit(self) -> Option<&'static str> {
match self {
Kind::Location => Some("Servo 0.7 never asks for the location: navigator.geolocation does nothing"),
Kind::Camera | Kind::Microphone | Kind::DeviceInfo => Some("Servo 0.7 has no navigator.mediaDevices, so no page can ask"),
Kind::Storage => Some("Servo 0.7 has no navigator.storage.persist(), so no page can ask"),
Kind::Javascript => Some("Servo 0.7 can't turn JavaScript off for one site"),
Kind::Clipboard => Some("Servo 0.7 doesn't ask before a page reads the clipboard"),
_ => None,
}
}
/// The answer when the user has set nothing: sensitive things ask, harmless ones are allowed.
pub fn builtin_default(self) -> PermissionDefault {
match self {
@ -150,12 +162,14 @@ pub struct Permissions {
sites: BTreeMap<String, BTreeMap<Kind, Decision>>,
dirty: bool,
read_only: bool,
/// Counts every change, so the app notices edits made by menus and pages.
revision: u64,
}
impl Permissions {
pub fn load(path: PathBuf, read_only: bool) -> Permissions {
let sites = if read_only { BTreeMap::new() } else { util::load_json(&path) };
Permissions { path, sites, dirty: false, read_only }
Permissions { path, sites, dirty: false, read_only, revision: 0 }
}
/// The decision stored for exactly this site, if any.
@ -198,6 +212,11 @@ impl Permissions {
},
}
self.dirty = true;
self.revision += 1;
}
pub fn revision(&self) -> u64 {
self.revision
}
/// Every stored decision: (host, kind, decision).
@ -212,6 +231,7 @@ impl Permissions {
pub fn clear_host(&mut self, host: &str) {
if self.sites.remove(host).is_some() {
self.dirty = true;
self.revision += 1;
}
}
@ -219,6 +239,7 @@ impl Permissions {
if !self.sites.is_empty() {
self.sites.clear();
self.dirty = true;
self.revision += 1;
}
}
@ -248,5 +269,6 @@ mod tests {
assert_eq!(p.answer(&s, "a.example", Kind::Camera), Answer::Allow);
p.set("a.example", Kind::Camera, None);
assert!(p.all().is_empty());
assert_eq!(p.revision(), 2);
}
}

View file

@ -3,7 +3,7 @@
use egui::{RichText, Sense, Stroke, Ui, vec2};
use super::super::widgets::{ButtonKind, button, card, empty_state, icon, icon_button, icon_row, icon_link_row, list_item, page_column, page_header, row, search_pill, section, segmented, status_state, switch, switch_row};
use super::super::widgets::{ButtonKind, button, card, empty_state, icon, icon_button, icon_row, icon_link_row, list_item, page_column, page_header, row, search_pill, section, segmented, status_state, switch, switch_row, unavailable_row};
use super::super::{Frame, paint};
use crate::actions::Command;
use crate::store::permissions::{Decision, Kind};
@ -73,6 +73,10 @@ pub fn site_settings(ui: &mut Ui, f: &mut Frame, host: &str) {
section(ui, "Permissions");
card(ui, |ui| {
for kind in Kind::ALL {
if let Some(reason) = kind.engine_limit() {
unavailable_row(ui, kind.label(), reason);
continue;
}
let current = f.shared.permissions.borrow().site_decision(host, *kind);
let mut value: u8 = match current {
None => 0,

View file

@ -1293,6 +1293,10 @@ fn permissions(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
section(ui, "Defaults");
card(ui, |ui| {
for kind in crate::store::permissions::Kind::ALL {
if let Some(reason) = kind.engine_limit() {
unavailable_row(ui, kind.label(), reason);
continue;
}
let mut value = s.privacy.permission_defaults.get(kind.key()).copied().unwrap_or_else(|| kind.builtin_default());
let before = value;
row(ui, kind.label(), "", |ui| segmented(ui, &mut value, PermissionDefault::ALL));

View file

@ -0,0 +1,11 @@
<!doctype html>
<meta charset="utf-8">
<title>Site permissions probe</title>
<img id="pic" width="32" height="32" src="backdrop.gif" onload="res.img = 'loaded'" onerror="res.img = 'blocked'">
<script>
// Test page for tests/smoke/site-memory*.txt (served by `python3 -m http.server 8768` over tests/smoke/pages).
// Each probe puts its answer in `res`; the script waits for it with `waitfor`.
window.res = {};
function notif() { delete res.notif; Notification.requestPermission().then(r => { res.notif = r; }); }
function pop() { delete res.pop; const w = window.open('hello.html'); res.pop = w ? 'opened' : 'null'; }
</script>

View file

@ -0,0 +1,36 @@
# Per-site memory and permissions (S008, R1-20), part 2: run on part 1's home (SMOKE_HOME=<outdir>/home).
# Everything set in part 1 is still stored, and applies again when the site is opened.
wait 3
status stored
expect /permissions/127.0.0.1/notifications block
expect /permissions/127.0.0.1/popups block
expect /permissions/127.0.0.1/images block
expect /permissions/127.0.0.1/sound block
expect /site_state/adblock_allow/0 "127.0.0.1"
expect /site_state/keep_active/0 "127.0.0.1"
expect /site_state/muted_sites/0 "127.0.0.1"
expect /site_state/https_exceptions/0 "127.0.0.1"
expect /site_state/zoom_sites/127.0.0.1 > 1
# Open the site fresh: zoom, mute, images and permissions apply again; a blocked pop-up stays blocked.
newtab http://127.0.0.1:8768/site.html
waitfor 20 window.res && window.res.img !== undefined
assert res.img === 'blocked'
wait 2
status opened
expect /active/zoom > 1
expect /active/muted true
js notif()
waitfor 10 res.notif === 'denied'
js pop()
wait 2
status checked
expect /tab_count 2
# Reset the images answer: the picture loads again, and the change is stored.
perm 127.0.0.1 images default
cmd reload
waitload
waitfor 20 window.res && window.res.img !== undefined
assert res.img === 'loaded'
shot images-back
status done
quit

View file

@ -0,0 +1,62 @@
# Per-site memory and permissions (S008, R1-20), part 1: set values, then quit.
# Part 2 (site-memory-restart.txt) runs on the same home and checks they came back and still apply. Offline.
# python3 -m http.server 8768 --bind 127.0.0.1 --directory tests/smoke/pages &
# tools/smoke.sh tests/smoke/site-memory.txt (hidden)
# SMOKE_HOME=<that outdir>/home tools/smoke.sh tests/smoke/site-memory-restart.txt
wait 3
open http://127.0.0.1:8768/site.html
waitfor 20 window.res && window.res.img !== undefined
assert res.img === 'loaded'
# Notifications: asks first; deny + remember; the next ask is refused without a prompt.
js notif()
wait 3
status ask
expect /active/prompts 1
prompt deny remember
waitfor 10 res.notif === 'denied'
js notif()
waitfor 10 res.notif === 'denied'
status notif
expect /active/prompts 0
expect /permissions/127.0.0.1/notifications block
# Pop-ups: a new tab by default, none once blocked.
js pop()
wait 2
status popup-default
expect /tab_count 2
cmd close_tab
cmd select 0
perm 127.0.0.1 popups block
js pop()
wait 2
status popup
expect /tab_count 1
# Images blocked for the site: the picture doesn't load after a reload.
perm 127.0.0.1 images block
cmd reload
waitload
waitfor 20 window.res && window.res.img !== undefined
assert res.img === 'blocked'
shot images-blocked
# Sound blocked: the tab is muted on load.
perm 127.0.0.1 sound block
cmd reload
waitload
wait 2
status sound
expect /active/muted true
# Other per-site choices: zoom, ad blocker off, keep active, mute, HTTPS exception.
cmd zoom 1
cmd zoom 1
set /adblock/allow ["127.0.0.1"]
set /perf/keep_active ["127.0.0.1"]
set /media/muted_sites ["127.0.0.1"]
set /privacy/https_exceptions ["127.0.0.1"]
wait 1
status set
expect /active/zoom > 1
expect /site_state/adblock_allow/0 "127.0.0.1"
expect /permissions/127.0.0.1/images block
expect /permissions/127.0.0.1/popups block
status done
quit