S051: WIP clear data with time range, site info shows cookies and stored data

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-14 08:00:49 -06:00
commit 84407da261
9 changed files with 149 additions and 12 deletions

View file

@ -14,8 +14,8 @@ one MPRIS player.
## Steps
- [x] `paths.rs`: `APP_DIR = "nacre-browser"`; migration (rename config/data/cache once if new missing and old present; delete Servo-only engine files after; log it); unit test with temp dirs; `~/.config/nacre` never touched.
- [ ] Cookies: persistent storage path in `$XDG_RUNTIME_DIR/nacre-<profile>/cookies.sqlite`; at start decrypt `cookies.bin` → `add_cookie` (or write the SQLite) ; seal at quit and 60 s after `changed`; no keyring → run-only; convert Servo-era `cookies.bin` when it parses, else move aside.
- [ ] Clear data / clear on exit / site info flyout on `WebsiteDataManager` (types + since-time) and `CookieManager::get_cookies`; drop the "Servo keeps no dates" text.
- [x] Cookies: persistent storage path in `$XDG_RUNTIME_DIR/nacre-<profile>/cookies.sqlite`; at start decrypt `cookies.bin` → `add_cookie` (or write the SQLite) ; seal at quit and 60 s after `changed`; no keyring → run-only; convert Servo-era `cookies.bin` when it parses, else move aside.
- [x] Clear data / clear on exit / site info flyout on `WebsiteDataManager` (types + since-time) and `CookieManager::get_cookies`; drop the "Servo keeps no dates" text.
- [ ] Incognito: ephemeral session, nothing written; check the throwaway home after a run.
- [ ] Media: probe events + `is-playing-audio` → media state; mute via `set_is_muted`; check whether WebKitGTK publishes its own MPRIS player (`busctl --user list | grep mpris` in the nested bus) and apply D-039 (one player).
- [ ] Smoke: `cookies.txt` → `cookies-restart.txt` → `cookies-cleared.txt` with `SMOKE_KEYRING=1`, `cookies-nokeyring.txt`, `restore.txt`, `privacy-incognito.txt` green hidden; `grep -c` of a test cookie value in the home dir = 0.
@ -32,4 +32,4 @@ one MPRIS player.
Migration behaviour, seal timing, MPRIS outcome (which player).
## Resume note (WIP)
- Box 2 code done (store/cookies.rs: tmpfs `nacre-<profile>-<hash>/cookies.sqlite` written with rusqlite from cookies.bin, sealed by reading the DB; engine `Setup::cookie_db`, `Event::CookiesChanged`, App `cookies` tick/finish); unit tests green. Next: release build, cookies smokes to verify box 2, then box 3.
- Boxes 1–3 done (site-data.txt smoke new, green). Next: box 4 incognito check, box 5 media.

View file

