host: plugins, custom CSS, feature flags, settings and open_panel are host commands

run_app now keeps and serves what every app's panel and page need, with the same caller checks
as the rest (commands::SHELL: shell_only first; testkit::assert_host_guards covers them):

- app.rs: PageState (the plugin store in app data `plugins`, the feature flags, ShellSettings)
  managed by the host; commands plugins_list, plugin_set_enabled, plugins_open_folder,
  custom_css_get/set, features_get/set, settings_get/set (moved from wayBetter for X). The app
  reads the state through app::page(), gets a loaded document's scripts from app::page_scripts()
  (flags, links, custom CSS, plugins) and writes through set_features/set_settings/set_custom_css
  (a backup import). AppConfig takes the app's PluginHost (AppConfig::new(site, title, plugins))
  and an optional home_url. SiteHooks::navigation_started and new_window_mode default to the
  owner's link settings.
- settings.rs (pure, tested): ShellSettings { homeUrl, externalLinks, siteLinks, restoreTabs }
  with its input form (missing fields take the defaults; `xLinks`, the name wayBetter for X used,
  is read as siteLinks), links_script ({ site: mode }), feature validation and features_script.
- commands::SITE + open_panel: a tab on the site's origin asks the shell to open the app's panel
  (site_tab_only first). testkit: assert_site_only(command, site) checks that every capability
  granting a site command is a tab capability limited to the site's URLs; assert_host_commands and
  assert_host_guards include the site commands.
- shell frame backupModel: a settings section that still says xLinks compares as siteLinks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
CRTkafa 2026-09-30 14:28:52 +07:00
parent 94ca44edad
commit f6a50602d7
7 changed files with 529 additions and 36 deletions

View file

