diff --git a/CHANGELOG.md b/CHANGELOG.md index 920df89e..7ef8e5b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,10 @@ All notable changes to Tarn are documented in this file. The format is based on GitHub or the official catalog with per-site grants (macOS, Windows, Linux, iOS, Android). On macOS they run in WebKit and Chromium tabs alike, cross-site frames included, with a toolbar button, badge and popup; on Windows they are the extensions Tarn can run. +- Extension store: an "Install in Tarn" link on extensions.tarnbrowser.com opens a confirmation + in Settings › Extensions built only from Tarn's verified catalog, and nothing is downloaded + until you press Install there; Settings › Extensions links the store (macOS, Windows, Linux, + iOS, Android). ### Changed diff --git a/PRIVACY.md b/PRIVACY.md index bb41041a..320ef211 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -73,7 +73,7 @@ Settings › Privacy › Connections Tarn makes on macOS and Windows. | Update check | GitHub (Releases of this repository) | Your IP address and Tarn version (on Windows only your IP address: Tarn fetches the signed `windows-update.json` and, when it names a later version, downloads that installer); from the `nightly` release in place of the latest one while Settings › General › Nightly builds is on | Once a day while Settings › General › Check for updates automatically is on (the default; on Windows an hour after a check that failed), and when you choose Tarn › Check for Updates…, on macOS and Windows | | Filter-list update | GitHub (Releases of this repository) | Your IP address. Every list is downloaded whatever you switched on, so the download does not reveal your blocking choices | Once a day, on macOS and Windows; switch off in Settings › Privacy | | Fraudulent-website check | Apple, which relays Google Safe Browsing; done by WebKit itself, on macOS and iOS. On Android, Google directly, done by the system WebView's Safe Browsing | Shortened hashes of the addresses you visit, not the addresses | While "Block dangerous sites" is on (the default); off with that switch. On iOS and Android the web view's default, which Tarn leaves on and no switch turns off. Windows and Linux make no such check | -| Extension catalog and downloads | GitHub (the repository you name, or the official catalog in `Quavon-dev/tarn-extensions`, not offered yet because its signing key is not set) | Your IP address and which repository or extension you install or check | Only when you click Install, Check for Updates or Show Official Extensions in Settings › Extensions; switch off in Settings › Privacy (installing from a file keeps working) | +| Extension catalog and downloads | GitHub (the repository you name, or the official catalog in `Quavon-dev/tarn-extensions`, not offered yet because its signing key is not set) | Your IP address and which repository or extension you install or check | Only when you click Install, Check for Updates or Show Official Extensions in Settings › Extensions; an Install in Tarn link from extensions.tarnbrowser.com makes no request until you click Install on the confirmation it opens there; switch off in Settings › Privacy (installing from a file keeps working) | | Theme catalog and downloads | GitHub (the repository you name, or the official catalog in `Quavon-dev/tarn-themes`, not offered yet because its signing key is not set) | Your IP address and which repository or theme you install or check | Only when you click Install, Check for Updates or Show Official Themes in Settings › Appearance, on every client; on macOS and Windows switch off with the same Settings › Privacy switch as extensions; Linux, iOS and Android have no such switch yet (themes from a file or the clipboard keep working) | | Site icon | The site you are on, or a server it already loaded from (such as its CDN, without cookies), through the tab's web engine with your Shield rules | Same as visiting the site | After a page loads over https; never under Lockdown; cleared with history | | Translation (builds with the `translation` feature) | Nobody: Apple's Translation framework runs on your Mac | Nothing. Only language packs you installed in System Settings › General › Language & Region › Translation Languages are used; Tarn never downloads one | Only when you click Translate on the banner; never under Lockdown | diff --git a/crates/app/src/browser.rs b/crates/app/src/browser.rs index b26010f4..24d56ee6 100644 --- a/crates/app/src/browser.rs +++ b/crates/app/src/browser.rs @@ -1808,6 +1808,7 @@ impl Browser { None => self.notify_offer(key, message, None), } } + Event::StoreInstall(id) => self.store_link(key, id, window, cx), Event::PopupBlocked(url) => { let message = nav_policy::popup_blocked_notice(url.as_ref()); let offer = url.filter(|u| nav_policy::decide(u, Source::Typed) == Decision::Allow).map(Offer::NewTab); diff --git a/crates/app/src/extensions.rs b/crates/app/src/extensions.rs index f8359950..54823472 100644 --- a/crates/app/src/extensions.rs +++ b/crates/app/src/extensions.rs @@ -15,14 +15,14 @@ use ui::controls::{icon_button, tooltip}; use ui::icon::Icon; use ui::theme::Theme; -use crate::browser::Browser; +use crate::browser::{Browser, TabKey}; use crate::ext_package; use crate::ext_sources::{self, Net}; use crate::prefs::Pref; use crate::shared::AppCore; pub use browser_core::extensions::Install; -pub use browser_core::extensions::install::UNREVIEWED; -use browser_core::extensions::install::{self, CATALOG_SEEN_SETTING, Slot}; +use browser_core::extensions::install::{self, CATALOG_SEEN_SETTING, Slot, StoreCatalog, StoreContext}; +pub use browser_core::extensions::install::{StoreToken, UNREVIEWED}; use browser_core::extensions::{Step, Unpacked, badge, every_site, fetch_and_unpack, grew, may_use_all_sites, png_icon}; pub use browser_core::theme_fetch::DOWNLOADS_SETTING; @@ -147,6 +147,8 @@ pub struct Extensions { repin: HashSet, /// Check for Updates runs once the catalog it asked for arrives. check_after_catalog: bool, + store_sheet: install::StoreSheet, + store_confirmed: Option<(u64, String)>, catalog: Option, } @@ -810,7 +812,12 @@ impl Browser { let row = u.row(slot.profile_id, &slot.install_id, extension.name(), extension.version(), permissions); let mut ext = self.core.extensions.borrow_mut(); ext.busy = None; + let confirmed = ext.store_confirmed.take().is_some_and(|(g, id)| g == generation && install::store_confirmed(&id, &row.source)); ext.pending = Some(Pending { slot, row, extension }); + drop(ext); + if confirmed { + self.confirm_extension_install(cx); + } cx.notify(); } @@ -1008,6 +1015,72 @@ impl Browser { } } + pub(crate) fn store_link(&mut self, key: TabKey, id: String, window: &mut Window, cx: &mut Context) { + if !self.core.admit_store_link(std::time::Instant::now()) { + return; + } + let (mut sheet, busy) = { + let ext = self.core.extensions.borrow(); + (ext.store_sheet.clone(), ext.busy.is_some() || ext.pending.is_some() || ext.choice.is_some()) + }; + match self.store_check(key, busy, |context, catalog| sheet.offer(key, &id, context, catalog, std::time::Instant::now())) { + Ok(()) => { + self.core.extensions.borrow_mut().store_sheet = sheet; + self.open_settings_pane(crate::settings::SettingsPane::Extensions, window, cx); + } + Err(why) => self.notify_offer(key, why, None), + } + cx.notify(); + } + + fn store_check(&self, key: TabKey, busy: bool, step: impl FnOnce(StoreContext, StoreCatalog) -> R) -> R { + let page = self.views.get(&key).and_then(|v| v.url()); + let profile = self.model.profile_of(&self.core, key).filter(|p| self.current_profile_id() == Some(*p)); + let allowed = self.extensions_allowed() && profile.is_some_and(|p| self.core.store_link_allowed(key.private, p, page.as_ref())); + let rows = profile.map(|p| self.core.disk.extensions(p).unwrap_or_default()).unwrap_or_default(); + let (catalog, revoked) = (self.core.extensions.borrow().catalog.clone(), install::revoked(&self.core.disk)); + let context = StoreContext { allowed, configured: catalog_configured(), downloads: self.extension_downloads(), busy }; + step(context, StoreCatalog { index: catalog.as_ref(), now: now(), revoked: &revoked, installed: &rows }) + } + + pub fn store_sheet(&self) -> Option<(install::StoreToken, String, Vec)> { + let ext = self.core.extensions.borrow(); + let offer = ext.store_sheet.shown()?; + let (title, lines) = install::store_sheet(&offer.entry); + Some((offer.token.clone(), title, lines)) + } + + pub fn cancel_store_offer(&mut self, cx: &mut Context) { + self.core.extensions.borrow_mut().store_sheet.clear(); + cx.notify(); + } + + pub fn confirm_store_offer(&mut self, token: &install::StoreToken, cx: &mut Context) { + if !self.layout_stable() { + return; + } + let Some(install::StoreOffer { tab: key, entry: offered, .. }) = self.core.extensions.borrow_mut().store_sheet.take(token, std::time::Instant::now()) + else { + return; + }; + let busy = { + let ext = self.core.extensions.borrow(); + ext.busy.is_some() || ext.pending.is_some() || ext.choice.is_some() + }; + match self.store_check(key, busy, |context, catalog| install::store_confirm(&offered, context, catalog)) { + Ok(entry) => { + let before = self.core.extensions.borrow().generation; + self.install_extension(Install::Official(*entry), None, cx); + let mut ext = self.core.extensions.borrow_mut(); + if ext.generation != before { + ext.store_confirmed = Some((ext.generation, offered.id)); + } + } + Err(why) => self.core.extensions.borrow_mut().notices.push(why), + } + cx.notify(); + } + pub fn choose_extension_asset(&mut self, ix: usize, cx: &mut Context) { let choice = self.core.extensions.borrow_mut().choice.take(); if let Some((input, assets)) = choice diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index 17298257..126bde80 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -236,6 +236,7 @@ struct Snapshot { extension_busy: Option, extension_choice: Vec, consent: Option, + store_sheet: Option<(crate::extensions::StoreToken, String, Vec)>, catalog: (Vec, bool), card: Option, /// `None` outside an app bundle, which cannot become the default browser. @@ -263,6 +264,7 @@ pub struct SettingsWindow { appearance: appearance::Pane, _observe: Option, _activation: Subscription, + _release: Subscription, } impl SettingsWindow { @@ -324,6 +326,9 @@ impl SettingsWindow { appearance: appearance::Pane::new(cx), _observe: observe, _activation: activation, + _release: cx.on_release(|this: &mut SettingsWindow, cx| { + this.main.update(cx, |b, _, cx| b.cancel_store_offer(cx)).ok(); + }), } }) }) @@ -403,6 +408,7 @@ impl SettingsWindow { .map(|(_, a)| a.iter().map(|a| crate::extensions::shown(&a.name)).collect()) .unwrap_or_default(), consent: if self.pane == SettingsPane::Extensions { b.core.extensions.borrow().consent() } else { None }, + store_sheet: if self.pane == SettingsPane::Extensions { b.store_sheet() } else { None }, catalog: if self.pane == SettingsPane::Extensions { b.catalog_rows() } else { (Vec::new(), false) }, filters: b.core.filters.borrow().clone(), shared_data: self.pane == SettingsPane::Privacy @@ -439,6 +445,9 @@ impl SettingsWindow { } pub(crate) fn set_pane(&mut self, pane: SettingsPane, cx: &mut Context) { + if self.pane == SettingsPane::Extensions && pane != SettingsPane::Extensions { + self.with_browser(cx, |b, _, cx| b.cancel_store_offer(cx)); + } if pane == SettingsPane::Developer { self.with_browser(cx, |b, _, cx| b.refresh_local_servers(cx)); } @@ -1759,6 +1768,24 @@ impl SettingsWindow { ), ); } + if let Some((token, title, lines)) = s.store_sheet { + let card = group() + .child(row(true).child(text_block(title, "From Tarn's signed official catalog."))) + .children(lines.into_iter().map(|l| row(false).child(div().flex_1().child(l)))) + .child( + row(false) + .child(div().flex_1()) + .child( + button("store-cancel", "Cancel", true) + .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.cancel_store_offer(cx)))), + ) + .child(button("store-install", "Install", false).on_click(cx.listener(move |this, _, _, cx| { + let token = token.clone(); + this.with_browser(cx, move |b, _, cx| b.confirm_store_offer(&token, cx)) + }))), + ); + return page.child(section("Confirm")).child(card).into_any_element(); + } if let Some(c) = s.consent { let list = |title: &'static str, items: &[String]| { (!items.is_empty()).then(|| text_block(title, items.iter().map(|i| crate::extensions::shown(i)).collect::>().join(", "))) @@ -1925,6 +1952,13 @@ impl SettingsWindow { .into_any_element() })); } + official = official.child(self.link_row( + "extension-store", + "Browse the store", + "Official extensions with screenshots and search; Install in Tarn asks here first.", + browser_core::extensions::STORE_URL, + cx, + )); page = page.child(section("Official")).child(official); if old { page = page.child(note("This list is more than 30 days old. Show official extensions to get the current one.")); diff --git a/crates/browser-core/src/extensions.rs b/crates/browser-core/src/extensions.rs index 34c385f2..1bd2a414 100644 --- a/crates/browser-core/src/extensions.rs +++ b/crates/browser-core/src/extensions.rs @@ -12,6 +12,8 @@ use crate::github::{self, Fetch, Resolved}; pub mod install; +pub use engine::tarn_ext::{STORE_EVENT, STORE_URL, store_install}; + pub const MAX_ICON_BYTES: u64 = 1 << 20; pub const MAX_ICON_SIDE: u32 = 512; diff --git a/crates/browser-core/src/extensions/install.rs b/crates/browser-core/src/extensions/install.rs index 35c7a7e9..a5e497aa 100644 --- a/crates/browser-core/src/extensions/install.rs +++ b/crates/browser-core/src/extensions/install.rs @@ -5,7 +5,7 @@ use std::collections::BTreeSet; use std::path::{Path, PathBuf}; -use shield::catalog::{self, Index}; +use shield::catalog::{self, Entry, Index}; use store::{Id, InstalledExtension, Store}; use super::{Install, Step, Unpacked, badge, fetch_and_unpack, grew, may_use_all_sites, older, pattern_covers}; @@ -18,6 +18,18 @@ pub const MAX_INSTALLS: usize = 32; pub const REVOKED_SETTING: &str = "extension_revoked"; pub const CATALOG_SEEN_SETTING: &str = "extension_catalog_version"; pub const UNREVIEWED: &str = "Nobody reviewed this extension's code. It can read and change the sites you allow and send what it reads anywhere."; +pub const STORE_LINK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10); +pub const STORE_CONFIRM_DELAY: std::time::Duration = std::time::Duration::from_millis(700); +pub const STORE_REFUSED: &str = "Extensions are not installed in private spaces, burner tabs or Lockdown."; +pub const STORE_NO_CATALOG: &str = "The official catalog is not available in this build."; +pub const STORE_DOWNLOADS_OFF: &str = "Extension downloads are off in Privacy settings."; +pub const STORE_NEEDS_CATALOG: &str = + "Tarn has no current official catalog. Load it with Show Official Extensions in Settings › Extensions, then open the link again."; +pub const STORE_BUSY: &str = "An extension install is already in progress."; +pub const STORE_CHANGED: &str = "The official catalog changed since you opened the link; open it again."; +pub const STORE_FETCH_NOTE: &str = "Tarn downloads it from GitHub only when you press Install."; +pub const STORE_UNKNOWN: &str = "This extension is not in Tarn's official catalog."; +pub const STORE_WITHDRAWN: &str = "This extension was withdrawn from the official catalog."; pub const NOT_TARN: &str = "This is not a Tarn extension. Only extensions whose manifest sets browser_specific_settings.tarn.runtime to 1 run in this version of Tarn."; @@ -346,6 +358,123 @@ pub fn catalog_fetched(store: &Store, index: &Index) { merge_revoked(store, index); } +#[derive(Clone, Copy, Debug)] +pub struct StoreContext { + pub allowed: bool, + pub configured: bool, + pub downloads: bool, + pub busy: bool, +} + +#[derive(Clone, Copy, Debug)] +pub struct StoreCatalog<'a> { + pub index: Option<&'a Index>, + pub now: u64, + pub revoked: &'a BTreeSet<(String, String)>, + pub installed: &'a [InstalledExtension], +} + +pub fn store_step(id: &str, context: StoreContext, catalog: StoreCatalog) -> Result, String> { + let refuse = |why: &str| Err(why.to_owned()); + if !context.allowed { + return refuse(STORE_REFUSED); + } + if !context.configured { + return refuse(STORE_NO_CATALOG); + } + if !context.downloads { + return refuse(STORE_DOWNLOADS_OFF); + } + if context.busy { + return refuse(STORE_BUSY); + } + let Some(index) = catalog.index.filter(|c| !catalog::is_old(c, catalog.now)) else { return refuse(STORE_NEEDS_CATALOG) }; + let Some(entry) = index.extensions.iter().find(|e| e.id == id) else { return refuse(STORE_UNKNOWN) }; + let listed = |rid: &str, sha: &str| rid == entry.id && sha == entry.sha256; + if catalog.revoked.iter().any(|(rid, sha)| listed(rid, sha)) || index.revoked.iter().any(|r| listed(&r.id, &r.sha256)) { + return refuse(STORE_WITHDRAWN); + } + if catalog.installed.iter().any(|r| r.source.strip_prefix("official:") == Some(id)) { + return Err(format!("{} is already installed.", shown(&entry.name))); + } + Ok(Box::new(entry.clone())) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoreToken { + seq: u64, + id: String, + sha256: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct StoreOffer { + pub tab: crate::tabs::TabKey, + pub entry: Entry, + pub token: StoreToken, + shown: std::time::Instant, +} + +#[derive(Clone, Debug, Default)] +pub struct StoreSheet { + seq: u64, + offer: Option, +} + +impl StoreSheet { + pub fn offer(&mut self, tab: crate::tabs::TabKey, id: &str, context: StoreContext, catalog: StoreCatalog, now: std::time::Instant) -> Result<(), String> { + let entry = *store_step(id, context, catalog)?; + self.seq += 1; + let token = StoreToken { seq: self.seq, id: entry.id.clone(), sha256: entry.sha256.clone() }; + self.offer = Some(StoreOffer { tab, entry, token, shown: now }); + Ok(()) + } + + pub fn shown(&self) -> Option<&StoreOffer> { + self.offer.as_ref() + } + + pub fn clear(&mut self) { + self.offer = None; + } + + pub fn take(&mut self, token: &StoreToken, now: std::time::Instant) -> Option { + let ready = self.offer.as_ref().is_some_and(|o| o.token == *token && now.saturating_duration_since(o.shown) >= STORE_CONFIRM_DELAY); + if ready { self.offer.take() } else { None } + } +} + +pub fn store_confirm(offered: &Entry, context: StoreContext, catalog: StoreCatalog) -> Result, String> { + let entry = store_step(&offered.id, context, catalog)?; + if *entry != *offered { + return Err(STORE_CHANGED.to_owned()); + } + Ok(entry) +} + +pub fn store_sheet(entry: &Entry) -> (String, Vec) { + let list = |items: &[String]| items.iter().map(|i| shown(i)).collect::>().join(", "); + let mut lines = Vec::new(); + if !entry.description.is_empty() { + lines.push(shown(&entry.description)); + } + lines.push(format!("Source: {}", badge(&format!("official:{}", entry.id)))); + if !entry.permissions.is_empty() { + lines.push(format!("Uses: {}", list(&entry.permissions))); + } + if !entry.optional_permissions.is_empty() { + lines.push(format!("May ask for: {}", list(&entry.optional_permissions))); + } + lines.push(if entry.hosts.is_empty() { "Asks for no sites.".to_owned() } else { format!("Wants to read and change: {}", list(&entry.hosts)) }); + lines.push("It asks you on every site before it runs there, unless you let it use every site it lists.".to_owned()); + lines.push(STORE_FETCH_NOTE.to_owned()); + (format!("Install \u{201C}{}\u{201D} {}?", shown(&entry.name), shown(&entry.version)), lines) +} + +pub fn store_confirmed(confirmed: &str, source: &str) -> bool { + source.strip_prefix("official:") == Some(confirmed) +} + /// The title of the per-site prompt every client shows. pub fn access_title(name: &str, badge: &str, host: &str) -> String { format!("The extension \u{201C}{}\u{201D} ({}) wants to read and change {}", shown(name), shown(badge), shown(host)) @@ -472,6 +601,126 @@ mod tests { assert_eq!(access_title("Helper", "Official", "shop.test"), "The extension \u{201C}Helper\u{201D} (Official) wants to read and change shop.test"); } + fn store_index(now: u64) -> Index { + serde_json::from_value(serde_json::json!({ + "kind": "tarn-extensions", "version": 3, "created": now, + "extensions": [ + {"id": "helper", "name": "Helper", "description": "", "version": "1.0", "url": "https://x.test/h.zip", "sha256": "a".repeat(64), "size": 1, "permissions": [], "hosts": []}, + {"id": "gone", "name": "Gone", "description": "", "version": "1.0", "url": "https://x.test/g.zip", "sha256": "b".repeat(64), "size": 1, "permissions": [], "hosts": []}, + {"id": "pulled", "name": "Pulled", "description": "", "version": "1.0", "url": "https://x.test/p.zip", "sha256": "c".repeat(64), "size": 1, "permissions": [], "hosts": []} + ], + "revoked": [{"id": "gone", "sha256": "b".repeat(64)}] + })) + .unwrap() + } + + #[test] + fn a_store_link_offers_only_a_fresh_verified_catalog_entry_and_never_fetches() { + let now = 1_900_000_000; + let (index, old) = (store_index(now), store_index(now - 31 * 24 * 3600)); + let ok = StoreContext { allowed: true, configured: true, downloads: true, busy: false }; + let none = BTreeSet::new(); + let fresh = StoreCatalog { index: Some(&index), now, revoked: &none, installed: &[] }; + let refused = |why: &str| Err(why.to_owned()); + assert_eq!(store_step("helper", ok, fresh).unwrap().id, "helper"); + assert_eq!(store_step("helper", StoreContext { allowed: false, ..ok }, fresh), refused(STORE_REFUSED)); + assert_eq!(store_step("helper", StoreContext { configured: false, ..ok }, fresh), refused(STORE_NO_CATALOG)); + assert_eq!(store_step("helper", StoreContext { downloads: false, ..ok }, fresh), refused(STORE_DOWNLOADS_OFF)); + assert_eq!(store_step("helper", StoreContext { busy: true, ..ok }, fresh), refused(STORE_BUSY)); + assert_eq!(store_step("helper", ok, StoreCatalog { index: None, ..fresh }), refused(STORE_NEEDS_CATALOG), "no catalog: a notice, never a fetch"); + assert_eq!(store_step("helper", ok, StoreCatalog { index: Some(&old), ..fresh }), refused(STORE_NEEDS_CATALOG), "a list over 30 days old is not used"); + assert_eq!(store_step("missing", ok, fresh), refused(STORE_UNKNOWN)); + assert_eq!(store_step("gone", ok, fresh), refused(STORE_WITHDRAWN)); + let stored: BTreeSet<_> = [("pulled".to_owned(), "c".repeat(64))].into(); + assert_eq!(store_step("pulled", ok, StoreCatalog { revoked: &stored, ..fresh }), refused(STORE_WITHDRAWN)); + let other_build: BTreeSet<_> = [("pulled".to_owned(), "d".repeat(64))].into(); + assert!(store_step("pulled", ok, StoreCatalog { revoked: &other_build, ..fresh }).is_ok()); + let installed = [InstalledExtension { source: "official:helper".into(), ..Default::default() }]; + assert_eq!(store_step("helper", ok, StoreCatalog { installed: &installed, ..fresh }), refused("Helper is already installed.")); + assert!(store_step("pulled", ok, StoreCatalog { installed: &installed, ..fresh }).is_ok()); + } + + #[test] + fn the_store_confirmation_checks_everything_again_and_holds_to_the_shown_entry() { + let now = 1_900_000_000; + let index = store_index(now); + let none = BTreeSet::new(); + let ok = StoreContext { allowed: true, configured: true, downloads: true, busy: false }; + let fresh = StoreCatalog { index: Some(&index), now, revoked: &none, installed: &[] }; + let offered = *store_step("helper", ok, fresh).unwrap(); + assert_eq!(*store_confirm(&offered, ok, fresh).unwrap(), offered); + assert_eq!(store_confirm(&offered, StoreContext { allowed: false, ..ok }, fresh), Err(STORE_REFUSED.to_owned()), "a private space or Lockdown by now"); + assert_eq!(store_confirm(&offered, StoreContext { busy: true, ..ok }, fresh), Err(STORE_BUSY.to_owned())); + let stale = StoreCatalog { now: now + 31 * 24 * 3600, ..fresh }; + assert_eq!(store_confirm(&offered, ok, stale), Err(STORE_NEEDS_CATALOG.to_owned())); + let grown = Entry { hosts: vec!["*://*.bank.test/*".into()], ..offered.clone() }; + assert_eq!(store_confirm(&grown, ok, fresh), Err(STORE_CHANGED.to_owned()), "what was shown is what installs"); + } + + #[test] + fn a_new_store_link_replaces_an_unanswered_confirmation_and_only_a_running_install_blocks() { + let now = 1_900_000_000; + let index = store_index(now); + let none = BTreeSet::new(); + let ok = StoreContext { allowed: true, configured: true, downloads: true, busy: false }; + let catalog = StoreCatalog { index: Some(&index), now, revoked: &none, installed: &[] }; + let (first, second) = (crate::tabs::TabKey { private: false, id: 1 }, crate::tabs::TabKey { private: false, id: 2 }); + let at = std::time::Instant::now(); + let mut sheet = StoreSheet::default(); + sheet.offer(first, "helper", ok, catalog, at).unwrap(); + sheet.offer(second, "pulled", ok, catalog, at).unwrap(); + assert_eq!(sheet.shown().map(|o| (o.tab, o.entry.id.as_str())), Some((second, "pulled")), "the unanswered one is replaced"); + assert_eq!(sheet.offer(first, "helper", StoreContext { busy: true, ..ok }, catalog, at), Err(STORE_BUSY.to_owned())); + assert_eq!(sheet.offer(first, "missing", ok, catalog, at), Err(STORE_UNKNOWN.to_owned())); + assert_eq!(sheet.shown().map(|o| o.entry.id.as_str()), Some("pulled"), "a refused link leaves the confirmation shown"); + sheet.clear(); + assert!(sheet.shown().is_none(), "closing the pane drops it"); + } + + #[test] + fn install_confirms_only_the_sheet_it_was_drawn_for_and_not_at_once() { + let now = 1_900_000_000; + let index = store_index(now); + let none = BTreeSet::new(); + let ok = StoreContext { allowed: true, configured: true, downloads: true, busy: false }; + let catalog = StoreCatalog { index: Some(&index), now, revoked: &none, installed: &[] }; + let tab = crate::tabs::TabKey { private: false, id: 1 }; + let (at, ms) = (std::time::Instant::now(), std::time::Duration::from_millis); + let mut sheet = StoreSheet::default(); + sheet.offer(tab, "helper", ok, catalog, at).unwrap(); + let a = sheet.shown().unwrap().token.clone(); + sheet.offer(tab, "pulled", ok, catalog, at + ms(10_000)).unwrap(); + let b = sheet.shown().unwrap().token.clone(); + assert_ne!(a, b); + assert!(sheet.take(&a, at + ms(20_000)).is_none(), "a click aimed at the replaced sheet never confirms the new one"); + assert!(sheet.take(&b, at + ms(10_000) + STORE_CONFIRM_DELAY - ms(1)).is_none(), "too soon after it appeared"); + assert_eq!(sheet.shown().map(|o| o.entry.id.as_str()), Some("pulled"), "refused clicks leave the sheet"); + let taken = sheet.take(&b, at + ms(10_000) + STORE_CONFIRM_DELAY).unwrap(); + assert_eq!(taken.entry.id, "pulled"); + assert!(sheet.shown().is_none() && sheet.take(&b, at + ms(30_000)).is_none(), "taken once"); + sheet.offer(tab, "helper", ok, catalog, at + ms(40_000)).unwrap(); + let again = sheet.shown().unwrap().token.clone(); + assert!(again != a && sheet.take(&a, at + ms(50_000)).is_none(), "the same entry offered again gets a new token"); + } + + #[test] + fn the_store_sheet_shows_only_the_signed_entry() { + let index = store_index(1_900_000_000); + let entry = Entry { + optional_permissions: vec!["tabs".into()], + hosts: vec!["*://*.shop.test/*".into()], + permissions: vec!["storage".into()], + ..index.extensions[0].clone() + }; + let (title, lines) = store_sheet(&entry); + assert_eq!(title, "Install \u{201C}Helper\u{201D} 1.0?"); + assert!( + lines.contains(&"Source: Official".to_owned()) && lines.contains(&"Uses: storage".to_owned()) && lines.contains(&"May ask for: tabs".to_owned()) + ); + assert!(lines.contains(&"Wants to read and change: *://*.shop.test/*".to_owned()) && lines.last().map(String::as_str) == Some(STORE_FETCH_NOTE)); + assert!(store_confirmed("helper", "official:helper") && !store_confirmed("helper", "official:other") && !store_confirmed("helper", "github:1")); + } + struct NoNet; impl Fetch for NoNet { diff --git a/crates/browser-core/src/lib.rs b/crates/browser-core/src/lib.rs index 90ba6f13..4c3786c3 100644 --- a/crates/browser-core/src/lib.rs +++ b/crates/browser-core/src/lib.rs @@ -144,6 +144,7 @@ pub struct Core { judged: Cell>, /// Profiles of the private store that each hold one window's burner tab. pub burners: RefCell>, + store_link_at: Cell>, } impl Core { @@ -187,6 +188,7 @@ impl Core { #[cfg(any(target_os = "macos", windows))] judged: Cell::new(None), burners: RefCell::default(), + store_link_at: Cell::default(), } } @@ -208,6 +210,19 @@ impl Core { self.profiles.borrow().get(&(private, profile_id)).map(|rt| effective_level(&rt.profile, &rt.overrides, url)) } + pub fn admit_store_link(&self, now: std::time::Instant) -> bool { + let admitted = self.store_link_at.get().is_none_or(|at| now.saturating_duration_since(at) >= extensions::install::STORE_LINK_INTERVAL); + if admitted { + self.store_link_at.set(Some(now)); + } + admitted + } + + pub fn store_link_allowed(&self, private: bool, profile_id: Id, page: Option<&Url>) -> bool { + let store = Url::parse(engine::tarn_ext::STORE_URL).ok(); + !private && [None, page, store.as_ref()].into_iter().all(|url| self.level(false, profile_id, url).is_some_and(|l| l != ShieldLevel::Lockdown)) + } + /// An address the user opens (typed, completed or from another app) without the tracking /// parameters its Shield level strips; links from pages are left alone. pub fn clean_user_url(&self, profile: Option<(bool, Id)>, url: Url) -> Url { @@ -464,6 +479,41 @@ mod tests { assert_eq!(core.web_engine(false, p, None, Url::parse("https://a.test/").ok().as_ref()), Some(WebEngine::Chromium)); } + #[test] + fn store_links_install_only_outside_private_spaces_and_lockdown() { + let dir = tempfile::tempdir().unwrap(); + let core = TestCore::open(dir.path(), true); + let p = core.disk.profiles().unwrap().remove(0).id; + let (page, locked) = (Url::parse("https://a.test/").unwrap(), Url::parse("https://locked.test/").unwrap()); + assert!(!core.store_link_allowed(false, p, Some(&page)), "not opened yet"); + core.disk.set_site_override(p, "locked.test", Some(ShieldLevel::Lockdown)).unwrap(); + core.open_profile(false, p, downloads).unwrap(); + assert!(core.store_link_allowed(false, p, Some(&page)) && core.store_link_allowed(false, p, None)); + assert!(!core.store_link_allowed(true, p, Some(&page)), "private spaces and burner tabs"); + assert!(!core.store_link_allowed(false, p, Some(&locked)), "from a Lockdown site"); + core.profiles.borrow()[&(false, p)].overrides.borrow_mut().insert(engine::tarn_ext::STORE_HOST.to_owned(), ShieldLevel::Lockdown); + assert!(!core.store_link_allowed(false, p, Some(&page)), "the store set to Lockdown"); + let q = core.disk.create_profile("Q", "uuid-q", false).unwrap().id; + core.disk.set_profile_shield_level(q, ShieldLevel::Lockdown).unwrap(); + core.open_profile(false, q, downloads).unwrap(); + assert!(!core.store_link_allowed(false, q, Some(&page)), "a Lockdown profile"); + } + + #[test] + fn one_store_link_is_taken_per_interval() { + let dir = tempfile::tempdir().unwrap(); + let core = TestCore::open(dir.path(), true); + let start = std::time::Instant::now(); + let interval = extensions::install::STORE_LINK_INTERVAL; + assert!(core.admit_store_link(start)); + assert!(!core.admit_store_link(start)); + assert!(!core.admit_store_link(start + interval - std::time::Duration::from_millis(1)), "inside the window it is ignored"); + assert!(core.admit_store_link(start + interval)); + assert!(!core.admit_store_link(start + interval + std::time::Duration::from_secs(9)), "an ignored link does not move the window"); + assert!(core.admit_store_link(start + interval * 2)); + assert!(!core.admit_store_link(start), "a clock that went back admits nothing"); + } + #[test] fn user_addresses_lose_tracking_parameters() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/engine/src/chromium/view.rs b/crates/engine/src/chromium/view.rs index cea40c56..09abd543 100644 --- a/crates/engine/src/chromium/view.rs +++ b/crates/engine/src/chromium/view.rs @@ -718,15 +718,21 @@ wrap_request_handler! { emit(&tab, Event::WebEngineOutdated); return 1; } - let (shell, user_started) = if is_redirect == 1 { - (false, tab.user_started.get()) + let (shell, user_started, link) = if is_redirect == 1 { + (false, tab.user_started.get(), false) } else { let (shell, step) = (tab.shell_load.take().is_some_and(|u| u == url), tab.history_step.take().contains(&url)); // CEF reports the shell's own LoadURL as a gesture; a link the shell loads for a page stays the page's. let link = tab.link_load.take(); - (shell, !link && (shell || user_gesture == 1 || step)) + (shell, !link && (shell || user_gesture == 1 || step), link) }; tab.user_started.set(user_started); + if nav_policy::chromium_store_link(is_redirect == 1, shell, link, user_gesture == 1) + && let Some(id) = crate::tarn_ext::store_install(&url) + { + emit(&tab, Event::StoreInstall(id)); + return 1; + } let source = if shell { Source::Typed } else { Source::Link }; match nav_policy::decide_chromium(&url, source) { #[cfg(target_os = "macos")] diff --git a/crates/engine/src/delegates.rs b/crates/engine/src/delegates.rs index 5b22cf8a..b9b22f4f 100644 --- a/crates/engine/src/delegates.rs +++ b/crates/engine/src/delegates.rs @@ -225,6 +225,13 @@ pub(crate) fn page_title(view: &WKWebView) -> String { bounded(&title) } +fn store_link_activated(action: &WKNavigationAction, shell_load: bool, page_link: bool, redirect: bool) -> bool { + let known = action.respondsToSelector(sel!(_isRedirect)) && action.respondsToSelector(sel!(_isUserInitiated)); + // SAFETY: main-thread reads of the live action; the private selector exists (checked first) and returns a BOOL. + let clicked = known && unsafe { action.navigationType() == WKNavigationType::LinkActivated && msg_send![action, _isUserInitiated] }; + nav_policy::store_link_asks(nav_policy::StoreNav { redirect, shell_load, page_link, clicked }) +} + pub(crate) fn to_url(url: Option>) -> Option { let s = url?.absoluteString()?.to_string(); Url::parse(&s).ok() @@ -346,6 +353,13 @@ define_class!( handler.call((WKNavigationActionPolicy::Cancel, prefs)); return; }; + if store_link_activated(action, from_shell, link, redirect) + && let Some(id) = crate::tarn_ext::store_install(&url) + { + self.emit(Event::StoreInstall(id)); + handler.call((WKNavigationActionPolicy::Cancel, prefs)); + return; + } match nav_policy::decide(&url, Source::Link) { Decision::Allow => {} Decision::Prompt => { diff --git a/crates/engine/src/events.rs b/crates/engine/src/events.rs index e3d4617c..5e09580d 100644 --- a/crates/engine/src/events.rs +++ b/crates/engine/src/events.rs @@ -91,6 +91,7 @@ pub enum Event { from: Option, background: bool, }, + StoreInstall(String), /// A link to another app's scheme; the shell must ask before handing it off. `origin` is the /// frame that started it, `None` for the shell's own loads and opaque origins. ExternalScheme { diff --git a/crates/engine/src/nav_policy.rs b/crates/engine/src/nav_policy.rs index 6980718e..9e064662 100644 --- a/crates/engine/src/nav_policy.rs +++ b/crates/engine/src/nav_policy.rs @@ -144,6 +144,22 @@ pub fn user_started(shell_load: bool, link: bool, history_step: bool, redirect: (shell_load && !link) || history_step || (redirect && pending_user_load) } +#[derive(Debug, Clone, Copy, Default)] +pub struct StoreNav { + pub redirect: bool, + pub shell_load: bool, + pub page_link: bool, + pub clicked: bool, +} + +pub fn store_link_asks(nav: StoreNav) -> bool { + !nav.redirect && !nav.page_link && (nav.shell_load || nav.clicked) +} + +pub fn chromium_store_link(redirect: bool, shell_load: bool, link_load: bool, user_gesture: bool) -> bool { + store_link_asks(StoreNav { redirect, shell_load, page_link: link_load, clicked: user_gesture }) +} + /// Whether a main-frame navigation away from the page `from` into a local address is refused (a /// router's admin page, a local service): a script may not take a tab from the public web onto the /// local network; the user may, by navigations the caller judges as theirs (typed, history steps the shell started; in Chromium also a click with a user gesture), also through redirects. A `blob:` @@ -244,6 +260,22 @@ pub fn chromium_external(url: &Url, source: Source) -> bool { #[cfg(test)] mod tests { + #[test] + fn only_the_users_own_navigation_asks_for_a_store_install() { + use super::{StoreNav, chromium_store_link, store_link_asks}; + let asks = |redirect, shell_load, page_link, clicked| store_link_asks(StoreNav { redirect, shell_load, page_link, clicked }); + assert!(asks(false, true, false, false), "typed"); + assert!(asks(false, false, false, true), "a click the engine credits to the user"); + assert!(!asks(false, false, false, false), "a script's navigation without a gesture"); + assert!(!asks(true, true, false, false) && !asks(true, false, false, true), "a redirect never"); + assert!(!asks(false, true, true, false), "a link the shell loads for a page (peek, pop-up tab)"); + assert!(chromium_store_link(false, false, false, true), "Chromium: a click with a gesture"); + assert!(chromium_store_link(false, true, false, true), "Chromium: the shell's own load, which CEF reports as a gesture"); + assert!(!chromium_store_link(true, false, false, true), "Chromium: the redirect of a gesture's navigation"); + assert!(!chromium_store_link(false, true, true, true), "Chromium: a peek or pop-up the shell loads for the page"); + assert!(!chromium_store_link(false, false, false, false), "Chromium: a script navigation without a gesture"); + } + #[test] fn chromium_hands_off_only_app_schemes() { use super::Source::*; diff --git a/crates/engine/src/tarn_ext.rs b/crates/engine/src/tarn_ext.rs index ca00a83a..e4be6764 100644 --- a/crates/engine/src/tarn_ext.rs +++ b/crates/engine/src/tarn_ext.rs @@ -18,6 +18,9 @@ pub const WORLD_PREFIX: &str = "tarn-ext-"; pub const POST: &str = "__tarnExtPost"; pub const RECEIVE: &str = "__tarnExtReceive"; pub const MAX_MESSAGE_BYTES: usize = 1 << 20; +pub const STORE_HOST: &str = "extensions.tarnbrowser.com"; +pub const STORE_URL: &str = "https://extensions.tarnbrowser.com/"; +pub const STORE_EVENT: &str = "storeInstall"; /// Starts the messages an engine's own setup code sends; the shim only sends JSON objects. pub const HELLO: char = '\u{1}'; pub const DOCUMENT: &str = "__tarnExtDoc"; @@ -146,6 +149,15 @@ pub fn opens_as_tab(url: &Url) -> bool { && !shield::rules::is_local(url, true) } +pub fn store_install(url: &Url) -> Option { + if url.scheme() != "https" || url.host_str() != Some(STORE_HOST) || url.port().is_some() || !url.username().is_empty() || url.password().is_some() { + return None; + } + let id = url.path().strip_prefix("/install/")?; + let id = id.strip_suffix('/').unwrap_or(id); + shield::catalog::valid_id(id).then(|| id.to_owned()) +} + /// The shim that defines `chrome.*` and `browser.*` from `config`, made by the core. pub fn bootstrap(config: &Value) -> String { format!("{SHIM}({config});\n") @@ -306,6 +318,41 @@ pub fn reply(doc: Option<&str>, json: &str) -> String { mod tests { use super::*; + #[test] + fn only_the_store_install_address_names_a_catalog_id() { + let id = |s: &str| store_install(&Url::parse(s).unwrap()); + assert_eq!(id("https://extensions.tarnbrowser.com/install/ublock-lite"), Some("ublock-lite".into())); + assert_eq!(id("https://extensions.tarnbrowser.com/install/ublock-lite/"), Some("ublock-lite".into())); + assert_eq!(id("https://EXTENSIONS.tarnbrowser.com/install/a1?x=1#y"), Some("a1".into())); + assert_eq!(id("https://extensions.tarnbrowser.com:443/install/a1"), Some("a1".into())); + assert_eq!(id(&format!("https://extensions.tarnbrowser.com/install/{}", "a".repeat(64))), Some("a".repeat(64))); + for refused in [ + "http://extensions.tarnbrowser.com/install/a1", + "https://extensions.tarnbrowser.com./install/a1", + "https://evil.extensions.tarnbrowser.com/install/a1", + "https://tarnbrowser.com/install/a1", + "https://extensions.tarnbrowser.com.evil.test/install/a1", + "https://extensions.tarnbrowser.com:8443/install/a1", + "https://user@extensions.tarnbrowser.com/install/a1", + "https://:pw@extensions.tarnbrowser.com/install/a1", + "https://extensions.tarnbrowser.com/", + "https://extensions.tarnbrowser.com/install/", + "https://extensions.tarnbrowser.com/install//", + "https://extensions.tarnbrowser.com/install", + "https://extensions.tarnbrowser.com/extension/a1", + "https://extensions.tarnbrowser.com/install/a1/b", + "https://extensions.tarnbrowser.com/install/a1//", + "https://extensions.tarnbrowser.com/install/A1", + "https://extensions.tarnbrowser.com/install/a_1", + "https://extensions.tarnbrowser.com/install/a%2D1", + "https://extensions.tarnbrowser.com/x/install/a1", + "tarn-extension://extensions.tarnbrowser.com/install/a1", + ] { + assert_eq!(id(refused), None, "{refused}"); + } + assert_eq!(id(&format!("https://extensions.tarnbrowser.com/install/{}", "a".repeat(65))), None); + } + #[test] fn worlds_name_one_install() { let world = World::for_install("0123abcd").unwrap(); diff --git a/crates/engine/tests/common/mod.rs b/crates/engine/tests/common/mod.rs index 96e5e3af..fcea6db6 100644 --- a/crates/engine/tests/common/mod.rs +++ b/crates/engine/tests/common/mod.rs @@ -64,6 +64,8 @@ const SUB_WAIT: &str = "SUB"; +const STORE_LINK: &str = "https://extensions.tarnbrowser.com/install/helper"; + /// Serves the test site; `seen` gets `host path` of every request. pub fn serve(seen: Arc>>) -> u16 { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); @@ -95,12 +97,26 @@ pub fn serve(seen: Arc>>) -> u16 { while path.ends_with("?wait") && !seen.lock().unwrap().iter().any(|s| s == "release") && Instant::now() < until { std::thread::sleep(Duration::from_millis(50)); } + if route == "/store-redirect" { + write!(stream, "HTTP/1.1 302 Found\r\nLocation: {STORE_LINK}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").ok(); + return; + } if route == "/nocontent" { std::thread::sleep(Duration::from_millis(1000)); write!(stream, "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n").ok(); return; } + let store = format!( + "STORElink\ + ", + match path.split('?').nth(1) { + Some("click") => "document.getElementById('l').click()".to_owned(), + Some("assign") => format!("location.href = '{STORE_LINK}'"), + _ => String::new(), + } + ); let (kind, body) = match route { + "/store" => ("text/html", store.as_str()), _ if route.ends_with(".js") => ("text/javascript", "window.blockedRan = 1;"), "/probe" => ("text/html", PROBE), "/frames" => ("text/html", FRAMES), diff --git a/crates/engine/tests/tarn_extension.rs b/crates/engine/tests/tarn_extension.rs index ec44c3cc..f88ceb90 100644 --- a/crates/engine/tests/tarn_extension.rs +++ b/crates/engine/tests/tarn_extension.rs @@ -24,6 +24,8 @@ mod window { use super::common::{INSTALL, ORIGIN, View, fixture, serve, spin, window}; + const BLOCKED_BY_CONTENT_RULE: isize = 104; + pub fn run() { let mtm = MainThreadMarker::new().expect("main thread"); let window = window(mtm); @@ -47,7 +49,9 @@ mod window { let uuid = "6A1B2C3D-0000-4000-8000-00000000E715"; let data = DataStore::persistent(uuid, uuid, Rc::new(|_| {})).unwrap(); - let rules = format!(r#"[{{"trigger":{{"url-filter":"^http://127\\.0\\.0\\.1:{port}/blocked\\.js"}},"action":{{"type":"block"}}}}]"#); + let rules = format!( + r#"[{{"trigger":{{"url-filter":"^http://127\\.0\\.0\\.1:{port}/blocked\\.js"}},"action":{{"type":"block"}}}},{{"trigger":{{"url-filter":"^https://extension\\.tarnbrowser\\.com/"}},"action":{{"type":"block"}}}}]"# + ); let compiled: Rc>> = Rc::default(); let slot = compiled.clone(); FilterLists::compile("tarn-ext.test", "1", vec![rules], move |r| *slot.borrow_mut() = Some(r.expect("rules compile"))); @@ -315,6 +319,36 @@ mod window { drop(page); drop(views.borrow_mut().drain(..)); drop((granted, other, ungated, tab, probe, locked, frames, twice)); + let asked: Rc>> = Rc::default(); + let failed: Rc>> = Rc::default(); + let store_sink = { + let (asked, failed) = (asked.clone(), failed.clone()); + Rc::new(move |e: Event| match e { + Event::StoreInstall(id) => asked.borrow_mut().push(id), + Event::Failed { code, .. } => failed.borrow_mut().push(code), + _ => {} + }) + }; + let link = "https://extensions.tarnbrowser.com/install/helper"; + let store = WebView::new(&host, &data, ShieldLevel::Standard, true, false, site_for.clone(), store_sink); + store.set_frame(0., 0., 800., 600.); + for page in ["store?click", "store?assign", "store-redirect"] { + failed.borrow_mut().clear(); + store.load(&Url::parse(&format!("http://127.0.0.1:{port}/{page}")).unwrap()); + let reached = || failed.borrow().contains(&BLOCKED_BY_CONTENT_RULE); + spin(10.0, &reached); + assert!(reached(), "{page}: the navigation to the store link was let through (and blocked by the test's rule): {:?}", failed.borrow()); + if page != "store-redirect" { + assert_eq!(store.title(), "RAN", "{page}: the page's script ran"); + } else { + assert_eq!(requested(&format!("127.0.0.1:{port} /store-redirect")), 1, "the redirect was served"); + } + assert!(asked.borrow().is_empty(), "{page}: a script, a frame or a redirect never asks to install: {:?}", asked.borrow()); + } + store.load(&Url::parse(&format!("{link}/")).unwrap()); + spin(3.0, &|| !asked.borrow().is_empty()); + assert_eq!(*asked.borrow(), ["helper"], "the user's own load asks"); + drop(store); DataStore::wipe_persistent(uuid); FilterLists::remove("tarn-ext.test"); window.close(); diff --git a/crates/shield/src/catalog.rs b/crates/shield/src/catalog.rs index 07cad1b9..1890902b 100644 --- a/crates/shield/src/catalog.rs +++ b/crates/shield/src/catalog.rs @@ -143,7 +143,7 @@ pub fn signed_message(index: &[u8]) -> Vec { EXTENSIONS.signed_message(index) } -fn valid_id(id: &str) -> bool { +pub fn valid_id(id: &str) -> bool { (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') } diff --git a/docs/mobile-plan.md b/docs/mobile-plan.md index 101b6fce..bb3a2ea1 100644 --- a/docs/mobile-plan.md +++ b/docs/mobile-plan.md @@ -286,6 +286,16 @@ worlds_supported, frame_event}` in its crate, the `extensionPost` command and `e `tarn.webview`, and the `tarn.extpage` component (`mobile/app` reaches the crate as `platform::ext`). All decisions come from `browser_core::tarn_ext`. +- **Store install link** (`docs/shared-core.md` §1). iOS cancels it in the navigation delegate + (`ios/src/component.rs`, `ios/src/store_link.rs`: a shell load or a main-frame `linkActivated` + navigation). iOS uses no private WebKit API and has no public user-gesture or redirect flag, so a page's + own script-started link click, or a redirect after a link click, can raise the confirmation built from the + held catalog entry; the shell takes at most one store link per 10 s (`Core::admit_store_link`, on every + client), and nothing is requested or installed until the user presses Install on it. Android in `shouldOverrideUrlLoading` (main frame, `hasGesture`, not `isRedirect`) and + in its shell load (`Native.storeInstall`); both emit `storeInstall`, and the shared shell checks + `Shell::store_link_allowed` and opens Settings › Extensions on the confirmation, or shows the notice on + the tab (`tarn_nsh_shared::extensions::store_link`). A routed pop-up to the install address keeps its + opener, so it never asks. Not yet run in the simulator or the emulator. - **Shared shell** (`app/src/extensions.rs`, `app/src/ui/extensions.rs`). For the persistent profile on screen it loads each enabled install with `tarn_ext::load`, so the tree is hashed against the stored hash before anything runs (a mismatch turns the install off and drops its site answers, as on desktop); a diff --git a/docs/nsh-plan.md b/docs/nsh-plan.md index a060cfcd..bee43034 100644 --- a/docs/nsh-plan.md +++ b/docs/nsh-plan.md @@ -118,6 +118,13 @@ runtime in `browser_core::tarn_ext`; the shell only carries out its decisions. Gaps, with their reason: +- **Store links in frames.** WebKitGTK's navigation policy decision names no frame: the pinned + `webkit6` 0.6.1 `NavigationAction` has only `frame_name`, the target name a page may give, and + no main-frame flag. So the user's own click (with a gesture) on an install link inside a frame + also opens the consent for that catalog id. Frames a page loads and script navigations without + a gesture never do (`linux/src/webview/display_tests.rs`), and the consent still shows only + Tarn's verified catalog entry and waits for the user. + - **Messaging from subframes.** WebKitGTK gives the UI process no frame for a script message: in WebKitGTK 2.54.2 (Fedora 43, checked 2026-11-16) and the pinned `webkit6` 0.6.1, `script-message-received` carries only the value and `script-message-with-reply-received` adds diff --git a/docs/shared-core.md b/docs/shared-core.md index 90d3e5c9..05f6057f 100644 --- a/docs/shared-core.md +++ b/docs/shared-core.md @@ -104,6 +104,30 @@ checked installs (`replace`, `insert`, `retain`), the session's grants (`gate`, Every shell reads the "every site" switch with `extensions::every_site_setting`, and installs go through `extensions::install` (`slot`, `vet`, `carry_over`, the signed catalog). +Store install link: every implementation cancels a main-frame navigation the user started +(`nav_policy::store_link_asks`: a shell load that is not a link or pop-up the shell loads for a +page, or a link click with a user gesture) +whose URL `tarn_ext::store_install` maps to a catalog id (exactly +`https://extensions.tarnbrowser.com/install/`, with or without a final `/`), before any +request, and reports `Event::StoreInstall(id)`; NSH engines emit `tarn_ext::STORE_EVENT` +(`storeInstall`, `{id}`). Redirects, subframes and script navigations without a gesture load +normally. WebKit on macOS reads the gesture from the navigation action's private +`_isUserInitiated` and redirects from `_isRedirect`; without them only shell loads count. iOS uses +only public signals: a shell load or a main-frame `linkActivated` navigation, script-started ones +and redirects after a link click included. The shell takes at most one store link per `install::STORE_LINK_INTERVAL` (10 s, +`Core::admit_store_link`) and ignores the others without a sheet. It makes no request on the +link: `extensions::install::store_step` (with `Core::store_link_allowed` for the tab and the +catalog copy the shell already holds) returns the entry, which the shell keeps in an +`install::StoreSheet` and Settings › Extensions shows with `store_sheet`, or the notice the shell +shows on the tab (no fresh catalog: load it in Settings › Extensions). A new store link replaces +the sheet under a new `StoreToken` (sequence number, id and SHA-256); closing the Extensions pane +or Settings drops it. The Install button carries the token of the sheet it was drawn for, and +`StoreSheet::take` hands the offer over only for that token and only `STORE_CONFIRM_DELAY` (700 ms) +after the sheet appeared (on macOS and Windows also only while `Browser::layout_stable`); then +`store_confirm` checks everything again (and the same entry), then `Install::Official(entry)`; when the unpacked package's source is that entry +(`store_confirmed`) the shell confirms it without a second prompt. Settings › Extensions links +`extensions::STORE_URL` on every client. + The shim (`tarn_ext_shim.js`) defines `chrome.*` and `browser.*` and talks only through these two functions: it sends `{"id": , "call": "", "args": [...]}` and receives `{"id": , "result": ...}`, `{"id": , "error": "..."}` or an event diff --git a/docs/threat-model.md b/docs/threat-model.md index 7ea96a06..499303d2 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -13,7 +13,7 @@ settings per client are in `cryptography.md`; the actors, components and externa | S2 | High | Prompt injection makes the AI leak data or act | The model has no tools in any provider. Output is rendered natively as text: no remote images, no auto-opened links. Grouping returns schema-validated JSON limited to the tab IDs sent and is applied after confirmation. Context is limited to the active profile; query strings are stripped from URLs. | Not built. | | S3 | High | API token or page content leaks | Token only in the Keychain. Content leaves the device only after an explicit click with a visible indicator. AI is unavailable in the private profile. We never read the CLI's stored credentials. | Not built. | | S4 | High | Malicious update | EdDSA-signed updates, HTTPS, downgrade protection, signing keys only in the signing environments of the release workflow. On Windows, `platform::updater` reads `windows-update.json` next to the appcast: its Ed25519 signature (the Sparkle key in `packaging/updates.conf`, compiled in) is checked over the exact bytes before anything is parsed; the installer must come over https from this repository's release downloads, match the signed length, SHA-256 and its own Ed25519 signature before it is written, and is hashed again through a handle that bars writes while it starts; only a later version is offered; feeds are capped at 64 KiB and installers at 512 MiB. Windows releases ship the unsigned installer CI built: the release workflow's signing job, which runs no build code, signs that run's installer and its `windows-update.json` with the update key (`scripts/windows-feed.sh`, its URL limited to this repository's release downloads), so installs have no Authenticode signature; `scripts/sign-windows.ps1` (Authenticode) is not part of CI and no certificate is set up. Remaining on Windows: the installer is not Authenticode-checked by the updater, so the Ed25519 key is the only anchor, and a replayed feed that lists the running version still counts as a verified check (as on macOS) until releases carry an expiry. Repository: two-factor login, branch protection, pinned actions, no secrets for fork pull requests. | CI actions pinned by commit hash; no job that pull requests, issues or comments can start runs on a self-hosted runner: enforced only by the runner group's "Selected workflows" limit and fork-approval settings in `release.md`, applied by hand, since a fork pull request runs its own edited workflow; `scripts/check-workflows.sh` in CI is a merge-time lint that keeps such jobs out of `main`, not a control on what a pull request can schedule; `.github/CODEOWNERS` covers the workflows, `codesign-app.sh`, `bundle.sh`, `packaging/`, the lockfiles and manifests and the embedded signing keys (owner `@Quavon-dev/maintainers`), and `main`'s ruleset requires approval of the most recent push and dismisses stale approvals (settings by hand); Chromium updates are proposed by `chromium-update.yml` as pull requests that run CI and need a maintainer's approval like any other; once merged, it tags them and `release.yml` signs and publishes them only after a maintainer approves its `release-signing` deployment. Updater: Sparkle 2.10.1, pinned by SHA-256, verifies the archive's EdDSA signature before extraction, requires a signed feed and refuses older versions; the feed (the latest published GitHub release's `appcast.xml`) and the public key are in `packaging/updates.conf` and only release bundles carry them; the private key, the Developer ID certificate and the notary API key are secrets of the `release-signing` environment (deployments from `main` and `v*` tags, a maintainer's approval) and the `nightly-signing` environment (deployments from `main` only, no approval) and the private key has an offline backup; only the `sign` job enters them, runs no build code, imports the certificate into a temporary keychain and writes the other keys under `RUNNER_TEMP`, and deletes both when it ends. A compromised build job or dependency build script holds none of them, but a workflow or script changed on `main` runs with them on the next nightly without approval and could sign a feed that Release users accept, since both channels share the update key (Sparkle takes one `SUPublicEDKey`); code-owner review of `.github/` and `scripts/` on `main` is what stands in the way, and `scripts/appcast.sh` signs only a notarised Tarn of team CFV35FGSHF whose version matches the tag. The feed URL comes from Info.plist through the updater delegate, never from user defaults; with Settings › General › Nightly builds on it is the same file in the `nightly` release (`platform::updater::nightly_feed`), on macOS and Windows. Nightly builds carry `.` versions and are signed with the same keys: every commit merged to `main`, including engine updates (reviewed, with a CEF archive whose hash only `chromium-update.yml`'s own download checked), reaches users of that channel signed and notarised within a day, with no release review. Nightly feeds carry their channel inside the signed bytes (`sparkle:channel`, the Windows feed's `channel`), and the Release channel refuses them, so a nightly feed uploaded to a release is not offered to Release users. A nightly on the Release channel counts the release feed as current for its release version (`channel_version`) and is offered only a later release. A check counts as verified for the Chromium staleness gate only if the signed appcast lists the running version or a later one, so an old appcast replayed through a release asset no longer keeps Chromium open; one listing the running version still does. A feed that fails verification still offers items in Sparkle's fallback mode (no critical marking); the archive signature still applies. Tampered and older updates not yet tried against a real feed. Windows, Linux and mobile release files are built unsigned from pinned containers and a pinned rustup-init but with unpinned distribution packages and Gradle dependencies; they are attested by a job that runs none of their code, and each build job can add only its own file names to the release. A release run starts from a `v*` tag push (tag creation limited by ruleset), from `start-release.yml` on `main` (any account with write access can start it; it builds every client without keys, and only after a maintainer approves the `release-signing` deployment does the `sign` job create the `v*` tag with the update app, whose key that environment then also holds, so this tag is the app's, not a maintainer's signed tag), a manual `workflow_dispatch` on an existing `v*` tag, which any account with write access can start and which builds macOS alone, or `chromium-update.yml`; it never replaces a published release's files (a re-run of a published tag only marks the highest version latest) and publishes only after the `release-signing` deployment is approved. `nightly.yml` publishes the `nightly` pre-release without approval. The signed zip, disk image and feeds are in `SHA256SUMS` and the attestation. | -| S18 | High | Malicious or compromised extension | Per-profile install, per-site permission prompts, hash recorded, no silent updates, off in private mode by default, no access to internal pages or other profiles. | App and Official extensions get every site they list without a prompt while Settings › Extensions › "Allow extensions on every site" is on, which is the default (`Pref::ExtensionsEverySite`); Unverified ones always ask per site and Lockdown hosts stay denied. `tabs.create` from an App extension opens a web page as a normal tab through `nav_policy`, at the pop-up rate (3 in 10 s) and never with a private-network address as its URL (S10). Open: that tab is a user load, so a redirect of its URL to a private address is followed. With the global switch on, an update that asks for more sites is not held back. Only Safari web extensions bundled with apps in `/Applications` are offered (`engine::extensions`); nothing runs until the user turns an extension on for the current profile in Settings › Extensions, which lists every requested permission and site pattern. Turning it on grants all of them (no per-site prompts). Each profile has its own `WKWebExtensionController`: storage is keyed by the profile's own data-store UUID, also when it shares website data with another profile, the private space gets an in-memory controller with nothing enabled, Lockdown profiles and Lockdown-level views get no controller, and hosts with a Lockdown override are denied to every extension (checked: the content script stops answering), because a link into such a host keeps its view. An extension sees only the tabs of its own profile. Its `safari-web-extension://` origin (Safari's scheme, which Bitwarden's inline menu requires), which pages can see, is derived from the profile's data-store UUID, so it differs per user and profile; sites that probe for Bitwarden's Safari pages find it as they would in Safari. `windows.create` opens a window only for the extension's own pages (Bitwarden's unlock, passkey and edit popouts), at most four per extension, each side between 200 and 1000 points and the height kept on screen; the window's top-level navigations are held to the extension's own pages, because it has no navigation policy or Shield, and it closes when the extension is turned off or its data is removed. Only the extension that opened it sees it. Frames inside it are not restricted and it shows no origin chip, as with the extension's toolbar popup. Native messages and native ports are answered only for an app extension whose code signature is Bitwarden's (`com.bitwarden.desktop.safari`, signed by team `LTZ2PFU5D6`, or by Apple for the Mac App Store with that team's entitlement), checked when extensions are discovered, and only for the four Bitwarden uses (`copyToClipboard`, `readFromClipboard`, `sleep` with at most 16 pending, `showPopover`); a native port (`connectNative`) is accepted only for Bitwarden's app id, at most four per extension, closed with the extension, and answers only Bitwarden's biometrics questions as its Safari app extension does: Touch ID through LocalAuthentication, then the user key the Bitwarden desktop app keeps in the login keychain (`Bitwarden_biometric`, account `_user_biometric`), read off the main thread after Touch ID succeeded and handed only to that port; one Touch ID prompt at a time, naming the extension; once Bitwarden has run in a profile, until Tarn restarts, pages there (not at Lockdown) are told that passkeys and conditional mediation are available, as in Safari, but only in frames where `navigator.credentials.get` has been replaced again, by Bitwarden's page script or the page itself; WebKit says no without Apple's browser entitlement and refuses conditional requests at once, so in those frames such a refusal of a request with an abort signal stays pending until the page aborts it, as Safari's conditional UI does, and Bitwarden's answer is not cut short; elsewhere WebKit's own answers are returned, the availability one after waiting while the document still parses, at most 40 checks 50 ms apart; clipboard writes need the granted `clipboardWrite` permission and reads also need `clipboardRead` in the manifest, which Settings then lists. Deleting a profile removes its extensions' data through WebKit and then WebKit's folder for it, whose `State.plist` names each extension; "Delete everything" removes the data and restarts the profile's extensions. Tarn has no internal web pages to reach. Extensions can also be installed from a GitHub repository, the signed official catalog (own ed25519 key, domain-separated signature, rollback and 30-day freshness checks, a revoked set that only grows) and `.zip`/`.crx` files: archives are unpacked with strict name, size, depth and type checks into read-only per-install directories; storage is keyed by a random install id; the tree hash is recorded at install and checked before every load, `.appex` bundles included, and a mismatch turns the extension off and drops its site grants; trust labels and the Bitwarden privileges (native messages, clipboard read, passkey script, pop-out windows) follow the install source, never the manifest; unpacked extensions show a popup only after a toolbar click. Host access is per site: the grant-all loop is gone, WebKit's own URL prompt becomes a tab-modal Allow/Deny with Remember (Once lasts an hour), decisions are stored per install and profile, and App and Official sources may be switched to "Allow on every site", which turns off when an update asks for more sites (without effect while the global switch is on). Extension pages, workers and popups get the profile's private-network and HTTPS rule lists. `Tab` refuses `loadURL`, reload, back, forward and zoom without access to the tab's page. Updates are a new install with the same prompt, never automatic. Tarn extensions (`manifest_version` 3 with `browser_specific_settings.tarn.runtime` 1) run on Tarn's own runtime (`browser_core::tarn_ext`, contract `engine::tarn_ext`), the same on every engine: a package using any manifest key, permission (only `storage`, `activeTab`, `declarativeNetRequest`), content-script option or network-rule action outside the subset is refused at install with the key named, and `redirect`, `modifyHeaders` and `allowAllRequests` rules always are, as are a `priority` other than 1, a port in a site pattern and more than 1000 `regexFilter` rules; content scripts and their CSS run only in the install's isolated world `tarn-ext-`, only in http and https frames, only where the engine's synchronous gate (`frame_decision`) allows them, which needs a grant for the frame's host from the same per-site machinery (App and Official may use every site, Unverified always ask, Lockdown hosts denied, Once one hour or until the tab closes, one prompt per site and session); nothing runs in private spaces, burner tabs, Lockdown profiles or Lockdown-level views: no extension page opens in a Lockdown profile, the pages already open close when a profile moves into Lockdown (`Runtime::level_changed`, called by every shell), and its messages and action clicks are refused. Messages travel only between the install's isolated worlds, its own pages and the shell's router (`tarn_ext::router`): the engine defines the transport only in that world or page and reports where a call arrived, so the sender (install, tab, frame, page) never comes from the message; a main frame's message counts only while the install holds a grant for the tab's host (and, where the engine reports the main frame's origin, only when it is the tab's) and a subframe's only while it holds one for the frame's own origin as the engine reported it, a plain `http` document's only when one of the install's site patterns also covers `http`, and no frame inside a page of a Lockdown host runs a script or sends a message; each message is JSON of at most 1 MiB, at most 200 per second per install and tab, malformed ones dropped; a reply counts only from a receiver the message went to; `tabs.query` shows the URL and title only of tabs whose host the install holds a grant for or that `activeTab` gave it; `tabs.sendMessage` reaches only such tabs; `tabs.create` opens web pages only through `nav_policy`, at most 3 in 10 s, never a private-network address (S10); `storage.local` holds JSON per profile and install, at most 5 MiB with keys up to 1 KiB, in memory for a private profile, and is deleted with the install. Static network rules (at most 5 files of 4 MiB, 30,000 rules) compile into one content rule list per install whose block and upgrade rules act only on top-level sites the install holds a grant for (every site only with the trusted switch, minus the hosts the user denied for the install and Lockdown hosts); the grant is the host's whatever the scheme, so they also act on a plain `http` page of a granted host, also for an install whose site patterns name only `https` (WebKit's `if-domain` names no scheme, and the `if-top-url` that could cannot share a list with it); a rule without `resourceTypes` leaves out top-level documents as in Chrome, and one for only main or only sub frames is kept to them (`load-context`); `excludedRequestDomains`, and `excludedInitiatorDomains` together with `initiatorDomains` or `domains`, are refused, because a content rule list can only lift every earlier rule; `allow` rules lift only the same install's rules, never Shield's, and no list is attached in private spaces, Lockdown profiles or Lockdown-level views. Extension pages are served from `tarn-extension:///`, the origin id the first 32 hex digits of SHA-256 of the profile's data-store seed and the install id, only from the install's read-only directory, whose tree hash is checked when the install loads (files are read on request; a change after that check is found at the next load, which turns the install off), with paths that leave it refused, with `script-src 'self'; frame-src 'self'; object-src 'none'`, so its frames are only its own pages or `about:` ones; web pages cannot load the scheme (no `web_accessible_resources`). The background page is started on its first event and closed after 30 s idle; one that does not get ready within 30 s is closed and its waiting callers get an error, and at most 64 messages wait for a page; a reply not given within 30 s ends with an error, at most 256 replies wait per install, and the background page's own calls do not keep it running. The tree hash is checked before every load and a mismatch turns the install off and drops its grants; Tarn extensions get none of the Bitwarden privileges whatever their source. On macOS and Windows the gate is asked in the navigation callback of every frame before the engine is answered, and its answer travels in the world's scripts (`tarn_ext::injections`); a document whose answer did not arrive first runs nothing, and on WebKit a view without a gate (the link peek) holds an empty answer for each of its documents, so no tab can let that document run, until it gets a gate or closes. WebKit (macOS) runs the scripts in a `WKContentWorld` named after the install with a script message handler added only to that world, and takes the frame from WebKit's own message (subframes by WebKit's private `_handle.frameID`; without it a subframe cannot send), each subframe document numbered on its own per install and holding a random value the install's world draws at document start and sends with every message (a message with another value from a frame that has a newer document is dropped); WebKit runs a reply in whatever document the frame shows, so the reply runs only where that value matches, never in the frame's next document, and a fragment navigation or a load that never commits keeps the document and its replies; extension pages are views of their own with the bootstrap in their main world, a handler that answers only the main frame of the install's origin and a `tarn-extension` scheme handler that serves only that origin. Chromium (macOS and Windows) does the same over the in-process DevTools channel only (S22): new-document scripts in an isolated world named after the install, a `Runtime.addBinding` limited to that world's name and taken out of its global before any content script runs, each context's frame and origin taken from DevTools' own `Runtime.executionContextCreated` (never from what a script sends), replies by `Runtime.evaluate` into those contexts. Frames in another process (cross-site iframes) are attached over the same channel (`Target.setAutoAttach` for iframes only, flattened, each waiting before its first document): a frame gets the same binding and scripts in its own session before it is resumed, an install added later gets them in every attached frame, and its contexts are known by session and context id, so its identity comes from the session DevTools reported, never from a script. The Runtime and Page domains are on in tabs of a profile with Tarn extensions, so a page there can tell that a DevTools client is attached (console argument previews); they stay on because without the Runtime domain no binding reaches a new document's context (checked: no `Runtime.bindingCalled` from any new document), and `Page.createIsolatedWorld` with a binding by context id reaches a frame only after its document has started, too late for `document_start` scripts. Checked at run time in a signed debug bundle on macOS (`engine/tests/tarn_extension_chromium.rs`, `app/tests/tarn_extension.rs`) and in WebKit (`engine/tests/tarn_extension.rs`): the isolated world, messages both ways, storage, the network rule only with a grant, no extension file loads from a web page, frame identity in same-site and cross-site frames after reloads and navigations, an install added after a cross-site frame was attached, nothing in a Lockdown view or profile, and an extension page framing only its own origin. The Runtime domain and auto-attach are turned off again in a view when its last install is removed, which detaches its frames' sessions; an install added later attaches them again. An install added (or added back) while a cross-site frame's navigation is in flight does not run in the document that navigation commits: DevTools holds the commands for that frame's session until the commit, after the document's contexts exist, so nothing runs or is heard there (it fails closed) and the frame's next document runs the install. Open on Chromium: not confirmed against Blink whether `Page.addScriptToEvaluateOnNewDocument` with a `worldName` creates that world with universal access; if it does, content scripts there can reach more than in a WebKit content world. `document_end` scripts start after a round trip to the shell, so they can run after the page's `load` event; extension pages register the scheme per request context on Windows only, where it is a standard, secure, display-isolated scheme in every process; the request context is the profile's, so its handler serves only the browser of the page view of that origin and refuses every other one. | +| S18 | High | Malicious or compromised extension | Per-profile install, per-site permission prompts, hash recorded, no silent updates, off in private mode by default, no access to internal pages or other profiles. | App and Official extensions get every site they list without a prompt while Settings › Extensions › "Allow extensions on every site" is on, which is the default (`Pref::ExtensionsEverySite`); Unverified ones always ask per site and Lockdown hosts stay denied. `tabs.create` from an App extension opens a web page as a normal tab through `nav_policy`, at the pop-up rate (3 in 10 s) and never with a private-network address as its URL (S10). Open: that tab is a user load, so a redirect of its URL to a private address is followed. With the global switch on, an update that asks for more sites is not held back. Only Safari web extensions bundled with apps in `/Applications` are offered (`engine::extensions`); nothing runs until the user turns an extension on for the current profile in Settings › Extensions, which lists every requested permission and site pattern. Turning it on grants all of them (no per-site prompts). Each profile has its own `WKWebExtensionController`: storage is keyed by the profile's own data-store UUID, also when it shares website data with another profile, the private space gets an in-memory controller with nothing enabled, Lockdown profiles and Lockdown-level views get no controller, and hosts with a Lockdown override are denied to every extension (checked: the content script stops answering), because a link into such a host keeps its view. An extension sees only the tabs of its own profile. Its `safari-web-extension://` origin (Safari's scheme, which Bitwarden's inline menu requires), which pages can see, is derived from the profile's data-store UUID, so it differs per user and profile; sites that probe for Bitwarden's Safari pages find it as they would in Safari. `windows.create` opens a window only for the extension's own pages (Bitwarden's unlock, passkey and edit popouts), at most four per extension, each side between 200 and 1000 points and the height kept on screen; the window's top-level navigations are held to the extension's own pages, because it has no navigation policy or Shield, and it closes when the extension is turned off or its data is removed. Only the extension that opened it sees it. Frames inside it are not restricted and it shows no origin chip, as with the extension's toolbar popup. Native messages and native ports are answered only for an app extension whose code signature is Bitwarden's (`com.bitwarden.desktop.safari`, signed by team `LTZ2PFU5D6`, or by Apple for the Mac App Store with that team's entitlement), checked when extensions are discovered, and only for the four Bitwarden uses (`copyToClipboard`, `readFromClipboard`, `sleep` with at most 16 pending, `showPopover`); a native port (`connectNative`) is accepted only for Bitwarden's app id, at most four per extension, closed with the extension, and answers only Bitwarden's biometrics questions as its Safari app extension does: Touch ID through LocalAuthentication, then the user key the Bitwarden desktop app keeps in the login keychain (`Bitwarden_biometric`, account `_user_biometric`), read off the main thread after Touch ID succeeded and handed only to that port; one Touch ID prompt at a time, naming the extension; once Bitwarden has run in a profile, until Tarn restarts, pages there (not at Lockdown) are told that passkeys and conditional mediation are available, as in Safari, but only in frames where `navigator.credentials.get` has been replaced again, by Bitwarden's page script or the page itself; WebKit says no without Apple's browser entitlement and refuses conditional requests at once, so in those frames such a refusal of a request with an abort signal stays pending until the page aborts it, as Safari's conditional UI does, and Bitwarden's answer is not cut short; elsewhere WebKit's own answers are returned, the availability one after waiting while the document still parses, at most 40 checks 50 ms apart; clipboard writes need the granted `clipboardWrite` permission and reads also need `clipboardRead` in the manifest, which Settings then lists. Deleting a profile removes its extensions' data through WebKit and then WebKit's folder for it, whose `State.plist` names each extension; "Delete everything" removes the data and restarts the profile's extensions. Tarn has no internal web pages to reach. Extensions can also be installed from a GitHub repository, the signed official catalog (own ed25519 key, domain-separated signature, rollback and 30-day freshness checks, a revoked set that only grows) and `.zip`/`.crx` files: archives are unpacked with strict name, size, depth and type checks into read-only per-install directories; storage is keyed by a random install id; the tree hash is recorded at install and checked before every load, `.appex` bundles included, and a mismatch turns the extension off and drops its site grants; trust labels and the Bitwarden privileges (native messages, clipboard read, passkey script, pop-out windows) follow the install source, never the manifest; unpacked extensions show a popup only after a toolbar click. Host access is per site: the grant-all loop is gone, WebKit's own URL prompt becomes a tab-modal Allow/Deny with Remember (Once lasts an hour), decisions are stored per install and profile, and App and Official sources may be switched to "Allow on every site", which turns off when an update asks for more sites (without effect while the global switch is on). Extension pages, workers and popups get the profile's private-network and HTTPS rule lists. `Tab` refuses `loadURL`, reload, back, forward and zoom without access to the tab's page. Updates are a new install with the same prompt, never automatic. Tarn extensions (`manifest_version` 3 with `browser_specific_settings.tarn.runtime` 1) run on Tarn's own runtime (`browser_core::tarn_ext`, contract `engine::tarn_ext`), the same on every engine: a package using any manifest key, permission (only `storage`, `activeTab`, `declarativeNetRequest`), content-script option or network-rule action outside the subset is refused at install with the key named, and `redirect`, `modifyHeaders` and `allowAllRequests` rules always are, as are a `priority` other than 1, a port in a site pattern and more than 1000 `regexFilter` rules; content scripts and their CSS run only in the install's isolated world `tarn-ext-`, only in http and https frames, only where the engine's synchronous gate (`frame_decision`) allows them, which needs a grant for the frame's host from the same per-site machinery (App and Official may use every site, Unverified always ask, Lockdown hosts denied, Once one hour or until the tab closes, one prompt per site and session); nothing runs in private spaces, burner tabs, Lockdown profiles or Lockdown-level views: no extension page opens in a Lockdown profile, the pages already open close when a profile moves into Lockdown (`Runtime::level_changed`, called by every shell), and its messages and action clicks are refused. Messages travel only between the install's isolated worlds, its own pages and the shell's router (`tarn_ext::router`): the engine defines the transport only in that world or page and reports where a call arrived, so the sender (install, tab, frame, page) never comes from the message; a main frame's message counts only while the install holds a grant for the tab's host (and, where the engine reports the main frame's origin, only when it is the tab's) and a subframe's only while it holds one for the frame's own origin as the engine reported it, a plain `http` document's only when one of the install's site patterns also covers `http`, and no frame inside a page of a Lockdown host runs a script or sends a message; each message is JSON of at most 1 MiB, at most 200 per second per install and tab, malformed ones dropped; a reply counts only from a receiver the message went to; `tabs.query` shows the URL and title only of tabs whose host the install holds a grant for or that `activeTab` gave it; `tabs.sendMessage` reaches only such tabs; `tabs.create` opens web pages only through `nav_policy`, at most 3 in 10 s, never a private-network address (S10); `storage.local` holds JSON per profile and install, at most 5 MiB with keys up to 1 KiB, in memory for a private profile, and is deleted with the install. Static network rules (at most 5 files of 4 MiB, 30,000 rules) compile into one content rule list per install whose block and upgrade rules act only on top-level sites the install holds a grant for (every site only with the trusted switch, minus the hosts the user denied for the install and Lockdown hosts); the grant is the host's whatever the scheme, so they also act on a plain `http` page of a granted host, also for an install whose site patterns name only `https` (WebKit's `if-domain` names no scheme, and the `if-top-url` that could cannot share a list with it); a rule without `resourceTypes` leaves out top-level documents as in Chrome, and one for only main or only sub frames is kept to them (`load-context`); `excludedRequestDomains`, and `excludedInitiatorDomains` together with `initiatorDomains` or `domains`, are refused, because a content rule list can only lift every earlier rule; `allow` rules lift only the same install's rules, never Shield's, and no list is attached in private spaces, Lockdown profiles or Lockdown-level views. Extension pages are served from `tarn-extension:///`, the origin id the first 32 hex digits of SHA-256 of the profile's data-store seed and the install id, only from the install's read-only directory, whose tree hash is checked when the install loads (files are read on request; a change after that check is found at the next load, which turns the install off), with paths that leave it refused, with `script-src 'self'; frame-src 'self'; object-src 'none'`, so its frames are only its own pages or `about:` ones; web pages cannot load the scheme (no `web_accessible_resources`). The background page is started on its first event and closed after 30 s idle; one that does not get ready within 30 s is closed and its waiting callers get an error, and at most 64 messages wait for a page; a reply not given within 30 s ends with an error, at most 256 replies wait per install, and the background page's own calls do not keep it running. The tree hash is checked before every load and a mismatch turns the install off and drops its grants; Tarn extensions get none of the Bitwarden privileges whatever their source. On macOS and Windows the gate is asked in the navigation callback of every frame before the engine is answered, and its answer travels in the world's scripts (`tarn_ext::injections`); a document whose answer did not arrive first runs nothing, and on WebKit a view without a gate (the link peek) holds an empty answer for each of its documents, so no tab can let that document run, until it gets a gate or closes. WebKit (macOS) runs the scripts in a `WKContentWorld` named after the install with a script message handler added only to that world, and takes the frame from WebKit's own message (subframes by WebKit's private `_handle.frameID`; without it a subframe cannot send), each subframe document numbered on its own per install and holding a random value the install's world draws at document start and sends with every message (a message with another value from a frame that has a newer document is dropped); WebKit runs a reply in whatever document the frame shows, so the reply runs only where that value matches, never in the frame's next document, and a fragment navigation or a load that never commits keeps the document and its replies; extension pages are views of their own with the bootstrap in their main world, a handler that answers only the main frame of the install's origin and a `tarn-extension` scheme handler that serves only that origin. Chromium (macOS and Windows) does the same over the in-process DevTools channel only (S22): new-document scripts in an isolated world named after the install, a `Runtime.addBinding` limited to that world's name and taken out of its global before any content script runs, each context's frame and origin taken from DevTools' own `Runtime.executionContextCreated` (never from what a script sends), replies by `Runtime.evaluate` into those contexts. Frames in another process (cross-site iframes) are attached over the same channel (`Target.setAutoAttach` for iframes only, flattened, each waiting before its first document): a frame gets the same binding and scripts in its own session before it is resumed, an install added later gets them in every attached frame, and its contexts are known by session and context id, so its identity comes from the session DevTools reported, never from a script. The Runtime and Page domains are on in tabs of a profile with Tarn extensions, so a page there can tell that a DevTools client is attached (console argument previews); they stay on because without the Runtime domain no binding reaches a new document's context (checked: no `Runtime.bindingCalled` from any new document), and `Page.createIsolatedWorld` with a binding by context id reaches a frame only after its document has started, too late for `document_start` scripts. Checked at run time in a signed debug bundle on macOS (`engine/tests/tarn_extension_chromium.rs`, `app/tests/tarn_extension.rs`) and in WebKit (`engine/tests/tarn_extension.rs`): the isolated world, messages both ways, storage, the network rule only with a grant, no extension file loads from a web page, frame identity in same-site and cross-site frames after reloads and navigations, an install added after a cross-site frame was attached, nothing in a Lockdown view or profile, and an extension page framing only its own origin. The Runtime domain and auto-attach are turned off again in a view when its last install is removed, which detaches its frames' sessions; an install added later attaches them again. An install added (or added back) while a cross-site frame's navigation is in flight does not run in the document that navigation commits: DevTools holds the commands for that frame's session until the commit, after the document's contexts exist, so nothing runs or is heard there (it fails closed) and the frame's next document runs the install. Open on Chromium: not confirmed against Blink whether `Page.addScriptToEvaluateOnNewDocument` with a `worldName` creates that world with universal access; if it does, content scripts there can reach more than in a WebKit content world. `document_end` scripts start after a round trip to the shell, so they can run after the page's `load` event; extension pages register the scheme per request context on Windows only, where it is a standard, secure, display-isolated scheme in every process; the request context is the profile's, so its handler serves only the browser of the page view of that origin and refuses every other one. Store install link (new boundary: a web page leads to an install prompt): only a main-frame navigation the user started (a typed or other shell load that is not a link or pop-up the shell loads for a page, or a link click with a user gesture; `nav_policy::store_link_asks`) to exactly `https://extensions.tarnbrowser.com/install/` (`engine::tarn_ext::store_install`: https, that host, no port, no user info, a valid catalog id, query and fragment ignored) is cancelled before any request; the page passes nothing but the id and gets no channel into the browser. The link itself makes no request: if Tarn already holds a fresh (at most 30 days old) verified copy of the signed catalog, Settings › Extensions shows a confirmation built only from that entry (name, description, version, permissions, optional permissions, sites; `extensions::install::store_step`, `store_sheet`), otherwise a notice points to Settings › Extensions, where the user can load the catalog, and nothing else happens. Requests start only when the user presses Install there: Tarn first checks everything again (`store_confirm`: the same entry in a fresh catalog, not revoked or installed, no install in progress, and `Core::store_link_allowed` for the tab), then downloads, verifies and unpacks the package as for Settings › Extensions › Official; a package whose manifest stays within that entry (`vet`, as always) installs without a second prompt. A page cannot swap what the user confirms: a new store link replaces the sheet under a new token (`install::StoreToken`: a sequence number, the entry's id and SHA-256), the Install button carries the token of the sheet it was drawn for and `StoreSheet::take` refuses any other, and Install clicks within 700 ms of a sheet appearing or being replaced are ignored (`STORE_CONFIRM_DELAY`; on macOS and Windows also while the window layout is not stable, as for the S5 hand-off rule); closing Settings › Extensions drops an unanswered sheet. An unknown, revoked or already installed id or an install in progress gets a notice, and nothing is offered in a private space, a burner tab, a Lockdown profile, from a page at Lockdown or while the store's host is at Lockdown. Every client takes at most one store link per 10 s and ignores the rest without a sheet (`Core::admit_store_link`). Redirects into the address, subframes and script navigations without a gesture load normally. A script that navigates while handling the user's click counts as the user's, as for pop-ups. WebKit on macOS tells a user's click from a script's `a.click()` only through WebKit's private `_isUserInitiated`, and redirects through `_isRedirect`; where they are missing only shell loads ask. Chromium uses CEF's user gesture, Android WebView `hasGesture`, WebKitGTK `is_user_gesture`. iOS uses no private WebKit API and has no public user-gesture or redirect flag: a shell load or any main-frame `linkActivated` navigation asks, so a page's own script-started link click (and a redirect after a link click) can raise the confirmation there, at most once per 10 s; it requests and installs nothing without the user's confirmation. Open: on Linux the user's own click on an install link inside a frame also opens the consent (WebKitGTK does not say which frame a navigation targets). | | S5 | High | Origin spoofing; a sidebar-only UI hides the URL | Origin chip always visible; registrable domain emphasised; punycode for mixed-script names. Prompts and dialogs show the origin and are tab-modal. | Origin chip shows the host as parsed by `url` (IDNA to punycode); a `blob:` page shows the host of the URL it wraps and a page without a host (an opener-filled `about:blank`, `data:`) shows only its scheme (`about:blank`, `data:`), as does its tab title when the page set none, so the chip is empty only when no page is loaded. While a navigation the page started is pending, WebKit's `URL` already names its target over the old content; `WebView::url` then returns the committed URL (`Delegate::shown_url`; `about:blank` for a pop-up before its first commit), so chip, peek header and site settings keep naming the page on screen. Only a server redirect (WebKit's private `_isRedirect`) of the navigation the shell itself started with `load` continues the user's load (`Delegate::user_load`); a navigation the old document starts while that load is pending, and its redirects, are the page's own for S10. Without the selector no hop counts as the user's. For the chip, `user_navigation` still covers the time until the user's load commits or any load fails. The link peek header uses the chip's label (`toolbar::site_of`). Dialogs, permission and sign-in requests are tab-modal cards naming the origin (shortened from the left so the registrable domain stays visible) and the embedding page for frames; a permission card's Allow and Remember ignore clicks for 700 ms after the card becomes visible, a banner above it appears or leaves, or the window becomes active (which also covers leaving element fullscreen). All guarded controls (this one, S6's "Open", S25's "Visit Anyway", a notice's offer) share one timer (`Browser::layout_stable_since`), restarted when any of them appears or changes in the active tab, a banner appears or leaves, the tab or overlay changes or the window becomes active. | A page-requested hand-off to another app names the requesting site, is rate-limited like other prompts, is not replaced while shown, ignores clicks for 700 ms after it appears and closes when the user switches tabs. A Shift-click link peek follows the pop-up rules and their rate limit. | S6 | High | Dangerous schemes and untrusted URL sources | Allowlist `http`, `https`, `about:blank`, `blob`. `data:` not at top level. `file:` only by explicit user action. `javascript:` rejected in the command bar and on paste. External schemes prompt each time. URLs from other apps, drops and sync pass the same policy. | `nav_policy::decide` with table test; applied to typed input, command-line URLs, restored tabs and session snapshots, main-frame navigations, redirects and popups. A page's external-scheme request shows a banner naming the origin of the frame that started it ("A page" when opaque or while a main-frame load is in flight, so a server redirect is never credited to the page or frame that linked to it), only in its own tab, until that tab's next commit or close; while it shows, further requests are dropped, and "Open" ignores clicks for 700 ms after it, or any banner above it, appears, and again when the window becomes active. Links other apps send (the default-browser case, `shared::open_urls` through GPUI's `on_open_urls`) pass `decide(ExternalApp)`, at most 10 in 10 s across the app (the rest are dropped with a toast), and load as a page's link (`WebView::load_link` with no opener), so S10 refuses a local target or any redirect hop into the local network with its usual notice; typing the address opens it. A loopback link (`localhost`, 127.0.0.0/8, `::1`) opens as typed while Settings › Privacy › Open localhost links from other apps is on (the default), since developers open local servers from terminals and editors; the accepted risk is that a link from a remote sender (a mail) can then reach a service on this computer, as a typed address could. Off, it gets the notice. Other local addresses always get it. The notice offers Open Anyway, which loads the address as the user's own navigation. Chromium tabs do the same: their `load_link` sets no shell mark, also for a load held until the view is ready, so `on_before_browse` credits the page (a Chromium integration test is not written yet); such a load is not a user's, so it does not bridge WebKit's cookies first and the site may open signed out in Chromium. Open: public names that resolve to private addresses (`nip.io`-style) are not recognised. | | S19 | High | Sync storage is read or tampered with | Client-side authenticated encryption; remote data validated as untrusted input; secrets and cookies never synced. | Not built. | @@ -59,7 +59,7 @@ desktop). None of the three has run on a real device or desktop, and none is rel | S10 | `shield::rules` private-network content rule plus `nav_policy` for navigations and popups (judged against the opener). Checked in M2 and on the integration build (public origin on the Mac's global IPv6 address) and again in M4 from `https://127.0.0.1.nip.io` (HTTPS image, `fetch`, link, script, popup and popup redirect blocked; `mobile/evidence/m4/`). WebSocket requests to local addresses were not tested. | `shouldInterceptRequest` with `engine::content_rules`; service-worker requests are checked at Standard with no top page, as third-party requests (built-in rules and filter lists). Checked: local subresources from a public page blocked. **Gap:** WebSocket requests are not visible to WebView clients, so a public page can open a WebSocket to a local address. Before commit, subresources are judged against the old and the new page. | `UserContentFilterStore` with the same rules, plus navigation checks. Checked. | | S11 | `WKDownload` into `Documents/Downloads` (visible in Files); sanitised names; never opened; at most 10 per tab in 10 s. No quarantine attribute exists on iOS. The private space saves to the same folder and its files stay after the space closes; only Android deletes them with the session. Checked. | Saved to `files/Downloads` (private space: `private//Downloads`, deleted with the session); sanitised names; never opened; 10 per tab in 10 s. No quarantine attribute. Checked. | Saved to `~/Downloads` with `user.xdg.origin.url`, mode `0644`, never opened; sanitised names including bidi controls. The private space saves to the same folder and its files stay after the space closes. Checked. | | S12 | The iOS app sandbox and WebKit's own content processes. No entitlements beyond the defaults; the default-browser entitlement is not requested. | The Android app sandbox; WebView renders in its own isolated process. The private space runs in a separate `:private` process. | No app sandbox: the shell runs as the user (distribution packages; no Flatpak, by decision). The app does not turn off WebKitGTK's bubblewrap sandbox for web processes, but the tests in Docker do (`WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1`), so it has not run with the sandbox on. | -| S18 | Tarn extensions only (no app or Safari web extensions), with the same runtime, grants and limits as macOS (`browser_core::tarn_ext::runtime`); content scripts run in a `WKContentWorld` per install and extension pages are views of their own whose frames load only their own extension origin or blank documents. | Tarn extensions only, with the same runtime, grants and limits as macOS (`browser_core::tarn_ext::runtime`); content scripts run in a `JavaScriptExecutionWorld` per install whose message listener is bound to that world. WebView gives documents of a custom scheme an opaque origin, so extension pages get their CSP with `'self'` replaced by `tarn-extension:`; the page view answers requests only for its own extension origin (any other `tarn-extension://` origin gets 403), and inline scripts and `eval` stay blocked. WebView refuses an origin rule for the custom scheme, so the extension page's message listener and document-start script are registered for every origin, but only on the dedicated extension page view (`ExtensionPage`, never a tab's view): its frames stay on its own extension origin or blank documents (other navigations are cancelled, and web documents in any of its frames are answered with an empty 403), the script sets itself up only in the top document of that origin, and the listener drops messages from subframes or from any other URL. The frame gate is asked at document start through a round trip to the shell thread (about 40 ms in the emulator), so `document_start` scripts run slightly late; a document whose answer has not arrived runs nothing. | Tarn extensions only, with the same runtime, grants and limits as macOS (`browser_core::tarn_ext::runtime`); content scripts run in a WebKitGTK script world per install and extension pages are views of their own whose bridge script runs only in their top frame. | +| S18 | Tarn extensions only (no app or Safari web extensions), with the same runtime, grants and limits as macOS (`browser_core::tarn_ext::runtime`); content scripts run in a `WKContentWorld` per install and extension pages are views of their own whose frames load only their own extension origin or blank documents. | Tarn extensions only, with the same runtime, grants and limits as macOS (`browser_core::tarn_ext::runtime`); content scripts run in a `JavaScriptExecutionWorld` per install whose message listener is bound to that world. WebView gives documents of a custom scheme an opaque origin, so extension pages get their CSP with `'self'` replaced by `tarn-extension:`; the page view answers requests only for its own extension origin (any other `tarn-extension://` origin gets 403), and inline scripts and `eval` stay blocked. WebView refuses an origin rule for the custom scheme, so the extension page's message listener and document-start script are registered for every origin, but only on the dedicated extension page view (`ExtensionPage`, never a tab's view): its frames stay on its own extension origin or blank documents (other navigations are cancelled, and web documents in any of its frames are answered with an empty 403), the script sets itself up only in the top document of that origin, and the listener drops messages from subframes or from any other URL. The frame gate is asked at document start through a round trip to the shell thread (about 40 ms in the emulator), so `document_start` scripts run slightly late; a document whose answer has not arrived runs nothing. | Tarn extensions only, with the same runtime, grants and limits as macOS (`browser_core::tarn_ext::runtime`); content scripts run in a WebKitGTK script world per install and extension pages are views of their own whose bridge script runs only in their top frame. The store install link also opens the consent for the user's own click inside a frame, since WebKitGTK names no frame for a navigation (`docs/nsh-plan.md`). | **Page scripts on Android (S1, S14).** Contract v3's reader, page-text, Find in Tabs text and element-picker scripts run in the page's own world on Android, which has no isolated world without a JavaScript bridge. A diff --git a/linux/src/browser.rs b/linux/src/browser.rs index 464307e1..faa89f8d 100644 --- a/linux/src/browser.rs +++ b/linux/src/browser.rs @@ -35,6 +35,7 @@ pub const ZOOM_STEPS: [f64; 9] = [0.5, 0.67, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 2.0] #[derive(Clone, Debug, Default)] pub struct Page { pub url: String, + pub link: bool, pub title: String, pub can_back: bool, pub can_forward: bool, @@ -325,6 +326,7 @@ impl Browser { let level = self.level_for(key, url); let page = self.pages.entry(key).or_default(); page.load = Some((url.to_owned(), seq)); + page.link = false; page.loading = true; page.level = level; page.error = None; @@ -718,11 +720,18 @@ impl Browser { self.outbox.push((key, "answer", prompt.answer(accept, Some(text.to_owned()), Some(user.to_owned()), Some(password.to_owned())))); } + pub fn store_link_allowed(&self, key: TabKey) -> bool { + let page = self.pages.get(&key).and_then(|p| Url::parse(&p.url).ok()); + let current = self.model.current_space().filter(|s| !s.private).map(|s| s.space.profile_id); + self.model.profile_of(&self.core, key).filter(|p| current == Some(*p)).is_some_and(|p| self.core.store_link_allowed(key.private, p, page.as_ref())) + } + pub fn on_event(&mut self, key: TabKey, name: &str, data: &Value) { let text = |k: &str| data[k].as_str().unwrap_or_default().to_owned(); match name { "committed" | "finished" => self.on_page(key, name == "finished", data), "started" | "stopped" => self.pages.entry(key).or_default().loading = name == "started", + browser_core::extensions::STORE_EVENT => self.pages.entry(key).or_default().loading = false, "title" => { if let Some(page) = self.pages.get_mut(&key) { page.title = text("title"); @@ -757,8 +766,12 @@ impl Browser { } "external" => self.notice = Some(Notice::External { url: text("url"), origin: text("origin") }), "popup" => { - if !(data["link"].as_bool() == Some(true) && self.open_routed(&text("url"))) { - self.new_tab(&text("url")); + let url = text("url"); + if !(data["link"].as_bool() == Some(true) && self.open_routed(&url)) { + self.new_tab(&url); + } + if let Some(page) = self.model.active.and_then(|k| self.pages.get_mut(&k)).filter(|p| p.load.as_ref().is_some_and(|(u, _)| *u == url)) { + page.link = true; } } "article" | "pageText" | "textFound" | "picked" => self.on_script_event(key, name, data), diff --git a/linux/src/browser/tests.rs b/linux/src/browser/tests.rs index cbc6a232..e741cea5 100644 --- a/linux/src/browser/tests.rs +++ b/linux/src/browser/tests.rs @@ -38,6 +38,37 @@ fn typed_addresses_load_with_a_new_sequence_and_the_site_level() { assert_eq!(b.pages[&key].level, ShieldLevel::Standard); } +#[test] +fn store_links_install_only_from_a_profile_tab_outside_lockdown() { + let (_dir, mut b) = browser(); + let key = active(&b); + b.on_event(key, "committed", &json!({ "url": "https://example.com/", "title": "" })); + assert!(b.store_link_allowed(key)); + b.set_site_level(Some(ShieldLevel::Lockdown)); + assert!(!b.store_link_allowed(key), "from a Lockdown site"); + b.set_site_level(None); + assert!(b.store_link_allowed(key)); + b.navigate("https://extensions.tarnbrowser.com/install/helper"); + assert!(b.pages[&key].loading); + b.on_event(key, browser_core::extensions::STORE_EVENT, &json!({ "id": "helper" })); + assert!(!b.pages[&key].loading, "the cancelled load stops"); + b.on_event(key, "popup", &json!({ "url": "https://extensions.tarnbrowser.com/install/helper" })); + let popup = active(&b); + assert_ne!(popup, key); + assert!(b.pages[&popup].link, "a page's pop-up loads as the page's link, not as the user's own load"); + let view = crate::snapshot::snapshot(&b, true).views.into_iter().find(|v| v.key == popup).unwrap(); + assert!(view.link); + b.navigate("https://extensions.tarnbrowser.com/install/helper"); + assert!(!b.pages[&popup].link, "the user's own load in that tab is theirs"); + b.activate(key); + b.private_space(); + let private = active(&b); + assert!(!b.store_link_allowed(private), "never from the private space"); + assert!(!b.store_link_allowed(key), "only from the space shown"); + b.open_burner(); + assert!(!b.store_link_allowed(active(&b)), "never from a burner tab"); +} + #[test] fn tabs_close_and_reopen_in_their_space() { let (_dir, mut b) = browser(); diff --git a/linux/src/snapshot.rs b/linux/src/snapshot.rs index bb19ef5d..0cf581f8 100644 --- a/linux/src/snapshot.rs +++ b/linux/src/snapshot.rs @@ -70,6 +70,7 @@ pub struct ViewItem { pub zaps: Value, pub sort_downloads: bool, pub load: Option<(String, u64)>, + pub link: bool, pub active: bool, /// Its place in the split on screen. pub pane: Option, @@ -270,6 +271,7 @@ pub fn views(b: &Browser, shown: bool) -> Vec { zaps, sort_downloads, load: page.and_then(|p| p.load.clone()), + link: page.is_some_and(|p| p.link), active: shown && (b.model.active == Some(key) || panes.contains(&key)), pane: panes.iter().position(|k| *k == key).filter(|_| shown), } diff --git a/linux/src/ui.rs b/linux/src/ui.rs index f46be652..87427b03 100644 --- a/linux/src/ui.rs +++ b/linux/src/ui.rs @@ -315,9 +315,12 @@ fn web_views(ui: Ui) -> View { .prop("themeStyles", move || item.with(|v| v.theme_styles.clone())) .prop("zaps", move || item.with(|v| v.zaps.clone())) .prop("sortDownloads", move || JsonValue::from(item.with(|v| v.sort_downloads))) - .prop("load", move || item.with(|v| v.load.as_ref().map_or(JsonValue::Null, |(u, s)| json!({ "url": u, "seq": s })))) + .prop("load", move || item.with(|v| v.load.as_ref().map_or(JsonValue::Null, |(u, s)| json!({ "url": u, "seq": s, "link": v.link })))) .prop("active", move || JsonValue::from(item.with(|v| v.active))) .on_native_event(move |event: &NativeEvent| { + if &*event.name == browser_core::extensions::STORE_EVENT { + extensions::store_link(ui, key, event.data["id"].as_str().unwrap_or_default()); + } if &*event.name == "iconData" { return icon_data(ui, key, event.data.clone()); } @@ -1865,6 +1868,13 @@ fn new_ui(row: SavedWindow) -> Ui { untracked(|| act(ui, |_| {})); } }); + let extensions_open = std::cell::Cell::new(false); + effect(move || { + let open = ui.panel.get() == Panel::Settings && ui.ext_pane.get(); + if extensions_open.replace(open) && !open { + untracked(tarn_nsh_shared::extensions::close_store_sheet); + } + }); let shown_space = std::cell::Cell::new(None); effect(move || { let space = ui.snap.with(|s| s.space); diff --git a/linux/src/ui/extensions.rs b/linux/src/ui/extensions.rs index e65bec21..9f30d7fd 100644 --- a/linux/src/ui/extensions.rs +++ b/linux/src/ui/extensions.rs @@ -3,12 +3,14 @@ use std::rc::Rc; use browser_core::Core; use browser_core::prompts::Prompt; +use browser_core::tabs::TabKey; use futures_util::StreamExt; use nsh_core::JsonValue; use nsh_core::prelude::*; use tarn_nsh_shared::controls::{secure_button, secure_surface}; -use super::{Ui, WINDOWS, act, read}; +use super::{Panel, Ui, WINDOWS, act, read}; +use crate::browser::Notice; use crate::controls::{body, card, pill, small}; use crate::data::Data; use crate::extensions::{self, Note, popup}; @@ -182,6 +184,29 @@ impl tarn_nsh_shared::extensions::Host for Installs { fn notice(self) -> Option { None } + fn store_link_allowed(self, tab: TabKey) -> bool { + read(self.0, |b| b.store_link_allowed(tab)) == Some(true) + } + fn open_link(self, url: &'static str) { + self.0.panel.set(Panel::None); + act(self.0, |b| { + b.new_tab(url); + }); + } +} + +pub(super) fn store_link(ui: Ui, key: TabKey, id: &str) { + if read(ui, |b| b.core.admit_store_link(std::time::Instant::now())) != Some(true) { + return; + } + match tarn_nsh_shared::extensions::store_link(Installs(ui), key, id) { + Ok(()) => { + ui.ext_pane.set(true); + ui.panel.set(Panel::Settings); + act(ui, |_| {}); + } + Err(why) => act(ui, |b| b.notice = Some(Notice::Message(why))), + } } pub(super) fn pane(ui: Ui) -> AnyElement { diff --git a/linux/src/webview/display_tests.rs b/linux/src/webview/display_tests.rs index 341b76ee..b670ff75 100644 --- a/linux/src/webview/display_tests.rs +++ b/linux/src/webview/display_tests.rs @@ -90,6 +90,52 @@ fn contract_v3_scripts_run_in_the_tarn_world_and_styles_and_zaps_apply() { eprintln!("v3 scripts, styles and zaps verified on {}", web.uri().unwrap_or_default()); } +#[test] +#[ignore = "needs a display and WebKitGTK; run scripts/test-display.sh"] +fn only_the_users_own_navigation_to_a_store_link_asks_to_install() { + gtk::init().expect("a display"); + let state = view(ShieldLevel::Standard, "burner:0123456789abcdef0123456789abcdef"); + let web = open(&state); + let block: Rc>> = Rc::default(); + let slot = block.clone(); + let rules = r#"[{"trigger":{"url-filter":"^https://extension\\.tarnbrowser\\.com/"},"action":{"type":"block"}}]"#; + filters::compile_one("store-block.test".into(), rules.into(), move |f| *slot.borrow_mut() = Some(f)); + assert!(spin_until(|| block.borrow().is_some(), 20), "the test's rule compiled"); + state.content.borrow().as_ref().unwrap().add_filter(block.borrow().as_ref().unwrap()); + let link = "https://extensions.tarnbrowser.com/install/helper"; + let decided = |state: &State| state.events.borrow().iter().any(|(n, d)| n == "decided" && d["url"].as_str().is_some_and(|u| u.starts_with(link))); + for script in [ + format!("location.href = '{link}'"), + format!("const a = document.createElement('a'); a.href = '{link}/'; document.body.append(a); a.click()"), + format!("const f = document.createElement('iframe'); f.src = '{link}'; document.body.append(f)"), + ] { + state.events.borrow_mut().clear(); + web.load_html(&format!(""), Some("http://page.test/")); + assert!(spin_until(|| decided(&state), 20), "{script}: the navigation reached the policy: {:?}", state.events.borrow()); + spin_until(|| false, 1); + assert!(event(&state, "committed").is_some(), "{script}: the page loaded"); + assert!(event(&state, engine::tarn_ext::STORE_EVENT).is_none(), "{script}: {:?}", state.events.borrow()); + if !script.contains("iframe") { + let blocked = event(&state, "failed").is_some_and(|d| d["url"].as_str().is_some_and(|u| u.starts_with(link))); + assert!(blocked, "{script}: the test's rule stopped the request: {:?}", state.events.borrow()); + } + } + state.events.borrow_mut().clear(); + *state.load.borrow_mut() = Some((link.to_owned(), 1)); + state.load_link.set(true); + load(&state, None); + assert!(spin_until(|| decided(&state), 20), "the pop-up's load reached the policy"); + spin_until(|| false, 1); + assert!(event(&state, engine::tarn_ext::STORE_EVENT).is_none(), "a page's pop-up tab never asks: {:?}", state.events.borrow()); + web.load_html(PAGE, Some("http://page.test/")); + assert!(spin_until(|| event(&state, "finished").is_some(), 30), "the page loaded"); + *state.load.borrow_mut() = Some((link.to_owned(), 2)); + state.load_link.set(false); + load(&state, None); + assert!(spin_until(|| event(&state, engine::tarn_ext::STORE_EVENT).is_some(), 20), "the user's own load asks"); + assert_eq!(event(&state, engine::tarn_ext::STORE_EVENT).unwrap(), json!({ "id": "helper" })); +} + #[test] #[ignore = "needs a display and WebKitGTK; run scripts/test-display.sh"] fn nothing_runs_or_applies_under_lockdown() { diff --git a/linux/src/webview/mod.rs b/linux/src/webview/mod.rs index c0fb36b4..36e78e1a 100644 --- a/linux/src/webview/mod.rs +++ b/linux/src/webview/mod.rs @@ -60,6 +60,8 @@ struct State { load: RefCell>, loaded_seq: Cell>, shell_url: RefCell>, + link_url: RefCell>, + load_link: Cell, upgraded: RefCell>, user_step: Cell, posted: RefCell>, @@ -322,6 +324,7 @@ fn load(state: &Rc, current: Option) { let target = match wanted { Some((url, seq)) if state.loaded_seq.get() != Some(seq) => { state.loaded_seq.set(Some(seq)); + *state.link_url.borrow_mut() = state.load_link.get().then(|| url.clone()); Some(url) } _ => current, @@ -402,6 +405,8 @@ fn decide_navigation(state: &Rc, web: &WebView, decision: &webkit6::Polic decision.ignore(); return true; }; + #[cfg(test)] + state.events.borrow_mut().push(("decided".to_owned(), json!({ "url": uri }))); let nav_type = action.navigation_type(); let gesture = action.is_user_gesture(); let link = matches!(nav_type, NavigationType::LinkClicked | NavigationType::FormSubmitted); @@ -417,6 +422,20 @@ fn decide_navigation(state: &Rc, web: &WebView, decision: &webkit6::Polic decision.ignore(); return true; }; + let page_link = state.link_url.borrow_mut().take_if(|s| *s == uri).is_some(); + let store = engine::nav_policy::StoreNav { + redirect: action.is_redirect(), + shell_load: from_shell, + page_link, + clicked: nav_type == NavigationType::LinkClicked && gesture, + }; + if engine::nav_policy::store_link_asks(store) + && let Some(id) = engine::tarn_ext::store_install(&url) + { + state.emit(engine::tarn_ext::STORE_EVENT, json!({ "id": id })); + decision.ignore(); + return true; + } let page = state.page.borrow().clone(); let nav = Navigation { url: &url, @@ -850,6 +869,7 @@ impl NativeComponent for TarnWebView { "sortDownloads" => return state.sort_downloads.set(value.as_bool().unwrap_or(false)), "load" => { *state.load.borrow_mut() = value["url"].as_str().zip(value["seq"].as_u64()).map(|(u, s)| (u.to_owned(), s)); + state.load_link.set(value["link"].as_bool() == Some(true)); } "active" => { let active = value.as_bool().unwrap_or(false); diff --git a/mobile/android/host/src/main/java/dev/tarn/android/Native.java b/mobile/android/host/src/main/java/dev/tarn/android/Native.java index 2c78d1ed..4db70194 100644 --- a/mobile/android/host/src/main/java/dev/tarn/android/Native.java +++ b/mobile/android/host/src/main/java/dev/tarn/android/Native.java @@ -66,6 +66,8 @@ static int stricter(int a, int b) { static native String downloadName(String suggested); + static native String storeInstall(String url); + static native boolean mayAskCredentials(String challenge, String page, int failures); static native int popupBurst(); diff --git a/mobile/android/host/src/main/java/dev/tarn/android/TarnWebView.java b/mobile/android/host/src/main/java/dev/tarn/android/TarnWebView.java index cf6c8da4..4dd5afc7 100644 --- a/mobile/android/host/src/main/java/dev/tarn/android/TarnWebView.java +++ b/mobile/android/host/src/main/java/dev/tarn/android/TarnWebView.java @@ -606,8 +606,16 @@ private boolean rebuildKeeping(int keptLevel) { return true; } + private boolean storeLink(String target) { + String id = Native.storeInstall(target); + if (id == null) return false; + emit("storeInstall", "id", id); + return true; + } + private void shellLoad(String target, String opener) { refusedUrl = null; + if (opener == null && storeLink(target)) return; if (!passesNavPolicy(target, opener == null ? Native.TYPED : Native.POPUP, opener)) return; int site = levelFor(target); if (opener != null && isWeb(target) && Native.intoPrivateNetwork(target, opener, false, site)) { @@ -922,7 +930,9 @@ private final class Client extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (!request.isForMainFrame()) return false; - return !pageNavigation(request.getUrl().toString(), request.isRedirect()); + String target = request.getUrl().toString(); + if (!request.isRedirect() && request.hasGesture() && storeLink(target)) return true; + return !pageNavigation(target, request.isRedirect()); } @Override diff --git a/mobile/android/rust/src/lib.rs b/mobile/android/rust/src/lib.rs index 5ed9847c..b39f55c9 100644 --- a/mobile/android/rust/src/lib.rs +++ b/mobile/android/rust/src/lib.rs @@ -115,6 +115,12 @@ pub extern "system" fn Java_dev_tarn_android_Native_downloadName(mut env: JNIEnv env.new_string(name).map_or(std::ptr::null_mut(), |s| s.into_raw()) } +#[unsafe(no_mangle)] +pub extern "system" fn Java_dev_tarn_android_Native_storeInstall(mut env: JNIEnv, _: JClass, url: JString) -> jstring { + let id = string(&mut env, &url).and_then(|u| url::Url::parse(&u).ok()).and_then(|u| engine::tarn_ext::store_install(&u)); + java_string(&mut env, id) +} + fn java_string(env: &mut JNIEnv, value: Option) -> jstring { value.and_then(|v| env.new_string(v).ok()).map_or(std::ptr::null_mut(), |s| s.into_raw()) } diff --git a/mobile/app/src/events.rs b/mobile/app/src/events.rs index b2e06bf3..8bcaa715 100644 --- a/mobile/app/src/events.rs +++ b/mobile/app/src/events.rs @@ -43,7 +43,7 @@ impl Shell { } match name { "committed" | "finished" => return self.page_event(key, name == "committed", data, now), - "started" | "stopped" => { + "started" | "stopped" | browser_core::extensions::STORE_EVENT => { if let Some(page) = self.pages.get_mut(&key) { page.loading = name == "started"; } diff --git a/mobile/app/src/extensions.rs b/mobile/app/src/extensions.rs index a7742ebd..6daa5e69 100644 --- a/mobile/app/src/extensions.rs +++ b/mobile/app/src/extensions.rs @@ -78,6 +78,12 @@ impl Shell { self.model.profile().filter(|(private, _)| !private).map(|(_, id)| id) } + pub fn store_link_allowed(&self, key: TabKey) -> bool { + let page = self.pages.get(&key).and_then(|p| p.committed.as_deref()).and_then(|u| Url::parse(u).ok()); + let profile = self.model.profile_of(&self.core, key).filter(|p| self.extension_profile() == Some(*p)); + profile.is_some_and(|p| self.core.store_link_allowed(key.private, p, page.as_ref())) + } + fn policy(&self, profile: Id) -> Policy { self.core.extension_policy(profile, every_site_setting(self.core.disk.setting(EVERY_SITE_SETTING).ok().flatten().as_deref())) } diff --git a/mobile/app/src/shell.rs b/mobile/app/src/shell.rs index 67b81b8e..0108609c 100644 --- a/mobile/app/src/shell.rs +++ b/mobile/app/src/shell.rs @@ -774,7 +774,8 @@ impl Shell { self.notice = Some("A burner tab does not open pop-ups.".into()); return; } - if let Some(ix) = Url::parse(url).ok().filter(|_| link).and_then(|u| self.routed_space(&u)) { + let fresh = Url::parse(url).ok().filter(|u| link && browser_core::extensions::store_install(u).is_none()); + if let Some(ix) = fresh.and_then(|u| self.routed_space(&u)) { self.switch_space(ix); self.new_tab(Some(url)); return; diff --git a/mobile/app/src/ui/extensions.rs b/mobile/app/src/ui/extensions.rs index 98ca4e93..53dd86cb 100644 --- a/mobile/app/src/ui/extensions.rs +++ b/mobile/app/src/ui/extensions.rs @@ -5,6 +5,7 @@ use std::rc::Rc; use std::time::Instant; use browser_core::extensions::install::access_title; +use browser_core::tabs::TabKey; use engine::tarn_ext::PageKind; use nsh_base::button; use nsh_core::prelude::*; @@ -82,6 +83,29 @@ impl Host for Exts { fn notice(self) -> Option { (!ext::worlds_supported()).then(|| NO_WORLDS.to_owned()) } + fn store_link_allowed(self, tab: TabKey) -> bool { + self.0.read(|s| s.store_link_allowed(tab)) + } + fn open_link(self, url: &'static str) { + self.0.act(|s| { + s.new_tab(Some(url)); + Vec::new() + }); + self.0.show(Screen::Browse); + } +} + +pub(super) fn store_link(ui: Ui, key: TabKey, id: &str) { + if !ui.read(|s| s.core.admit_store_link(Instant::now())) { + return; + } + match tarn_nsh_shared::extensions::store_link(Exts(ui), key, id) { + Ok(()) => ui.show(Screen::Extensions), + Err(why) => ui.act_on_screen(|s| { + s.notice = Some(why); + Vec::new() + }), + } } pub(super) fn pane(ui: Ui) -> AnyElement { diff --git a/mobile/app/src/ui/mod.rs b/mobile/app/src/ui/mod.rs index a983cc9e..df1b8587 100644 --- a/mobile/app/src/ui/mod.rs +++ b/mobile/app/src/ui/mod.rs @@ -105,6 +105,9 @@ impl Ui { if &*e.name == "pressed" && self.read(|s| s.model.active == Some(key)) { return; } + if &*e.name == browser_core::extensions::STORE_EVENT { + extensions::store_link(self, key, e.data["id"].as_str().unwrap_or_default()); + } if &*e.name == "iconData" { let (name, data) = (e.name.to_string(), e.data.clone()); let encoded = data.get("text").and_then(|t| t.as_str()).unwrap_or_default().to_owned(); @@ -442,6 +445,13 @@ pub fn App() -> impl IntoElement { field: element_ref(), fresh: signal(None), }; + let extensions_open = std::cell::Cell::new(false); + effect(move || { + let open = ui.screen.get() == Screen::Extensions; + if extensions_open.replace(open) && !open { + untracked(tarn_nsh_shared::extensions::close_store_sheet); + } + }); effect(move || { let light = !dark(); untracked(|| { diff --git a/mobile/app/tests/features.rs b/mobile/app/tests/features.rs index 87b72d62..80a5ea15 100644 --- a/mobile/app/tests/features.rs +++ b/mobile/app/tests/features.rs @@ -421,6 +421,23 @@ fn ruled_hosts_open_link_popups_in_their_space() { assert_eq!(load.opener, None, "a routed link opens as a fresh tab"); } +#[test] +fn a_pop_up_to_a_store_link_keeps_its_opener() { + let (_dir, mut shell) = open(); + shell.new_space("Work"); + let work = shell.model.space_ix; + shell.choose_space(0, 1); + visit(&mut shell, "https://extensions.tarnbrowser.com/", "Store"); + assert!(shell.set_site_rule(Some(work))); + shell.new_tab(None); + visit(&mut shell, "https://a.test/", "A"); + let link = "https://extensions.tarnbrowser.com/install/helper"; + shell.event(active(&shell), "popup", &json!({ "url": link, "link": true }), 3); + assert_eq!(shell.model.space_ix, 0, "not routed as a fresh tab"); + let load = shell.views().iter().filter_map(|v| v.load.clone()).find(|l| l.url == link).unwrap(); + assert_eq!(load.opener.as_deref(), Some("https://a.test/"), "the page's pop-up, never the user's own load"); +} + #[test] fn snapshots_save_and_restore_a_space() { let (_dir, mut shell) = open(); diff --git a/mobile/app/tests/shell.rs b/mobile/app/tests/shell.rs index 0352d5be..c2407c3f 100644 --- a/mobile/app/tests/shell.rs +++ b/mobile/app/tests/shell.rs @@ -778,3 +778,27 @@ fn waking_a_sleeping_pane_keeps_the_live_panes_views() { assert_eq!(shell.model.lifecycle.born(a), before, "waking b does not renumber a's view"); assert!(shell.model.lifecycle.born(b).is_some()); } + +#[test] +fn store_links_install_only_from_a_profile_tab_outside_lockdown() { + let (_dir, mut shell) = open(); + finish(&mut shell, "https://example.com/", "E"); + let key = active(&shell); + assert!(shell.store_link_allowed(key)); + assert!(shell.set_site_level(Some(ShieldLevel::Lockdown))); + assert!(!shell.store_link_allowed(key), "from a Lockdown site"); + assert!(shell.set_site_level(None)); + assert!(shell.store_link_allowed(key)); + shell.navigate("https://extensions.tarnbrowser.com/install/helper"); + shell.event(key, browser_core::extensions::STORE_EVENT, &json!({ "id": "helper" }), 3); + assert!(!shell.pages[&key].loading, "the cancelled load stops"); + shell.enter_private(); + assert!(!shell.store_link_allowed(active(&shell)), "never from the private space"); + assert!(!shell.store_link_allowed(key), "only from the space shown"); + shell.close_private(); + shell.open_burner(); + assert!(!shell.store_link_allowed(active(&shell)), "never from a burner tab"); + shell.burn(); + assert!(shell.set_default_level(ShieldLevel::Lockdown)); + assert!(!shell.store_link_allowed(active(&shell)), "never in a Lockdown profile"); +} diff --git a/mobile/ios/src/component.rs b/mobile/ios/src/component.rs index 59fac10a..3d4db4ff 100644 --- a/mobile/ios/src/component.rs +++ b/mobile/ios/src/component.rs @@ -336,6 +336,12 @@ impl Inner { } let from_shell = self.shell_load.take().is_some_and(|expected| expected == url); let opener = self.opener.borrow().clone(); + if crate::store_link::asks(from_shell && opener.is_none(), kind == WKNavigationType::LinkActivated) + && let Some(id) = engine::tarn_ext::store_install(&url) + { + self.emit(engine::tarn_ext::STORE_EVENT, json!({ "id": id })); + return WKNavigationActionPolicy::Cancel; + } let site = Site::new(self.props.borrow().site(&url)); let policy = site.level.max(view).policy(); let user_started = (from_shell && opener.is_none()) || history; diff --git a/mobile/ios/src/lib.rs b/mobile/ios/src/lib.rs index 93cdc0cf..ab516f46 100644 --- a/mobile/ios/src/lib.rs +++ b/mobile/ios/src/lib.rs @@ -15,6 +15,7 @@ mod handler; mod page_root; #[cfg(target_os = "ios")] mod scripts; +pub mod store_link; #[cfg(target_os = "ios")] mod stores; #[cfg(target_os = "ios")] diff --git a/mobile/ios/src/store_link.rs b/mobile/ios/src/store_link.rs new file mode 100644 index 00000000..b6994c4b --- /dev/null +++ b/mobile/ios/src/store_link.rs @@ -0,0 +1,18 @@ +use engine::nav_policy::{StoreNav, store_link_asks}; + +pub fn asks(shell_load: bool, link_activated: bool) -> bool { + store_link_asks(StoreNav { shell_load, clicked: link_activated, ..StoreNav::default() }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_typed_load_or_a_link_click_in_the_main_frame_asks() { + assert!(asks(true, false)); + assert!(asks(false, true)); + assert!(asks(true, true)); + assert!(!asks(false, false), "a script's location change, a form or a history step never asks"); + } +} diff --git a/nsh-shared/src/extensions.rs b/nsh-shared/src/extensions.rs index de647e9c..a51bb7b1 100644 --- a/nsh-shared/src/extensions.rs +++ b/nsh-shared/src/extensions.rs @@ -1,8 +1,9 @@ use std::path::PathBuf; -use browser_core::extensions::install::{self, Fetched, Pending, Slot}; +use browser_core::extensions::install::{self, Fetched, Pending, Slot, StoreCatalog, StoreContext}; use browser_core::extensions::{EVERY_SITE_SETTING, Install, badge, every_site_setting, may_use_all_sites}; use browser_core::github::{Asset, Hop}; +use browser_core::tabs::TabKey; use browser_core::theme_fetch::{self as fetch, shown}; use nsh_base::input; use nsh_core::picker::FilePickRequest; @@ -32,6 +33,8 @@ pub trait Host: Copy + 'static { fn changed(self); /// A line the client wants shown above the list, such as a missing engine feature. fn notice(self) -> Option; + fn open_link(self, url: &'static str); + fn store_link_allowed(self, tab: TabKey) -> bool; } #[derive(Clone, Default)] @@ -42,6 +45,8 @@ struct State { choice: Option<(String, Vec)>, catalog: Option, armed: Option, + sheet: install::StoreSheet, + confirmed: Option, } #[derive(Clone, Default)] @@ -89,10 +94,10 @@ impl Pane { } fn install(self, what: Install, update_of: Option) { - self.run(what, update_of, None); + self.run(what, update_of, None, None); } - fn run(self, what: Install, update_of: Option, temp: Option) { + fn run(self, what: Install, update_of: Option, temp: Option, confirmed: Option) { let drop_temp = move || { if let Some(path) = &temp { std::fs::remove_file(path).ok(); @@ -117,6 +122,7 @@ impl Pane { let locales = host.ui_locales(); self.set(|s| { s.busy = true; + s.confirmed = confirmed; s.choice = None; s.message = Some((false, if what.needs_network() { "Downloading\u{2026}" } else { "Unpacking\u{2026}" }.to_owned())); }); @@ -130,9 +136,11 @@ impl Pane { fn fetched(self, slot: Slot, result: Result) { let name = slot.previous.as_ref().map(|p| shown(&p.name)); + let confirmed = self.state.with_untracked(|s| s.confirmed.clone()); self.set(|s| { s.busy = false; s.message = None; + s.confirmed = None; }); match result.and_then(|f| match f { Fetched::Offer(offer) => install::pending(slot, offer).map(Some), @@ -142,7 +150,13 @@ impl Pane { } Fetched::Current => Err(format!("{}: this extension is up to date.", name.unwrap_or_default())), }) { - Ok(Some(pending)) => self.set(|s| s.pending = Some(pending)), + Ok(Some(pending)) => { + let agreed = confirmed.is_some_and(|id| install::store_confirmed(&id, &pending.row.source)); + self.set(|s| s.pending = Some(pending)); + if agreed { + self.confirm(); + } + } Ok(None) => {} Err(e) => self.say(true, e), } @@ -171,7 +185,7 @@ impl Pane { if let Err(e) = std::fs::write(&path, file.data.bytes()) { return self.say(true, format!("The file could not be read: {e}")); } - self.run(Install::File(path.clone()), None, Some(path)); + self.run(Install::File(path.clone()), None, Some(path), None); }); } @@ -206,6 +220,25 @@ impl Pane { }); } + fn store_check(self, tab: TabKey, busy: bool, step: impl FnOnce(StoreContext, StoreCatalog) -> R) -> R { + let allowed = self.host.profile().is_some() && self.host.store_link_allowed(tab); + let context = StoreContext { allowed, configured: install::catalog_configured(), downloads: self.host.with_store(fetch::downloads_on), busy }; + let (catalog, installed) = (self.state.with_untracked(|s| s.catalog.clone()), self.rows()); + let revoked = self.host.with_store(install::revoked); + step(context, StoreCatalog { index: catalog.as_ref(), now: now_secs(), revoked: &revoked, installed: &installed }) + } + + fn confirm_offer(self, token: &install::StoreToken) { + let mut sheet = self.state.with_untracked(|s| s.sheet.clone()); + let Some(install::StoreOffer { tab, entry: offered, .. }) = sheet.take(token, std::time::Instant::now()) else { return }; + self.set(|s| s.sheet = sheet); + let busy = self.state.with_untracked(|s| s.busy || s.pending.is_some() || s.choice.is_some()); + match self.store_check(tab, busy, |context, catalog| install::store_confirm(&offered, context, catalog)) { + Ok(entry) => self.run(Install::Official(*entry), None, None, Some(offered.id)), + Err(why) => self.say(true, why), + } + } + fn install_official(self, id: &str) { let entry = self .state @@ -297,6 +330,26 @@ fn consent(pane: Pane) -> Option { ) } +fn store_offer(pane: Pane) -> Option { + let (token, (title, lines)) = pane.get(|s| s.sheet.shown().map(|o| (o.token.clone(), install::store_sheet(&o.entry))))?; + let lines = lines.into_iter().map(|l| text(l).text_size(px(TEXT_SMALL)).text_color(Secure::muted()).into_element()); + Some( + view().pt_3().child( + crate::controls::secure_surface(Theme::radius_group()) + .p_3() + .flex_col() + .gap_2() + .child(text(title).font_weight(FontWeight::SEMIBOLD)) + .children(lines) + .child(view().flex_row().gap_2().child(secure_button("Install", move || pane.confirm_offer(&token), true)).child(secure_button( + "Cancel", + move || pane.set(|s| s.sheet.clear()), + false, + ))), + ), + ) +} + fn choice(pane: Pane) -> Option { let (input, assets) = pane.get(|s| s.choice.clone())?; let buttons = assets.into_iter().map(|a| { @@ -360,6 +413,17 @@ fn official(pane: Pane, rows: &[InstalledExtension]) -> View { ) .child(pill("Show Official Extensions", move || pane.show_official())), ) + .child( + row() + .child( + view() + .flex_col() + .flex_1() + .child(label("Browse the store")) + .child(small("Official extensions with screenshots and search; Install in Tarn asks here first.")), + ) + .child(pill("Open", move || pane.host.open_link(browser_core::extensions::STORE_URL))), + ) .children(listed.into_iter().map(|(id, name, description, version, installed)| { row() .child(view().flex_col().flex_1().child(label(name)).child(small(format!("{version} · {description}")))) @@ -381,6 +445,9 @@ fn body(pane: Pane) -> View { if let Some((error, message)) = pane.get(|s| s.message.clone()) { page = page.child(view().px_1().pt_2().child(note(message, error))); } + if let Some(card) = store_offer(pane) { + page = page.child(card); + } if let Some(card) = consent(pane) { page = page.child(card); } @@ -416,11 +483,31 @@ fn body(pane: Pane) -> View { .child(official(pane, &rows)) } -pub fn extensions(host: H) -> AnyElement { +fn opened(host: H) -> Pane { let pane = Pane { host, state: global::(), repo: global::() }; if install::catalog_configured() && pane.state.with_untracked(|s| s.catalog.is_none()) { let cached = install::cached_catalog(&host.catalog_dir(), &install::catalog_key()); pane.set(|s| s.catalog = cached); } + pane +} + +pub fn extensions(host: H) -> AnyElement { + let pane = opened(host); dynamic(move || body(pane)).into_element() } + +pub fn store_link(host: H, tab: TabKey, id: &str) -> Result<(), String> { + let pane = opened(host); + let (mut sheet, busy) = pane.state.with_untracked(|s| (s.sheet.clone(), s.busy || s.pending.is_some() || s.choice.is_some())); + pane.store_check(tab, busy, |context, catalog| sheet.offer(tab, id, context, catalog, std::time::Instant::now()))?; + pane.set(|s| s.sheet = sheet); + Ok(()) +} + +pub fn close_store_sheet() { + let state = global::(); + if state.with_untracked(|s| s.sheet.shown().is_some()) { + state.update(|s| s.sheet.clear()); + } +}