@ -150,6 +150,8 @@ pub enum Command {
OpenUpdate,
ClearData { since: u64, what: Vec<String> },
ClearSiteData(String),
/// Ask the engine what a host keeps, for the site info flyout.
SiteData(String),
SwitchProfile(String),
NewWindow,
NewIncognito,
@ -702,11 +704,18 @@ impl App {
Command::ClearData { since, what } => self.clear_data(since, &what),
Command::ClearSiteData(host) => {
if let Some(engine) = &self.engine {
engine.clear_data(true, false, Some(vec![host.clone()]));
engine.clear_data(true, false, 0, Some(vec![host.clone()]));
}
self.shared.permissions.borrow_mut().clear_host(&host);
self.shared.site_data.borrow_mut().0.clear();
self.shared.toast(format!("Data for {host} deleted"));
},
Command::SiteData(host) => {
let url = self.active_url(window);
if let Some(engine) = &self.engine {
engine.site_data(host, &url);
}
},
Command::SwitchProfile(name) => {
if let Ok(exe) = std::env::current_exe() {
let _ = std::process::Command::new(exe).args(["--profile", &name]).spawn();
@ -745,7 +754,7 @@ impl App {
}
}
if let Some(engine) = &self.engine {
engine.clear_data(false, true, None);
engine.clear_data(false, true, 0, None);
}
self.shared.toast(format!("{freed} background tabs unloaded; they load again when you open them"));
},
@ -2226,7 +2235,7 @@ impl App {
self.shared.downloads.borrow_mut().clear_inactive();
}
if let Some(engine) = &self.engine {
engine.clear_data(has("cookies"), has("cache"), None);
engine.clear_data(has("cookies"), has("cache"), since, None);
}
if has("permissions") {
self.shared.permissions.borrow_mut().clear_all();

View file

@ -172,6 +172,8 @@ pub struct Shared {
pub presence_status: RefCell<String>,
/// Page sources for nacre://source: url -> text or error (None while loading).
pub sources: RefCell<HashMap<String, Option<Result<String, String>>>>,
/// Site info flyout: the host asked about and what it keeps (None while the engine answers).
pub site_data: RefCell<(String, Option<crate::engine::SiteData>)>,
}
#[derive(Clone, Debug)]
@ -329,6 +331,7 @@ impl App {
cava: RefCell::new(Cava::new()),
art_images: RefCell::new(HashMap::new()),
sources: RefCell::new(HashMap::new()),
site_data: RefCell::default(),
presence_status: RefCell::new("Off".into()),
incognito,
paths,
@ -812,7 +815,16 @@ impl App {
Event::Notification(id, notification) => self.on_notification(id, notification),
Event::Page(id, message) => self.on_page_message(id, message),
Event::Find(id, count) => self.on_find(id, count),
Event::SiteData(host, data) => {
let mut current = self.shared.site_data.borrow_mut();
if current.0 == host {
current.1 = Some(data);
drop(current);
self.redraw_all();
}
},
Event::CookiesChanged => {
self.shared.site_data.borrow_mut().0.clear();
if let Some(cookies) = &mut self.cookies {
cookies.changed(Instant::now());
}
@ -1697,7 +1709,7 @@ impl App {
self.shared.downloads.borrow_mut().clear_inactive();
}
if let Some(engine) = &self.engine {
engine.clear_data(what.iter().any(|w| w == "cookies"), what.iter().any(|w| w == "cache"), None);
engine.clear_data(what.iter().any(|w| w == "cookies"), what.iter().any(|w| w == "cache"), 0, None);
}
}

View file

@ -462,8 +462,10 @@ impl Engine {
self.views.borrow().values().filter_map(|w| w.upgrade()).collect()
}
/// Delete every cookie and stored site data (`what`: cookies and/or cache).
pub fn clear_data(&self, cookies: bool, cache: bool, hosts: Option<Vec<String>>) {
/// Delete cookies and stored site data and/or the cache: changed since `since` (Unix seconds, 0 = all; cookies always
/// all), or every
/// item of `hosts` (and their subdomains) whatever its age.
pub fn clear_data(&self, cookies: bool, cache: bool, since: u64, hosts: Option<Vec<String>>) {
let Some(manager) = self.session.website_data_manager() else { return };
let mut types = webkit::WebsiteDataTypes::empty();
if cookies {
@ -476,7 +478,16 @@ impl Engine {
return;
}
match hosts {
None => manager.clear(types, glib::TimeSpan::from_seconds(0), None::<&gtk::gio::Cancellable>, |_| {}),
None => {
// WebKit takes "modified in the last <span>"; 0 clears everything. Its libsoup cookie store keeps no
// dates and ignores a span, so cookies go whatever the range (the Clear data page says so).
let span = if since == 0 { 0 } else { crate::util::now().saturating_sub(since).max(1) as i64 };
if span != 0 && types.contains(webkit::WebsiteDataTypes::COOKIES) {
manager.clear(webkit::WebsiteDataTypes::COOKIES, glib::TimeSpan::from_seconds(0), None::<&gtk::gio::Cancellable>, |_| {});
types.remove(webkit::WebsiteDataTypes::COOKIES);
}
manager.clear(types, glib::TimeSpan::from_seconds(span), None::<&gtk::gio::Cancellable>, |_| {});
},
Some(hosts) => {
let m = manager.clone();
manager.fetch(types, None::<&gtk::gio::Cancellable>, move |result| {
@ -491,6 +502,33 @@ impl Engine {
}
}
/// What `host` keeps (site info): the cookies sent to `url` and the kinds of stored data under the host's name.
/// Answers with `Event::SiteData`.
pub fn site_data(&self, host: String, url: &str) {
let (Some(manager), Some(cookies)) = (self.session.website_data_manager(), self.session.cookie_manager()) else { return };
let hub = self.hub.clone();
cookies.cookies(url, None::<&gtk::gio::Cancellable>, move |result| {
let count = result.map(|c| c.len()).unwrap_or(0);
let stored = webkit::WebsiteDataTypes::ALL & !(webkit::WebsiteDataTypes::MEMORY_CACHE | webkit::WebsiteDataTypes::DISK_CACHE | webkit::WebsiteDataTypes::COOKIES);
manager.fetch(stored, None::<&gtk::gio::Cancellable>, move |result| {
let mut kinds = webkit::WebsiteDataTypes::empty();
for d in result.unwrap_or_default() {
if d.name().is_some_and(|n| crate::util::host_matches(&host, &n)) {
kinds |= d.types();
}
}
let labels = [
(webkit::WebsiteDataTypes::LOCAL_STORAGE, "local storage"),
(webkit::WebsiteDataTypes::INDEXEDDB_DATABASES, "databases"),
(webkit::WebsiteDataTypes::SERVICE_WORKER_REGISTRATIONS, "service workers"),
(webkit::WebsiteDataTypes::DOM_CACHE, "offline files"),
];
let stored = labels.iter().filter(|(t, _)| kinds.contains(*t)).map(|(_, l)| *l).collect();
hub.push(Event::SiteData(host, super::SiteData { cookies: count, stored }));
});
});
}
/// A new web view for a tab (`related`: a pop-up sharing its opener's web process).
pub fn create_view(self: &Rc<Self>, id: ViewId, related: Option<&View>) -> View {
// The message handler is registered before the view exists, so the first document can already post.

View file

@ -89,6 +89,17 @@ pub enum Event {
Find(ViewId, u32),
/// A cookie was added, changed or deleted.
CookiesChanged,
/// What a host keeps (`Engine::site_data`).
SiteData(String, SiteData),
}
/// Cookies and stored data of one site, for the site info flyout.
#[derive(Clone, Debug, Default)]
pub struct SiteData {
/// Cookies the page's address gets.
pub cookies: usize,
/// Kinds of stored data under the host's name ("local storage", …).
pub stored: Vec<&'static str>,
}
/// A user style sheet (`store::scripts`), added at author level so it acts like the page's own last `<style>`.

View file

@ -26,7 +26,8 @@
//! find <text>, download <url>, pause_download|resume_download|cancel_download [id] (newest),
//! import <n> (bookmarks, history, settings from the n-th found browser profile),
//! install_script <url> (a .user.js / .user.css), open_app [id] (default: the first installed app),
//! navigate <typed text>, mute, pin
//! navigate <typed text>, mute, pin, clear_data <seconds back, 0 = all> <what,…> (keys of
//! the Clear browsing data page: history, cookies, cache, …)
//! 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
@ -477,6 +478,11 @@ impl App {
"install_script" => Command::InstallScript(arg.to_owned()),
"open_app" => Command::OpenApp(if arg.is_empty() { self.shared.apps.borrow().items.first().map(|a| a.id.clone()).unwrap_or_default() } else { arg.to_owned() }),
"media" => Command::Media { tab, action: arg.to_owned(), value: 0.0 },
"clear_data" => {
let (seconds, what) = arg.split_once(' ').unwrap_or((arg, ""));
let seconds: u64 = seconds.parse().unwrap_or(0);
Command::ClearData { since: if seconds == 0 { 0 } else { crate::util::now().saturating_sub(seconds) }, what: what.split(',').map(str::to_owned).collect() }
},
_ => {
self.selftest_log(&format!("unknown cmd {name}"));
return;
@ -905,6 +911,7 @@ impl App {
"notifications": self.notifications_shown,
"tab_count": tabs.len(),
"cookies": crate::store::cookies::keeping().map(|k| format!("{k:?}")),
"site_data": self.shared.site_data.borrow().1.as_ref().map(|d| serde_json::json!({"cookies": d.cookies, "stored": d.stored})),
"active_index": self.windows.get(&window).map(|w| w.active),
"fullscreen": self.windows.get(&window).map(|w| w.fullscreen),
"ui_typing": self.windows.get(&window).map(|w| w.ctx().egui_wants_keyboard_input()),

View file

@ -1130,6 +1130,20 @@ fn site_info(ui: &mut Ui, f: &mut Frame) {
icon(ui, rect.center(), glyph, 18.0, false, color);
ui.add(egui::Label::new(RichText::new(line).font(theme::font(theme::BODY, Weight::Regular)).color(if secure || file { p.on_surface } else { p.error })).wrap());
});
if !file {
ui.add_space(theme::GAP_S);
group(ui, "Cookies and site data", |_| {});
let asked = f.shared.site_data.borrow().0 == host;
if !asked {
*f.shared.site_data.borrow_mut() = (host.clone(), None);
f.send(Command::SiteData(host.clone()));
}
let line = match &f.shared.site_data.borrow().1 {
None => "Checking…".to_owned(),
Some(data) => site_data_line(data),
};
text(ui, &line, true);
}
ui.add_space(theme::GAP_S);
group(ui, "Permissions", |_| {});
let decisions = f.shared.permissions.borrow().for_host(&host);
@ -1162,6 +1176,18 @@ fn site_info(ui: &mut Ui, f: &mut Frame) {
}
}
/// "2 cookies, local storage" / "Nothing stored".
fn site_data_line(data: &crate::engine::SiteData) -> String {
let mut parts: Vec<String> = Vec::new();
match data.cookies {
0 => {},
1 => parts.push("1 cookie".into()),
n => parts.push(format!("{n} cookies")),
}
parts.extend(data.stored.iter().map(|s| (*s).to_owned()));
if parts.is_empty() { "Nothing stored".to_owned() } else { parts.join(", ") }
}
fn profiles(ui: &mut Ui, f: &mut Frame) {
ui.set_width(280.0);
let list = f.shared.paths.profile_list();

View file

@ -184,7 +184,7 @@ pub fn clear_data(ui: &mut Ui, f: &mut Frame) {
ui.add_space(theme::GAP_L);
ui.vertical(|ui| {
ui.set_max_width(ui.available_width() - theme::GAP_L);
ui.label(RichText::new("Cookies, cache, permissions and passwords are removed whatever the time range, because the engine keeps no dates for them.").font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
ui.label(RichText::new("Cookies, the downloads list, permissions, passwords and addresses are removed whatever the time range: the engine keeps no dates for them.").font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
});
});
ui.add_space(theme::GAP_L);

34
tests/smoke/site-data.txt Normal file
View file

@ -0,0 +1,34 @@
# Site data on WebKit (S051): the site info flyout counts a site's cookies and stored data; Clear browsing data with a
# time range keeps older stored data (WebsiteDataManager since-time) but deletes every cookie (WebKit's libsoup store keeps
# no cookie dates). Offline, never Tor or proxies.
# python3 tests/smoke/net/server.py &
# tools/smoke.sh tests/smoke/site-data.txt <out>
wait 3
set /vpn/enabled false
set /privacy/https_only false
wait 1
open http://127.0.0.1:8767/login?user=smoke
waitfor 20 document.title === "Signed in smoke"
js localStorage.setItem("nacre", "kept"); document.cookie = "early=1; max-age=3600; path=/"
wait 2
flyout siteinfo
waitstatus 20 /site_data/cookies 2
wait 1
shot siteinfo
flyout none
# Older than the range below.
wait 30
js document.cookie = "late=1; max-age=3600; path=/"
wait 2
cmd clear_data 15 cookies
wait 3
open http://127.0.0.1:8767/whoami
waitfor 20 document.title === "Signed out"
assert document.cookie === "" && localStorage.getItem("nacre") === "kept"
cmd clear_data 0 cookies
wait 3
open http://127.0.0.1:8767/whoami
waitfor 20 document.title === "Signed out"
assert document.cookie === "" && localStorage.getItem("nacre") === null
status done
quit