@ -1,15 +1,17 @@
//! The whole wayBetter app around one site: [`run_app`] (or [`App`]) makes the window, the trusted //! The whole wayBetter app around one site: [`run_app`] (or [`App`]) makes the window, the trusted
//! local shell webview and one child webview per tab, registers the Tauri plugins every app uses, //! local shell webview and one child webview per tab, registers the Tauri plugins every app uses,
//! and serves the generic commands ([`crate::commands`]): tab layout and actions, the shell's //! and serves the generic commands ([`crate::commands`]): tab layout and actions, the shell's
//! focus and raise, external links, the window menu, account profiles and the language. //! focus and raise, external links, the window menu, account profiles, the language, the plugins
//! folder and custom CSS, the page's feature flags and the shell's settings ([`PageState`]).
//! //!
//! The app hands it an [`AppConfig`] (its site, window title and size, which plugins it //! The app hands it an [`AppConfig`] (its site, window title and size, its plugin host, which
//! configures) and a [`SiteHooks`] implementation for what only it knows (the page scripts of a //! Tauri plugins it configures) and a [`SiteHooks`] implementation for what only it knows (the page
//! new tab, what happens when a site page loads, its own per-tab state), plus its own commands. //! scripts of a new tab, what happens when a site page loads, its own per-tab state), plus its own
//! commands.
//! //!
//! ```ignore //! ```ignore
//! pub fn run() { //! pub fn run() {
//! waybetter_host::app::App::new(CONFIG, MySite) //! waybetter_host::app::App::new(AppConfig::new(&SITE, "My app", &PLUGINS), MySite)
//! .setup(|app| { app.manage(MyState::load(app)); Ok(()) }) //! .setup(|app| { app.manage(MyState::load(app)); Ok(()) })
//! .run(tauri::generate_context!(), tauri::generate_handler![my_command]); //! .run(tauri::generate_context!(), tauri::generate_handler![my_command]);
//! } //! }
@ -17,10 +19,13 @@
use crate::{ use crate::{
commands, commands,
host::{self, emit_shell, emit_tab_state, read_json, shell_only, tab_only, tab_webview, write_json}, host::{self, emit_shell, emit_tab_state, read_json, shell_only, site_tab_only, tab_only, tab_webview, write_json},
i18n::{self, NativeStrings}, i18n::{self, NativeStrings},
layout, policy, layout,
plugins::{self, PluginHost, PluginStore, ScriptPlugin},
policy,
profiles::{self, AccountSeen, ProfileSettings}, profiles::{self, AccountSeen, ProfileSettings},
settings::{self, ShellSettings, ShellSettingsInput},
site::SiteSpec, site::SiteSpec,
tabs::{self, parse_web_url, OpenRequest, TabLayout, TabState}, tabs::{self, parse_web_url, OpenRequest, TabLayout, TabState},
}; };
@ -38,6 +43,12 @@ use url::Url;
pub const PROFILES_FILE: &str = "profiles.json"; pub const PROFILES_FILE: &str = "profiles.json";
/// The owner's language and the strings native code needs (app data), see [`i18n`]. /// The owner's language and the strings native code needs (app data), see [`i18n`].
pub const I18N_FILE: &str = "i18n.json"; pub const I18N_FILE: &str = "i18n.json";
/// The shell's settings (app data), see [`settings::ShellSettings`].
pub const SETTINGS_FILE: &str = "settings.json";
/// The page's feature flags (app data): a small map of booleans.
pub const FEATURES_FILE: &str = "features.json";
/// The plugins folder in app data (`*.plugin.js` files, `custom.css`, the enabled list).
pub const PLUGINS_DIR: &str = "plugins";
/// What differs between wayBetter apps at the window level. /// What differs between wayBetter apps at the window level.
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
@ -63,12 +74,18 @@ pub struct AppConfig {
pub updater: bool, pub updater: bool,
/// The language strings site tabs receive (key prefixes, e.g. `["x.", "kit.", "plugin."]`). /// The language strings site tabs receive (key prefixes, e.g. `["x.", "kit.", "plugin."]`).
pub page_string_prefixes: &'static [&'static str], pub page_string_prefixes: &'static [&'static str],
/// The app's plugin host: the page runtime's global, the site's origin, the custom CSS element
/// and the plugins shipped with the app. The plugin store lives in app data [`PLUGINS_DIR`].
pub plugins: &'static PluginHost,
/// The home page before the owner sets one (default: the site's first origin).
pub home_url: Option<&'static str>,
} }
impl AppConfig { impl AppConfig {
/// The defaults: 1360x900 (at least 900x560), a near-black background, the shell's own /// The defaults: 1360x900 (at least 900x560), a near-black background, the shell's own
/// titlebar, no deep links or updater, the UI kit's and plugins' strings for site tabs. /// titlebar, no deep links or updater, the UI kit's and plugins' strings for site tabs, the
pub const fn new(site: &'static SiteSpec, title: &'static str) -> Self { /// site's first origin as the home page.
pub const fn new(site: &'static SiteSpec, title: &'static str, plugins: &'static PluginHost) -> Self {
Self { Self {
site, site,
title, title,
@ -81,8 +98,15 @@ impl AppConfig {
deep_link: false, deep_link: false,
updater: false, updater: false,
page_string_prefixes: &["kit.", "plugin."], page_string_prefixes: &["kit.", "plugin."],
plugins,
home_url: None,
} }
} }
/// The home page before the owner sets one.
pub fn home(&self) -> String {
self.home_url.map(str::to_owned).unwrap_or_else(|| format!("{}/", self.site.primary_origin()))
}
} }
/// A tab webview about to be created ([`SiteHooks::init_scripts`]). /// A tab webview about to be created ([`SiteHooks::init_scripts`]).
@ -127,17 +151,18 @@ pub trait SiteHooks: Send + Sync + 'static {
false false
} }
/// A navigation starts in tab `label`. Returns whether links to other sites go to the /// A navigation starts in tab `label`. Returns whether links to other sites go to the system
/// system browser (the owner's setting), or None when the app's state is unavailable (the /// browser (the owner's setting, [`ShellSettings::external_in_browser`]), or None when the
/// navigation is refused). /// state is unavailable (the navigation is refused).
fn navigation_started(&self, _app: &AppHandle, _label: &str) -> Option<bool> { fn navigation_started(&self, app: &AppHandle, _label: &str) -> Option<bool> {
Some(false) page(app).ok().map(|page| page.settings.external_in_browser())
} }
/// Where a new-window request (target=_blank, window.open) for `url` opens: "tab", "pane" or /// Where a new-window request (target=_blank, window.open) for `url` opens: "tab", "pane" or
/// "browser". /// "browser" (the owner's link settings; a page on the site's origin counts as the site's).
fn new_window_mode(&self, _app: &AppHandle, _url: &Url) -> String { fn new_window_mode(&self, app: &AppHandle, url: &Url) -> String {
"tab".into() let on_site = config(app).site.is_origin(url) || self.site_navigation(url);
page(app).map(|page| page.settings.new_window_mode(on_site).to_owned()).unwrap_or_else(|_| "tab".into())
} }
/// A new document started loading in `tab`. /// A new document started loading in `tab`.
@ -170,8 +195,19 @@ pub struct ProfileState {
pub tab_profiles: HashMap<String, String>, pub tab_profiles: HashMap<String, String>,
} }
/// What every site page gets and the shell's settings: the plugin store (plugins, custom CSS),
/// the feature flags and [`ShellSettings`]. The host's commands read and save them; the app reads
/// them through [`page`] (its page scripts, backups, developer mode).
pub struct PageState {
pub plugins: PluginStore,
/// A JSON object of booleans ([`settings::validate_features`]).
pub features: serde_json::Value,
pub settings: ShellSettings,
}
struct Profiles(Mutex<ProfileState>); struct Profiles(Mutex<ProfileState>);
struct Strings(Mutex<NativeStrings>); struct Strings(Mutex<NativeStrings>);
struct Page(Mutex<PageState>);
struct Host { struct Host {
config: AppConfig, config: AppConfig,
@ -197,6 +233,93 @@ pub fn profiles(app: &AppHandle) -> Result<MutexGuard<'_, ProfileState>, String>
.map_err(|_| "DATABASE: workspace state unavailable; restart safely".into()) .map_err(|_| "DATABASE: workspace state unavailable; restart safely".into())
} }
/// The page state lock (plugins, feature flags, settings). Never call an app hook while holding
/// it; an app that holds a lock of its own may take this one after it, never the other way round.
pub fn page(app: &AppHandle) -> Result<MutexGuard<'_, PageState>, String> {
app.try_state::<Page>()
.ok_or("DATABASE: workspace state unavailable; restart safely")?
.inner()
.0
.lock()
.map_err(|_| "DATABASE: workspace state unavailable; restart safely".into())
}
/// The scripts a freshly loaded site document gets from the page state, in the order they apply.
pub struct PageScripts {
/// The feature flags ([`settings::features_script`]).
pub features: String,
/// Where clicked site pages open ([`settings::links_script`]).
pub links: String,
/// The owner's custom CSS, when there is any.
pub css: Option<String>,
/// One start script per enabled plugin.
pub plugins: Vec<String>,
}
impl PageScripts {
/// Flags, links, custom CSS, then the plugins.
pub fn all(self) -> Vec<String> {
let mut scripts = vec![self.features, self.links];
scripts.extend(self.css);
scripts.extend(self.plugins);
scripts
}
}
/// The page state as scripts for a site document that just loaded (evaluate them natively, so the
/// page's CSP cannot block them). An app with scripts of its own places them between these.
pub fn page_scripts(app: &AppHandle) -> Result<PageScripts, String> {
let site = config(app).site;
let page = page(app)?;
let css = page.plugins.css();
Ok(PageScripts {
features: settings::features_script(site, &page.features),
links: settings::links_script(site, &page.settings),
css: if css.is_empty() { None } else { plugins::css_script(page.plugins.host(), &css).ok() },
plugins: page.plugins.start_scripts(),
})
}
/// Evaluates `script` in every tab that is on the site right now.
pub fn eval_in_site_tabs(app: &AppHandle, script: &str) {
host::eval_in_site_tabs(app, config(app).site, script);
}
/// Replaces the feature flags (validated booleans), saves them and applies them in every site tab.
/// For the app's own writers (a backup import); the shell uses `features_set`.
pub fn set_features(app: &AppHandle, features: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
settings::validate_features(&features)?;
let value = serde_json::Value::Object(features);
write_json(app, FEATURES_FILE, &value)?;
let script = settings::features_script(config(app).site, &value);
page(app)?.features = value;
eval_in_site_tabs(app, &script);
Ok(())
}
/// Replaces the shell's settings (validated), saves them and tells every site tab where its links open.
/// For the app's own writers (a backup import); the shell uses `settings_set`.
pub fn set_settings(app: &AppHandle, input: ShellSettingsInput) -> Result<ShellSettings, String> {
let config = config(app);
let next = ShellSettings::from_input(input, &config.home())?;
write_json(app, SETTINGS_FILE, &next)?;
page(app)?.settings = next.clone();
eval_in_site_tabs(app, &settings::links_script(config.site, &next));
Ok(next)
}
/// Replaces the custom CSS, saves it and applies it in every site tab.
pub fn set_custom_css(app: &AppHandle, css: &str) -> Result<(), String> {
let script = {
let page = page(app)?;
let script = plugins::css_script(page.plugins.host(), css)?;
page.plugins.set_css(css)?;
script
};
eval_in_site_tabs(app, &script);
Ok(())
}
/// The profile tab webview `label` belongs to. /// The profile tab webview `label` belongs to.
pub fn tab_profile(app: &AppHandle, label: &str) -> Option<String> { pub fn tab_profile(app: &AppHandle, label: &str) -> Option<String> {
profiles(app).ok()?.tab_profiles.get(label).cloned() profiles(app).ok()?.tab_profiles.get(label).cloned()
@ -528,6 +651,82 @@ async fn i18n_set(webview: Webview, app: AppHandle, strings: NativeStrings) -> R
Ok(()) Ok(())
} }
#[tauri::command]
async fn plugins_list(webview: Webview, app: AppHandle) -> Result<Vec<ScriptPlugin>, String> {
shell_only(&webview)?;
page(&app)?.plugins.list()
}
/// Turns a plugin on or off and starts or stops it live in every site tab.
#[tauri::command]
async fn plugin_set_enabled(webview: Webview, app: AppHandle, file: String, enabled: bool) -> Result<Vec<ScriptPlugin>, String> {
shell_only(&webview)?;
let (script, list) = {
let page = page(&app)?;
// Build the start script first so a broken file is reported before it is marked enabled.
let script = if enabled { page.plugins.start_script(&file)? } else { plugins::stop_script(page.plugins.host(), &file)? };
page.plugins.set_enabled(&file, enabled)?;
(script, page.plugins.list()?)
};
eval_in_site_tabs(&app, &script);
Ok(list)
}
/// Opens the plugins folder in the system's file manager.
#[tauri::command]
async fn plugins_open_folder(webview: Webview, app: AppHandle) -> Result<(), String> {
shell_only(&webview)?;
let dir = {
let page = page(&app)?;
page.plugins.ensure()?;
page.plugins.dir().to_path_buf()
};
#[cfg(target_os = "windows")]
let opener = "explorer";
#[cfg(target_os = "macos")]
let opener = "open";
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
let opener = "xdg-open";
std::process::Command::new(opener).arg(dir).spawn().map(|_| ()).map_err(|error| format!("PLUGINS: {error}"))
}
#[tauri::command]
async fn custom_css_get(webview: Webview, app: AppHandle) -> Result<String, String> {
shell_only(&webview)?;
Ok(page(&app)?.plugins.css())
}
#[tauri::command]
async fn custom_css_set(webview: Webview, app: AppHandle, css: String) -> Result<(), String> {
shell_only(&webview)?;
set_custom_css(&app, &css)
}
#[tauri::command]
async fn features_get(webview: Webview, app: AppHandle) -> Result<serde_json::Value, String> {
shell_only(&webview)?;
Ok(page(&app)?.features.clone())
}
/// Feature flags are booleans only; the page normalizes them again before use.
#[tauri::command]
async fn features_set(webview: Webview, app: AppHandle, features: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
shell_only(&webview)?;
set_features(&app, features)
}
#[tauri::command]
async fn settings_get(webview: Webview, app: AppHandle) -> Result<ShellSettings, String> {
shell_only(&webview)?;
Ok(page(&app)?.settings.clone())
}
#[tauri::command]
async fn settings_set(webview: Webview, app: AppHandle, settings: ShellSettingsInput) -> Result<ShellSettings, String> {
shell_only(&webview)?;
set_settings(&app, settings)
}
/// Browser shortcuts pressed while a tab has keyboard focus, forwarded to the shell. /// Browser shortcuts pressed while a tab has keyboard focus, forwarded to the shell.
#[tauri::command] #[tauri::command]
async fn tab_shortcut(webview: Webview, app: AppHandle, shortcut: String) -> Result<(), String> { async fn tab_shortcut(webview: Webview, app: AppHandle, shortcut: String) -> Result<(), String> {
@ -544,6 +743,21 @@ async fn tab_link_drag(webview: Webview, app: AppHandle, phase: String, url: Opt
host::forward_link_drag(&app, id, phase, url) host::forward_link_drag(&app, id, phase, url)
} }
/// The app's entry in the site's page (its navigation item, the floating button) opens the app's
/// panel in the shell, at a section. Only from a tab that is on the site right now.
#[tauri::command]
async fn open_panel(webview: Webview, app: AppHandle, section: Option<String>) -> Result<(), String> {
site_tab_only(config(&app).site, &webview)?;
let id = tab_only(&webview)?;
#[derive(Clone, Serialize)]
struct Open {
from: String,
section: Option<String>,
}
emit_shell(&app, tabs::EVENT_OPEN_PANEL, Open { from: id, section: section.filter(|s| s.len() <= 32) });
Ok(())
}
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// Tab webviews // Tab webviews
@ -715,7 +929,7 @@ pub fn reset_lost_geometry(window: &tauri::Window, size: (f64, f64), min: (f64,
} }
} }
/// The host's commands ([`commands::SHELL`], [`commands::TAB`]). /// The host's commands ([`commands::SHELL`], [`commands::TAB`], [`commands::SITE`]).
fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static { fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![ tauri::generate_handler![
tabs_sync, tabs_sync,
@ -731,8 +945,18 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 's
profiles_set, profiles_set,
i18n_get, i18n_get,
i18n_set, i18n_set,
plugins_list,
plugin_set_enabled,
plugins_open_folder,
custom_css_get,
custom_css_set,
features_get,
features_set,
settings_get,
settings_set,
tab_shortcut, tab_shortcut,
tab_link_drag tab_link_drag,
open_panel
] ]
} }
@ -758,7 +982,8 @@ impl App {
} }
/// Runs the app: `context` is `tauri::generate_context!()` and `handler` the app's own /// Runs the app: `context` is `tauri::generate_context!()` and `handler` the app's own
/// `tauri::generate_handler![...]` (the host serves [`commands::SHELL`] and [`commands::TAB`]). /// `tauri::generate_handler![...]` (the host serves [`commands::SHELL`], [`commands::TAB`] and
/// [`commands::SITE`]).
pub fn run<H>(self, context: tauri::Context<Wry>, handler: H) pub fn run<H>(self, context: tauri::Context<Wry>, handler: H)
where where
H: Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static, H: Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static,
@ -806,6 +1031,21 @@ impl App {
tauri_app.manage(Profiles(Mutex::new(ProfileState { settings, tab_profiles: HashMap::new() }))); tauri_app.manage(Profiles(Mutex::new(ProfileState { settings, tab_profiles: HashMap::new() })));
let strings = read_json::<NativeStrings>(&handle, I18N_FILE).and_then(|strings| strings.validated().ok()).unwrap_or_default(); let strings = read_json::<NativeStrings>(&handle, I18N_FILE).and_then(|strings| strings.validated().ok()).unwrap_or_default();
tauri_app.manage(Strings(Mutex::new(strings))); tauri_app.manage(Strings(Mutex::new(strings)));
// The plugins folder (bundled plugins are upgraded at startup, not only when the
// Plugins list is opened: enabled ones would otherwise keep running the previous
// version's code), the feature flags and the shell's settings.
let plugins = PluginStore::new(directory.join(PLUGINS_DIR), config.plugins);
if let Err(error) = plugins.ensure() {
eprintln!("{}: {error}", config.title);
}
let home = config.home();
let settings = read_json::<serde_json::Value>(&handle, SETTINGS_FILE)
.and_then(|value| ShellSettings::from_value(value, &home).ok())
.unwrap_or_else(|| ShellSettings::defaults(&home));
let features = read_json::<serde_json::Value>(&handle, FEATURES_FILE)
.filter(serde_json::Value::is_object)
.unwrap_or_else(|| serde_json::json!({}));
tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings })));
tauri_app.manage(Host { config, hooks }); tauri_app.manage(Host { config, hooks });
if let Some(setup) = setup { if let Some(setup) = setup {
setup(&handle)?; setup(&handle)?;

View file

@ -1,9 +1,10 @@
//! The Tauri commands [`crate::app::run_app`] registers for every app, and who may call them. //! The Tauri commands [`crate::app::run_app`] registers for every app, and who may call them.
//! //!
//! An app's `build.rs` lists its own commands plus these in the app-command manifest //! An app's `build.rs` lists its own commands plus these in the app-command manifest
//! ([`manifest`]), and its capability files grant [`SHELL`] to the local `shell` webview only and //! ([`manifest`]), and its capability files grant [`SHELL`] to the local `shell` webview only,
//! [`TAB`] to tab webviews only; [`crate::testkit`] checks both. Every command re-checks its caller //! [`TAB`] to tab webviews only and [`SITE`] to tab webviews on the site's origin only;
//! natively (`host::shell_only` / `host::tab_only`) before anything else. //! [`crate::testkit`] checks them. Every command re-checks its caller natively
//! (`host::shell_only` / `host::tab_only` / `host::site_tab_only`) before anything else.
/// Shell-only: the local `shell` webview (debug builds also accept the dev server). /// Shell-only: the local `shell` webview (debug builds also accept the dev server).
pub const SHELL: &[&str] = &[ pub const SHELL: &[&str] = &[
@ -20,14 +21,27 @@ pub const SHELL: &[&str] = &[
"profiles_set", "profiles_set",
"i18n_get", "i18n_get",
"i18n_set", "i18n_set",
"plugins_list",
"plugin_set_enabled",
"plugins_open_folder",
"custom_css_get",
"custom_css_set",
"features_get",
"features_set",
"settings_get",
"settings_set",
]; ];
/// Tab-only: any tab webview, speaking only about itself. /// Tab-only: any tab webview, speaking only about itself.
pub const TAB: &[&str] = &["tab_shortcut", "tab_link_drag"]; pub const TAB: &[&str] = &["tab_shortcut", "tab_link_drag"];
/// Site-tab-only: a tab webview that is on the site's origin right now (the page runtime asks
/// the shell to open the app's panel). Grant these in a capability limited to the site's URLs.
pub const SITE: &[&str] = &["open_panel"];
/// Whether `command` is one of the host's (dispatched to the host, never to the app's handler). /// Whether `command` is one of the host's (dispatched to the host, never to the app's handler).
pub fn is_host(command: &str) -> bool { pub fn is_host(command: &str) -> bool {
SHELL.contains(&command) || TAB.contains(&command) SHELL.contains(&command) || TAB.contains(&command) || SITE.contains(&command)
} }
/// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`). /// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`).
@ -42,8 +56,8 @@ pub fn permission(command: &str) -> String {
/// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["draft_list"])) /// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["draft_list"]))
/// ``` /// ```
pub fn manifest(app: &[&'static str]) -> &'static [&'static str] { pub fn manifest(app: &[&'static str]) -> &'static [&'static str] {
let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len()); let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len() + SITE.len());
for command in app.iter().chain(SHELL).chain(TAB) { for command in app.iter().chain(SHELL).chain(TAB).chain(SITE) {
if !all.contains(command) { if !all.contains(command) {
all.push(command); all.push(command);
} }
@ -60,7 +74,7 @@ mod tests {
let all = manifest(&["draft_list", "tabs_sync"]); let all = manifest(&["draft_list", "tabs_sync"]);
assert_eq!(all[0], "draft_list"); assert_eq!(all[0], "draft_list");
assert_eq!(all.iter().filter(|c| **c == "tabs_sync").count(), 1); assert_eq!(all.iter().filter(|c| **c == "tabs_sync").count(), 1);
for command in SHELL.iter().chain(TAB) { for command in SHELL.iter().chain(TAB).chain(SITE) {
assert!(all.contains(command), "{command}"); assert!(all.contains(command), "{command}");
assert!(is_host(command)); assert!(is_host(command));
} }
@ -70,6 +84,7 @@ mod tests {
#[test] #[test]
fn shell_and_tab_commands_do_not_overlap() { fn shell_and_tab_commands_do_not_overlap() {
assert!(!SHELL.iter().any(|command| TAB.contains(command))); assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command)));
assert!(!TAB.iter().any(|command| SITE.contains(command)));
} }
} }

View file

@ -23,6 +23,8 @@
//! shows, its page color and delivery script) over a site's built-in themes. //! shows, its page color and delivery script) over a site's built-in themes.
//! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated). //! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated).
//! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file. //! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file.
//! - [`settings`]: the shell's settings (home page, where links open, session restore) and the page's
//! feature flags, as validated data and the scripts that hand them to site tabs.
//! - [`alerts`]: local keyword alerts (keywords, snippets, per-item/per-keyword rate limits). //! - [`alerts`]: local keyword alerts (keywords, snippets, per-item/per-keyword rate limits).
//! - [`media`]: gallery folders (path containment) and the opt-in clipboard history (private copies skipped). //! - [`media`]: gallery folders (path containment) and the opt-in clipboard history (private copies skipped).
//! - [`gfonts`]: self-hosted Google Fonts: CSS parsing, URL/woff2 checks, the cache format, the page script; //! - [`gfonts`]: self-hosted Google Fonts: CSS parsing, URL/woff2 checks, the cache format, the page script;
@ -37,7 +39,8 @@
//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state; with //! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state; with
//! `tauri` and `net`, [`updater`] runs signed native updates and the hotfix channel. With `app`, //! `tauri` and `net`, [`updater`] runs signed native updates and the hotfix channel. With `app`,
//! [`app`] is the whole app around a site: [`app::run_app`] makes the window, the shell and the tab //! [`app`] is the whole app around a site: [`app::run_app`] makes the window, the shell and the tab
//! webviews, registers the plugins and serves the generic commands; the app adds its own. //! webviews, registers the plugins and serves the generic commands (tab layout and actions, profiles,
//! language, the plugins folder and custom CSS, page tweaks, the shell's settings); the app adds its own.
pub mod alerts; pub mod alerts;
pub mod backup; pub mod backup;
@ -54,6 +57,7 @@ pub mod media;
pub mod plugins; pub mod plugins;
pub mod policy; pub mod policy;
pub mod profiles; pub mod profiles;
pub mod settings;
pub mod site; pub mod site;
pub mod store; pub mod store;
pub mod sync; pub mod sync;

View file

@ -0,0 +1,181 @@
//! What the shell's settings and the page tweaks are, as data the host keeps for every app:
//! [`ShellSettings`] (the home page, where links open, session restore; `settings.json`) and the
//! feature flags (a small map of booleans the page runtime applies; `features.json`). Pure: the
//! commands that read and save them are in [`crate::app`].
use crate::site::SiteSpec;
use crate::tabs;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use url::Url;
/// The home page, where links open and session restore.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShellSettings {
/// Page for new tabs and the first launch.
pub home_url: String,
/// Links to other sites opened from a tab: "pane" (split beside it), "tab" or "browser".
pub external_links: String,
/// The site's own pages clicked in the page: "same" (the site's in-place navigation), "pane",
/// "tab" or "browser". The page runtime diverts only those clicks; see [`links_script`].
pub site_links: String,
/// Reopen the previous session's tabs and splits on launch.
pub restore_tabs: bool,
}
/// Settings as they arrive (the shell, `settings.json`, a backup): any field may be missing.
/// `xLinks` is what wayBetter for X called `siteLinks` before the host kept the settings.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ShellSettingsInput {
pub home_url: Option<String>,
pub external_links: Option<String>,
#[serde(alias = "xLinks")]
pub site_links: Option<String>,
pub restore_tabs: Option<bool>,
}
impl ShellSettings {
/// The settings before the owner changes anything; `home` is the app's home page.
pub fn defaults(home: &str) -> Self {
Self { home_url: home.to_owned(), external_links: "pane".into(), site_links: "same".into(), restore_tabs: true }
}
/// `input` over the defaults, validated: an http(s) home page and known link modes.
pub fn from_input(input: ShellSettingsInput, home: &str) -> Result<Self, String> {
let defaults = Self::defaults(home);
Self {
home_url: input.home_url.unwrap_or(defaults.home_url),
external_links: input.external_links.unwrap_or(defaults.external_links),
site_links: input.site_links.unwrap_or(defaults.site_links),
restore_tabs: input.restore_tabs.unwrap_or(defaults.restore_tabs),
}
.validated()
}
/// Settings from JSON (a file, a backup section), over the defaults and validated.
pub fn from_value(value: Value, home: &str) -> Result<Self, String> {
let input: ShellSettingsInput = serde_json::from_value(value).map_err(|error| format!("VALIDATION: {error}"))?;
Self::from_input(input, home)
}
pub fn validated(mut self) -> Result<Self, String> {
let home = Url::parse(self.home_url.trim()).map_err(|_| "VALIDATION: invalid home page URL")?;
if !matches!(home.scheme(), "http" | "https") {
return Err("VALIDATION: home page must be an http(s) URL".into());
}
self.home_url = home.to_string();
if !tabs::valid_external_mode(&self.external_links) {
return Err("VALIDATION: external links must be \"pane\", \"tab\" or \"browser\"".into());
}
if !tabs::valid_site_mode(&self.site_links) {
return Err("VALIDATION: site links must be \"same\", \"pane\", \"tab\" or \"browser\"".into());
}
Ok(self)
}
/// Where a new-window request (a link with target=_blank, window.open) opens; `on_site`: the
/// request is for one of the site's own pages.
pub fn new_window_mode(&self, on_site: bool) -> &str {
// "same" only concerns ordinary clicks; an explicit new window on the site still gets a tab.
tabs::new_window_mode(on_site, &self.site_links, &self.external_links)
}
/// Links to other sites go to the system browser.
pub fn external_in_browser(&self) -> bool {
self.external_links == "browser"
}
}
/// Tells a site tab where clicked site pages open (`site_links`); the page runtime diverts only
/// "pane", "tab" and "browser" clicks, as a plain new-window request that
/// [`ShellSettings::new_window_mode`] routes. Queued in `__btLinks` until the runtime exists.
pub fn links_script(site: &SiteSpec, settings: &ShellSettings) -> String {
let links = serde_json::json!({ "site": settings.site_links });
tabs::deliver_script(site.runtime_global, "links", "configure", "__btLinks", &links.to_string())
}
/// Feature flags are booleans only, in a small map; the page normalizes them again before use.
pub fn validate_features(features: &Map<String, Value>) -> Result<(), String> {
if features.len() > 64 || features.iter().any(|(key, value)| key.len() > 64 || !value.is_boolean()) {
return Err("VALIDATION: features must be a small map of booleans".into());
}
Ok(())
}
/// Hands a site tab the feature flags (`<global>.features.apply`), queued in `__btFeatures` until
/// the runtime exists.
pub fn features_script(site: &SiteSpec, features: &Value) -> String {
tabs::deliver_script(site.runtime_global, "features", "apply", "__btFeatures", &features.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::site::testing::SITE;
use serde_json::json;
const HOME: &str = "https://x.com/home";
#[test]
fn missing_fields_take_the_defaults_and_the_old_name_is_read() {
let defaults = ShellSettings::defaults(HOME);
assert_eq!(ShellSettings::from_value(json!({}), HOME).unwrap(), defaults);
let old = ShellSettings::from_value(json!({ "homeUrl": "https://x.com/explore", "xLinks": "tab", "restoreTabs": false }), HOME).unwrap();
assert_eq!(old.site_links, "tab");
assert_eq!(old.home_url, "https://x.com/explore");
assert!(!old.restore_tabs);
assert_eq!(old.external_links, "pane");
let new = ShellSettings::from_value(json!({ "siteLinks": "browser" }), HOME).unwrap();
assert_eq!(new.site_links, "browser");
// What the shell reads back.
assert_eq!(
serde_json::to_value(&new).unwrap(),
json!({ "homeUrl": HOME, "externalLinks": "pane", "siteLinks": "browser", "restoreTabs": true })
);
}
#[test]
fn bad_values_are_refused() {
for bad in [
json!({ "homeUrl": "javascript:alert(1)" }),
json!({ "homeUrl": "not a url" }),
json!({ "externalLinks": "same" }),
json!({ "siteLinks": "window" }),
json!({ "restoreTabs": "yes" }),
] {
assert!(ShellSettings::from_value(bad.clone(), HOME).is_err(), "{bad}");
}
}
#[test]
fn new_windows_follow_the_link_settings() {
let mut settings = ShellSettings::defaults(HOME);
assert_eq!(settings.new_window_mode(true), "tab", "\"same\" is about plain clicks; a new window on the site is a tab");
assert_eq!(settings.new_window_mode(false), "pane");
settings.site_links = "browser".into();
settings.external_links = "browser".into();
assert_eq!(settings.new_window_mode(true), "browser");
assert!(settings.external_in_browser());
}
#[test]
fn scripts_deliver_data_to_the_runtime() {
let links = links_script(&SITE, &ShellSettings::defaults(HOME));
assert!(links.contains(r#"{"site":"same"}"#) && links.contains("R.links.configure(v)") && links.contains("window.__btLinks=v"), "{links}");
let features = features_script(&SITE, &json!({ "hideTrends": true }));
assert!(features.contains(r#"{"hideTrends":true}"#) && features.contains("R.features.apply(v)") && features.contains("window.__btFeatures=v"), "{features}");
}
#[test]
fn features_are_a_small_map_of_booleans() {
let map = |value: Value| value.as_object().cloned().unwrap();
assert!(validate_features(&map(json!({ "a": true, "b": false }))).is_ok());
assert!(validate_features(&map(json!({ "a": "yes" }))).is_err());
let long: Map<String, Value> = [("x".repeat(65), Value::Bool(true))].into_iter().collect();
assert!(validate_features(&long).is_err());
let many: Map<String, Value> = (0..65).map(|n| (format!("f{n}"), Value::Bool(true))).collect();
assert!(validate_features(&many).is_err());
}
}

View file

@ -11,6 +11,8 @@ pub const EVENT_TAB_OPEN: &str = "tab-open";
pub const EVENT_TAB_SHORTCUT: &str = "tab-shortcut"; pub const EVENT_TAB_SHORTCUT: &str = "tab-shortcut";
pub const EVENT_LINK_DRAG: &str = "link-drag"; pub const EVENT_LINK_DRAG: &str = "link-drag";
pub const EVENT_PROFILES_CHANGED: &str = "profiles-changed"; pub const EVENT_PROFILES_CHANGED: &str = "profiles-changed";
/// A site tab asks the shell to open the app's panel (`{ from, section }`).
pub const EVENT_OPEN_PANEL: &str = "open-panel";
/// One pane as the shell lays it out (`tabs_sync`). /// One pane as the shell lays it out (`tabs_sync`).
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]

View file

@ -132,12 +132,31 @@ impl Capabilities {
assert!(granting.is_empty(), "{permission} is granted by {granting:?}"); assert!(granting.is_empty(), "{permission} is granted by {granting:?}");
} }
/// The host's commands ([`commands::SHELL`], [`commands::TAB`]) keep their callers. /// `command` is granted, and only to tab webviews on `site`'s own pages: every capability
/// granting it is a tab capability whose remote URLs are exactly `https://<host>/*` of the
/// site's hosts.
pub fn assert_site_only(&self, command: &str, site: &crate::site::SiteSpec) {
self.assert_tab_only(command);
let permission = commands::permission(command);
let allowed: Vec<String> = site.hosts.iter().map(|host| format!("https://{host}/*")).collect();
for cap in self.granting(&permission) {
let urls: Vec<&str> = cap.json["remote"]["urls"].as_array().map(|list| list.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
assert!(
!urls.is_empty() && urls.iter().all(|url| allowed.iter().any(|ok| ok == url)),
"{permission} is for {allowed:?} only, but capability {:?} ({}) grants it on {urls:?}",
cap.identifier(),
cap.file
);
}
}
/// The host's commands ([`commands::SHELL`], [`commands::TAB`], [`commands::SITE`]) keep their
/// callers. Check the site commands' URLs with [`Self::assert_site_only`] too.
pub fn assert_host_commands(&self) { pub fn assert_host_commands(&self) {
for command in commands::SHELL { for command in commands::SHELL {
self.assert_shell_only(command); self.assert_shell_only(command);
} }
for command in commands::TAB { for command in commands::TAB.iter().chain(commands::SITE) {
self.assert_tab_only(command); self.assert_tab_only(command);
} }
} }
@ -179,15 +198,23 @@ pub fn assert_host_guards() {
for command in commands::TAB { for command in commands::TAB {
assert_guarded(source, command, "tab_only(&webview)?"); assert_guarded(source, command, "tab_only(&webview)?");
} }
for command in commands::SITE {
assert_guarded(source, command, "site_tab_only(config(&app).site, &webview)?");
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
fn caps(shell_extra: &str, tab_extra: &str) -> Capabilities { fn caps_with(shell_extra: &str, tab_extra: &str, site_extra: &str) -> Capabilities {
let host_shell: Vec<String> = commands::SHELL.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect(); let host_shell: Vec<String> = commands::SHELL.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect();
let host_tab: Vec<String> = commands::TAB.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect(); let host_tab: Vec<String> = commands::TAB.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect();
let host_site: Vec<String> = commands::SITE.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect();
let site = format!(
r#"{{"identifier":"site-tab","webviews":["tab-*"],"local":false,"remote":{{"urls":["https://x.com/*"]}},"permissions":[{}{site_extra}]}}"#,
host_site.join(",")
);
let shell = format!( let shell = format!(
r#"{{"identifier":"shell","webviews":["shell"],"local":true,"permissions":["core:event:default",{}{shell_extra}]}}"#, r#"{{"identifier":"shell","webviews":["shell"],"local":true,"permissions":["core:event:default",{}{shell_extra}]}}"#,
host_shell.join(",") host_shell.join(",")
@ -196,7 +223,11 @@ mod tests {
r#"{{"identifier":"tab-chrome","webviews":["tab-*"],"local":false,"remote":{{"urls":["https://*/*"]}},"permissions":[{}{tab_extra}]}}"#, r#"{{"identifier":"tab-chrome","webviews":["tab-*"],"local":false,"remote":{{"urls":["https://*/*"]}},"permissions":[{}{tab_extra}]}}"#,
host_tab.join(",") host_tab.join(",")
); );
Capabilities::from_sources(&[("shell.json", &shell), ("tab-chrome.json", &tab)]) Capabilities::from_sources(&[("shell.json", &shell), ("tab-chrome.json", &tab), ("site-tab.json", &site)])
}
fn caps(shell_extra: &str, tab_extra: &str) -> Capabilities {
caps_with(shell_extra, tab_extra, "")
} }
#[test] #[test]
@ -219,6 +250,15 @@ mod tests {
caps(r#","allow-tab-shortcut""#, "").assert_host_commands(); caps(r#","allow-tab-shortcut""#, "").assert_host_commands();
} }
#[test]
fn site_commands_are_for_the_site_only() {
use crate::site::testing::SITE;
caps("", "").assert_site_only("open_panel", &SITE);
// Granted to every tab (any site), a site command fails.
let wide = std::panic::catch_unwind(|| caps("", r#","allow-open-panel""#).assert_site_only("open_panel", &SITE));
assert!(wide.is_err());
}
#[test] #[test]
#[should_panic(expected = "plugin API")] #[should_panic(expected = "plugin API")]
fn plugin_apis_are_refused() { fn plugin_apis_are_refused() {

View file

@ -153,13 +153,24 @@ function details(section: string, current: Json, incoming: Json): string[] {
} }
} }
/**
* A section as it is compared. A `settings` section written before the host kept the settings
* names the site links `xLinks` (native code reads both); it is the same setting as `siteLinks`.
*/
function comparable(section: string, value: Json): Json {
if (section !== 'settings' || !('xLinks' in value) || 'siteLinks' in value) return value;
const { xLinks, ...rest } = value;
return { ...rest, siteLinks: xLinks };
}
/** One preview row per section present in `incoming`, in display order. */ /** One preview row per section present in `incoming`, in display order. */
export function diffSections(current: Json, incoming: Json): SectionRow[] { export function diffSections(current: Json, incoming: Json): SectionRow[] {
const rows: SectionRow[] = []; const rows: SectionRow[] = [];
for (const section of SECTION_ORDER) { for (const section of SECTION_ORDER) {
const next = incoming[section]; const given = incoming[section];
if (!isObject(next)) continue; if (!isObject(given)) continue;
const now = isObject(current[section]) ? current[section] as Json : null; const next = comparable(section, given);
const now = isObject(current[section]) ? comparable(section, current[section] as Json) : null;
const same = !!now && canonical(now) === canonical(next); const same = !!now && canonical(now) === canonical(next);
const status: SectionRow['status'] = same ? 'same' : now && Object.keys(now).length ? 'changed' : 'new'; const status: SectionRow['status'] = same ? 'same' : now && Object.keys(now).length ? 'changed' : 'new';
const lines = same ? [t('wb.backup.detail.same')] : details(section, now ?? {}, next); const lines = same ? [t('wb.backup.detail.same')] : details(section, now ?? {}, next);