Host: 256 feature flags, the onboarding mode (mode_get/mode_set, shell-only), and the one-time move of replaced plugin files to feature flags
- settings: MAX_FEATURES 64 -> 256 (an older app's whole-map backup still validates)
- modes: ModeState {mode, onboarded, existing} in modes.json; existing is decided natively on the first start
- plugins::migrate: PluginHost.superseded (file -> flag); enabled and as shipped -> flag on and the file goes; edited -> kept, flag left off; marker written last, every step repeatable; map_backup for imported enabled lists
- a superseded file is never written again by install_bundled
- create-waybetter: the host command list and PluginHost.superseded
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ca9eec05ab
commit
e7e744f66d
9 changed files with 477 additions and 6 deletions
|
|
@ -22,6 +22,7 @@ use crate::{
|
||||||
host::{self, emit_shell, emit_tab_state, read_json, shell_only, site_tab_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,
|
layout,
|
||||||
|
modes::{ModeState, MODES_FILE},
|
||||||
plugins::{self, PluginHost, PluginStore, ScriptPlugin},
|
plugins::{self, PluginHost, PluginStore, ScriptPlugin},
|
||||||
policy,
|
policy,
|
||||||
profiles::{self, AccountSeen, ProfileSettings},
|
profiles::{self, AccountSeen, ProfileSettings},
|
||||||
|
|
@ -203,6 +204,8 @@ pub struct PageState {
|
||||||
/// A JSON object of booleans ([`settings::validate_features`]).
|
/// A JSON object of booleans ([`settings::validate_features`]).
|
||||||
pub features: serde_json::Value,
|
pub features: serde_json::Value,
|
||||||
pub settings: ShellSettings,
|
pub settings: ShellSettings,
|
||||||
|
/// The onboarding mode the owner started from and whether the first-run screen was answered.
|
||||||
|
pub modes: ModeState,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Profiles(Mutex<ProfileState>);
|
struct Profiles(Mutex<ProfileState>);
|
||||||
|
|
@ -715,6 +718,25 @@ async fn features_set(webview: Webview, app: AppHandle, features: serde_json::Ma
|
||||||
set_features(&app, features)
|
set_features(&app, features)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The onboarding mode: what was chosen, whether the first-run screen was answered, and whether
|
||||||
|
/// this app was set up before modes existed.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn mode_get(webview: Webview, app: AppHandle) -> Result<ModeState, String> {
|
||||||
|
shell_only(&webview)?;
|
||||||
|
Ok(page(&app)?.modes.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remembers the chosen mode (or none) and that the first-run screen was answered. The preset's
|
||||||
|
/// flags are the shell's to apply (`features_set`); this only records the choice.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn mode_set(webview: Webview, app: AppHandle, mode: Option<String>, onboarded: bool) -> Result<ModeState, String> {
|
||||||
|
shell_only(&webview)?;
|
||||||
|
let next = page(&app)?.modes.chosen(mode, onboarded)?;
|
||||||
|
write_json(&app, MODES_FILE, &next)?;
|
||||||
|
page(&app)?.modes = next.clone();
|
||||||
|
Ok(next)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn settings_get(webview: Webview, app: AppHandle) -> Result<ShellSettings, String> {
|
async fn settings_get(webview: Webview, app: AppHandle) -> Result<ShellSettings, String> {
|
||||||
shell_only(&webview)?;
|
shell_only(&webview)?;
|
||||||
|
|
@ -952,6 +974,8 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 's
|
||||||
custom_css_set,
|
custom_css_set,
|
||||||
features_get,
|
features_get,
|
||||||
features_set,
|
features_set,
|
||||||
|
mode_get,
|
||||||
|
mode_set,
|
||||||
settings_get,
|
settings_get,
|
||||||
settings_set,
|
settings_set,
|
||||||
tab_shortcut,
|
tab_shortcut,
|
||||||
|
|
@ -1019,6 +1043,8 @@ impl App {
|
||||||
}
|
}
|
||||||
let directory = tauri_app.path().app_data_dir()?;
|
let directory = tauri_app.path().app_data_dir()?;
|
||||||
std::fs::create_dir_all(&directory)?;
|
std::fs::create_dir_all(&directory)?;
|
||||||
|
// Someone set this app up before (read before anything below writes a file).
|
||||||
|
let existing = [PROFILES_FILE, SETTINGS_FILE, FEATURES_FILE, PLUGINS_DIR].iter().any(|name| directory.join(name).exists());
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
@ -1042,10 +1068,28 @@ impl App {
|
||||||
let settings = read_json::<serde_json::Value>(&handle, SETTINGS_FILE)
|
let settings = read_json::<serde_json::Value>(&handle, SETTINGS_FILE)
|
||||||
.and_then(|value| ShellSettings::from_value(value, &home).ok())
|
.and_then(|value| ShellSettings::from_value(value, &home).ok())
|
||||||
.unwrap_or_else(|| ShellSettings::defaults(&home));
|
.unwrap_or_else(|| ShellSettings::defaults(&home));
|
||||||
let features = read_json::<serde_json::Value>(&handle, FEATURES_FILE)
|
let mut features = read_json::<serde_json::Value>(&handle, FEATURES_FILE)
|
||||||
.filter(serde_json::Value::is_object)
|
.filter(serde_json::Value::is_object)
|
||||||
.unwrap_or_else(|| serde_json::json!({}));
|
.unwrap_or_else(|| serde_json::json!({}));
|
||||||
tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings })));
|
// Plugin files the app turned into features: what was enabled becomes its flag, once
|
||||||
|
// (plugins::migrate). The flags are saved before any file is touched.
|
||||||
|
let migrated = plugins.migrate_superseded(config.plugins.superseded, |flags| {
|
||||||
|
let Some(map) = features.as_object_mut().filter(|_| !flags.is_empty()) else { return Ok(()) };
|
||||||
|
for flag in flags {
|
||||||
|
map.insert(flag.clone(), serde_json::Value::Bool(true));
|
||||||
|
}
|
||||||
|
settings::validate_features(map)?;
|
||||||
|
write_json(&handle, FEATURES_FILE, &*map)
|
||||||
|
});
|
||||||
|
if let Err(error) = migrated {
|
||||||
|
eprintln!("{}: {error}", config.title);
|
||||||
|
}
|
||||||
|
let modes = read_json::<ModeState>(&handle, MODES_FILE).and_then(|state| state.validated().ok()).unwrap_or_else(|| {
|
||||||
|
let state = ModeState::first_run(existing);
|
||||||
|
let _ = write_json(&handle, MODES_FILE, &state);
|
||||||
|
state
|
||||||
|
});
|
||||||
|
tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings, modes })));
|
||||||
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)?;
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,8 @@ pub const SHELL: &[&str] = &[
|
||||||
"custom_css_set",
|
"custom_css_set",
|
||||||
"features_get",
|
"features_get",
|
||||||
"features_set",
|
"features_set",
|
||||||
|
"mode_get",
|
||||||
|
"mode_set",
|
||||||
"settings_get",
|
"settings_get",
|
||||||
"settings_set",
|
"settings_set",
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@
|
||||||
//! - [`policy`]: webview labels, origin checks and the tab rectangle clamp (security boundary).
|
//! - [`policy`]: webview labels, origin checks and the tab rectangle clamp (security boundary).
|
||||||
//! - [`profiles`]: account profiles, one WebView data directory each, with the account seen inside.
|
//! - [`profiles`]: account profiles, one WebView data directory each, with the account seen inside.
|
||||||
//! - [`plugins`]: owner-installed `*.plugin.js` files, custom CSS and bundled-plugin upgrades;
|
//! - [`plugins`]: owner-installed `*.plugin.js` files, custom CSS and bundled-plugin upgrades;
|
||||||
|
//! [`plugins::migrate`]: the one-time move of replaced plugin files to feature flags;
|
||||||
//! [`plugins::commands`]: the palette commands site tabs report and the script that runs one.
|
//! [`plugins::commands`]: the palette commands site tabs report and the script that runs one.
|
||||||
//! - [`hotfix`]: the signed, data-only hotfix channel.
|
//! - [`hotfix`]: the signed, data-only hotfix channel.
|
||||||
//! - [`update`]: silent-update scheduling and the crash handshake.
|
//! - [`update`]: silent-update scheduling and the crash handshake.
|
||||||
|
|
@ -25,6 +26,7 @@
|
||||||
//! - [`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
|
//! - [`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.
|
//! feature flags, as validated data and the scripts that hand them to site tabs.
|
||||||
|
//! - [`modes`]: the onboarding mode the owner started from (the presets are the app's feature table).
|
||||||
//! - [`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;
|
||||||
|
|
@ -54,6 +56,7 @@ pub mod hotfix;
|
||||||
pub mod i18n;
|
pub mod i18n;
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
pub mod media;
|
pub mod media;
|
||||||
|
pub mod modes;
|
||||||
pub mod plugins;
|
pub mod plugins;
|
||||||
pub mod policy;
|
pub mod policy;
|
||||||
pub mod profiles;
|
pub mod profiles;
|
||||||
|
|
|
||||||
85
crates/waybetter-host/src/modes.rs
Normal file
85
crates/waybetter-host/src/modes.rs
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
//! The onboarding mode: which preset (Basic / Advanced / Power User, whatever the app defines) the
|
||||||
|
//! owner started from, and whether the first-run screen was answered. A mode is a starting point:
|
||||||
|
//! the presets themselves are the app's (its feature table) and are applied by the shell through
|
||||||
|
//! `features_set`; native code only remembers the choice (`modes.json`), so the screen shows once.
|
||||||
|
//!
|
||||||
|
//! `existing` is decided natively, once, on the first start of a version that has modes: an app
|
||||||
|
//! data folder that already held settings belongs to someone who set the app up before. They keep
|
||||||
|
//! exactly what they have, and the screen they see can be dismissed without choosing.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub const MODES_FILE: &str = "modes.json";
|
||||||
|
const MAX_MODE_ID: usize = 32;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct ModeState {
|
||||||
|
/// The mode chosen last; `None` = never chosen (the app's defaults, or an earlier setup).
|
||||||
|
pub mode: Option<String>,
|
||||||
|
/// The first-run screen was answered or dismissed.
|
||||||
|
pub onboarded: bool,
|
||||||
|
/// The app was set up before modes existed.
|
||||||
|
pub existing: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A mode id: lowercase letters, digits and `-`, starting with a letter, at most 32 characters.
|
||||||
|
pub fn valid_mode(id: &str) -> bool {
|
||||||
|
!id.is_empty()
|
||||||
|
&& id.len() <= MAX_MODE_ID
|
||||||
|
&& id.as_bytes()[0].is_ascii_lowercase()
|
||||||
|
&& id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModeState {
|
||||||
|
/// The state on the first start: nothing chosen, the screen still to be shown.
|
||||||
|
pub fn first_run(existing: bool) -> Self {
|
||||||
|
Self { mode: None, onboarded: false, existing }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validated(self) -> Result<Self, String> {
|
||||||
|
if self.mode.as_deref().is_some_and(|mode| !valid_mode(mode)) {
|
||||||
|
return Err("VALIDATION: invalid mode".into());
|
||||||
|
}
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the shell may change: the chosen mode and that the screen was answered. `existing`
|
||||||
|
/// stays what native code decided.
|
||||||
|
pub fn chosen(&self, mode: Option<String>, onboarded: bool) -> Result<Self, String> {
|
||||||
|
Self { mode, onboarded, existing: self.existing }.validated()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mode_ids_are_short_plain_words() {
|
||||||
|
for good in ["basic", "advanced", "power-user", "m2"] {
|
||||||
|
assert!(valid_mode(good), "{good}");
|
||||||
|
}
|
||||||
|
for bad in ["", "Basic", "2fast", "a b", "a/b", "../x", &"a".repeat(33)] {
|
||||||
|
assert!(!valid_mode(bad), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_shell_chooses_a_mode_but_never_what_kind_of_install_this_is() {
|
||||||
|
let fresh = ModeState::first_run(false);
|
||||||
|
assert_eq!(fresh, ModeState { mode: None, onboarded: false, existing: false });
|
||||||
|
let existing = ModeState::first_run(true);
|
||||||
|
let dismissed = existing.chosen(None, true).unwrap();
|
||||||
|
assert_eq!(dismissed, ModeState { mode: None, onboarded: true, existing: true }, "dismissed without choosing: nothing else changes");
|
||||||
|
let chosen = dismissed.chosen(Some("power".into()), true).unwrap();
|
||||||
|
assert_eq!(chosen.mode.as_deref(), Some("power"));
|
||||||
|
assert!(chosen.existing);
|
||||||
|
assert!(existing.chosen(Some("<script>".into()), true).is_err());
|
||||||
|
// The file reads back; missing fields take the defaults; unknown input never panics.
|
||||||
|
let json = serde_json::to_string(&chosen).unwrap();
|
||||||
|
assert_eq!(json, r#"{"mode":"power","onboarded":true,"existing":true}"#);
|
||||||
|
assert_eq!(serde_json::from_str::<ModeState>("{}").unwrap(), ModeState::default());
|
||||||
|
assert!(serde_json::from_str::<ModeState>(r#"{"mode":"BAD MODE"}"#).unwrap().validated().is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -13,6 +13,7 @@
|
||||||
//! it. A plugin without the line is "legacy" (full API, labelled so in the app).
|
//! it. A plugin without the line is "legacy" (full API, labelled so in the app).
|
||||||
|
|
||||||
pub mod commands;
|
pub mod commands;
|
||||||
|
pub mod migrate;
|
||||||
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
@ -43,6 +44,9 @@ pub struct PluginHost {
|
||||||
pub example: Option<(&'static str, &'static str)>,
|
pub example: Option<(&'static str, &'static str)>,
|
||||||
/// First-party plugins, written disabled and upgraded (see [`PluginStore::install_bundled`]).
|
/// First-party plugins, written disabled and upgraded (see [`PluginStore::install_bundled`]).
|
||||||
pub bundled: &'static [(&'static str, &'static str)],
|
pub bundled: &'static [(&'static str, &'static str)],
|
||||||
|
/// First-party plugin files the app replaced with feature flags: never written again, and moved
|
||||||
|
/// over once (see [`migrate`]).
|
||||||
|
pub superseded: &'static [migrate::Superseded],
|
||||||
}
|
}
|
||||||
|
|
||||||
fn content_hash(bytes: &[u8]) -> String {
|
fn content_hash(bytes: &[u8]) -> String {
|
||||||
|
|
@ -279,7 +283,7 @@ impl PluginStore {
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let before = manifest.clone();
|
let before = manifest.clone();
|
||||||
for (file, source) in bundled {
|
for (file, source) in bundled {
|
||||||
if !valid_file_name(file) {
|
if !valid_file_name(file) || self.host.superseded.iter().any(|row| row.file == *file) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let path = self.dir.join(file);
|
let path = self.dir.join(file);
|
||||||
|
|
@ -535,6 +539,7 @@ mod tests {
|
||||||
css_element_id: "demo-css",
|
css_element_id: "demo-css",
|
||||||
example: Some(("example.plugin.js", "/**\n * @name Example\n */\nmodule.exports = class { start(){} stop(){} };")),
|
example: Some(("example.plugin.js", "/**\n * @name Example\n */\nmodule.exports = class { start(){} stop(){} };")),
|
||||||
bundled: &[("wb-one.plugin.js", "/** @name One */ module.exports = {};")],
|
bundled: &[("wb-one.plugin.js", "/** @name One */ module.exports = {};")],
|
||||||
|
superseded: &[],
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
316
crates/waybetter-host/src/plugins/migrate.rs
Normal file
316
crates/waybetter-host/src/plugins/migrate.rs
Normal file
|
|
@ -0,0 +1,316 @@
|
||||||
|
//! One-time move of first-party plugin files to feature flags.
|
||||||
|
//!
|
||||||
|
//! When an app turns a bundled plugin into a feature of an area plugin (its code now runs from the
|
||||||
|
//! app's feature registry behind a flag), the old file must not keep running next to it, and the
|
||||||
|
//! owner must not lose what they had on. The app lists the files it replaced ([`Superseded`]:
|
||||||
|
//! file -> flag) in its [`super::PluginHost`]; [`PluginStore::migrate_superseded`] runs once per
|
||||||
|
//! listed file, at startup, and leaves the owner's effective state exactly as it was:
|
||||||
|
//!
|
||||||
|
//! | The old file is ... | Result |
|
||||||
|
//! |--------------------------------------------------------|------------------------------------------------------|
|
||||||
|
//! | enabled, as shipped (never edited) | its flag is turned on; the file and its entry go |
|
||||||
|
//! | disabled, as shipped | the flag stays off; the file goes |
|
||||||
|
//! | edited by the owner (or a file of their own) | kept with its on/off state; the flag is left off |
|
||||||
|
//! | deleted earlier by the owner | nothing; the flag stays off |
|
||||||
|
//! | not there at all (a fresh install) | nothing |
|
||||||
|
//!
|
||||||
|
//! "As shipped" means byte-identical to what the app last wrote (`bundled.json`). The marker
|
||||||
|
//! (`migrations.json` in the plugins folder) is written last, so a crash in between repeats the
|
||||||
|
//! steps, and every step is safe to repeat: flags are only ever turned on, and a file already
|
||||||
|
//! removed is simply not there. The same table maps the `enabled` list of an imported backup
|
||||||
|
//! ([`map_backup`]).
|
||||||
|
|
||||||
|
use super::{content_hash, valid_file_name, PluginStore, BUNDLED_FILE, STATE_FILE};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
/// Which superseded files were handled already (in the plugins folder).
|
||||||
|
pub const MARKER_FILE: &str = "migrations.json";
|
||||||
|
|
||||||
|
/// An old first-party plugin file and the feature flag that replaces it.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Superseded {
|
||||||
|
pub file: &'static str,
|
||||||
|
pub flag: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
struct Marker {
|
||||||
|
superseded: BTreeSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one run did (empty when there was nothing left to do).
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct Outcome {
|
||||||
|
/// Flags turned on: their old plugin was enabled and as shipped.
|
||||||
|
pub flags_on: Vec<String>,
|
||||||
|
/// Files removed (as shipped).
|
||||||
|
pub removed: Vec<String>,
|
||||||
|
/// Files kept because the owner changed them; their replacement flag was left alone.
|
||||||
|
pub kept: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PluginStore {
|
||||||
|
/// Handles every file of `table` that was not handled before. `turn_on` persists the flags to
|
||||||
|
/// turn on (it must only ever set them to true and keep every other flag) and runs before any
|
||||||
|
/// file is touched: when it fails nothing has changed and the next start tries again.
|
||||||
|
pub fn migrate_superseded(&self, table: &[Superseded], turn_on: impl FnOnce(&[String]) -> Result<(), String>) -> Result<Outcome, String> {
|
||||||
|
let marker_path = self.dir.join(MARKER_FILE);
|
||||||
|
let mut marker: Marker = fs::read_to_string(&marker_path).ok().and_then(|raw| serde_json::from_str(&raw).ok()).unwrap_or_default();
|
||||||
|
let pending: Vec<&Superseded> = table.iter().filter(|row| valid_file_name(row.file) && !marker.superseded.contains(row.file)).collect();
|
||||||
|
if pending.is_empty() {
|
||||||
|
return Ok(Outcome::default());
|
||||||
|
}
|
||||||
|
fs::create_dir_all(&self.dir).map_err(|error| format!("PLUGINS: {error}"))?;
|
||||||
|
let manifest_path = self.dir.join(BUNDLED_FILE);
|
||||||
|
let mut manifest: BTreeMap<String, String> = fs::read_to_string(&manifest_path).ok().and_then(|raw| serde_json::from_str(&raw).ok()).unwrap_or_default();
|
||||||
|
let mut enabled = self.enabled_set();
|
||||||
|
let mut outcome = Outcome::default();
|
||||||
|
let mut gone: Vec<&str> = Vec::new();
|
||||||
|
for row in &pending {
|
||||||
|
match fs::read(self.dir.join(row.file)) {
|
||||||
|
// Deleted earlier (or never installed): nothing to move; a stale enabled entry goes.
|
||||||
|
Err(_) => gone.push(row.file),
|
||||||
|
Ok(bytes) => {
|
||||||
|
if manifest.get(row.file).is_some_and(|installed| *installed == content_hash(&bytes)) {
|
||||||
|
if enabled.contains(row.file) {
|
||||||
|
outcome.flags_on.push(row.flag.to_owned());
|
||||||
|
}
|
||||||
|
outcome.removed.push(row.file.to_owned());
|
||||||
|
} else {
|
||||||
|
outcome.kept.push(row.file.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
turn_on(&outcome.flags_on)?;
|
||||||
|
let before = enabled.len();
|
||||||
|
for file in outcome.removed.iter().map(String::as_str).chain(gone.iter().copied()) {
|
||||||
|
enabled.remove(file);
|
||||||
|
}
|
||||||
|
if enabled.len() != before {
|
||||||
|
let json = serde_json::to_string_pretty(&enabled).map_err(|_| "PLUGINS: serialization failed")?;
|
||||||
|
fs::write(self.dir.join(STATE_FILE), json).map_err(|error| format!("PLUGINS: {error}"))?;
|
||||||
|
}
|
||||||
|
for file in &outcome.removed {
|
||||||
|
match fs::remove_file(self.dir.join(file)) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||||
|
Err(error) => return Err(format!("PLUGINS: {error}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The app no longer ships these files: their "last written" entries go with them. A kept
|
||||||
|
// (edited) file is an ordinary plugin of the owner's from here on.
|
||||||
|
let entries = manifest.len();
|
||||||
|
for row in &pending {
|
||||||
|
manifest.remove(row.file);
|
||||||
|
}
|
||||||
|
if manifest.len() != entries {
|
||||||
|
let json = serde_json::to_string_pretty(&manifest).map_err(|_| "PLUGINS: serialization failed")?;
|
||||||
|
fs::write(&manifest_path, json).map_err(|error| format!("PLUGINS: {error}"))?;
|
||||||
|
}
|
||||||
|
marker.superseded.extend(pending.iter().map(|row| row.file.to_owned()));
|
||||||
|
let json = serde_json::to_string_pretty(&marker).map_err(|_| "PLUGINS: serialization failed")?;
|
||||||
|
fs::write(&marker_path, json).map_err(|error| format!("PLUGINS: {error}"))?;
|
||||||
|
Ok(outcome)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `enabled` list of an imported backup, mapped through `table`: a superseded file that the
|
||||||
|
/// backup only names (it was as shipped, so the backup carries no copy) becomes its flag and leaves
|
||||||
|
/// the list; one the backup carries a copy of (`files`: the owner's edited version) stays a plugin.
|
||||||
|
/// Returns the list to enable and the flags to turn on.
|
||||||
|
pub fn map_backup(enabled: Vec<String>, files: &[String], table: &[Superseded]) -> (Vec<String>, Vec<String>) {
|
||||||
|
let mut keep = Vec::with_capacity(enabled.len());
|
||||||
|
let mut flags_on = Vec::new();
|
||||||
|
for name in enabled {
|
||||||
|
match table.iter().find(|row| row.file == name) {
|
||||||
|
Some(row) if !files.contains(&name) => {
|
||||||
|
if !flags_on.iter().any(|flag| flag == row.flag) {
|
||||||
|
flags_on.push(row.flag.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => keep.push(name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(keep, flags_on)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::plugins::PluginHost;
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
static HOST: PluginHost = PluginHost {
|
||||||
|
runtime_global: "Demo",
|
||||||
|
origin: "https://site.test",
|
||||||
|
product: "wayBetter for Test",
|
||||||
|
css_element_id: "demo-css",
|
||||||
|
example: None,
|
||||||
|
bundled: &[("wb-stays.plugin.js", "stays v1")],
|
||||||
|
superseded: TABLE,
|
||||||
|
};
|
||||||
|
/// The previous version of the app: it still shipped the files.
|
||||||
|
static OLD_HOST: PluginHost = PluginHost { superseded: &[], ..HOST };
|
||||||
|
const TABLE: &[Superseded] = &[
|
||||||
|
Superseded { file: "wb-focus.plugin.js", flag: "navigation.focusMode" },
|
||||||
|
Superseded { file: "wb-keys.plugin.js", flag: "navigation.keyboardPlus" },
|
||||||
|
Superseded { file: "wb-edited.plugin.js", flag: "navigation.edited" },
|
||||||
|
Superseded { file: "wb-deleted.plugin.js", flag: "navigation.deleted" },
|
||||||
|
];
|
||||||
|
/// What the previous version shipped.
|
||||||
|
const OLD: &[(&str, &str)] = &[
|
||||||
|
("wb-stays.plugin.js", "stays v1"),
|
||||||
|
("wb-focus.plugin.js", "focus v1"),
|
||||||
|
("wb-keys.plugin.js", "keys v1"),
|
||||||
|
("wb-edited.plugin.js", "edited v1"),
|
||||||
|
("wb-deleted.plugin.js", "deleted v1"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// A plugins folder as the previous version left it: Focus and the edited one enabled, Keys off.
|
||||||
|
fn upgraded() -> (tempfile::TempDir, PluginStore) {
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let old = PluginStore::new(root.path().join("plugins"), &OLD_HOST);
|
||||||
|
fs::create_dir_all(old.dir()).unwrap();
|
||||||
|
old.install_bundled(OLD);
|
||||||
|
let store = PluginStore::new(root.path().join("plugins"), &HOST);
|
||||||
|
fs::write(store.dir().join("wb-edited.plugin.js"), "my own version").unwrap();
|
||||||
|
fs::remove_file(store.dir().join("wb-deleted.plugin.js")).unwrap();
|
||||||
|
fs::write(store.dir().join("mine.plugin.js"), "mine").unwrap();
|
||||||
|
for file in ["wb-focus.plugin.js", "wb-edited.plugin.js", "mine.plugin.js", "wb-stays.plugin.js"] {
|
||||||
|
store.set_enabled(file, true).unwrap();
|
||||||
|
}
|
||||||
|
(root, store)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exists(store: &PluginStore, file: &str) -> bool {
|
||||||
|
store.dir().join(file).exists()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn marker(dir: &Path) -> Vec<String> {
|
||||||
|
let marker: Marker = serde_json::from_str(&fs::read_to_string(dir.join(MARKER_FILE)).unwrap()).unwrap();
|
||||||
|
marker.superseded.into_iter().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_case_keeps_the_owners_effective_state() {
|
||||||
|
let (_root, store) = upgraded();
|
||||||
|
let turned_on = RefCell::new(Vec::new());
|
||||||
|
let outcome = store.migrate_superseded(TABLE, |flags| { turned_on.borrow_mut().extend(flags.to_vec()); Ok(()) }).unwrap();
|
||||||
|
// Enabled and as shipped: the flag takes over and the file goes.
|
||||||
|
assert_eq!(outcome.flags_on, ["navigation.focusMode"]);
|
||||||
|
assert_eq!(*turned_on.borrow(), ["navigation.focusMode"]);
|
||||||
|
assert!(!exists(&store, "wb-focus.plugin.js") && !store.is_enabled("wb-focus.plugin.js"));
|
||||||
|
// Disabled and as shipped: the file goes, its flag stays off.
|
||||||
|
assert!(!exists(&store, "wb-keys.plugin.js"));
|
||||||
|
assert_eq!(outcome.removed, ["wb-focus.plugin.js", "wb-keys.plugin.js"]);
|
||||||
|
// Edited by the owner: kept, still enabled, and the built-in replacement is left off.
|
||||||
|
assert_eq!(outcome.kept, ["wb-edited.plugin.js"]);
|
||||||
|
assert_eq!(fs::read_to_string(store.dir().join("wb-edited.plugin.js")).unwrap(), "my own version");
|
||||||
|
assert!(store.is_enabled("wb-edited.plugin.js"));
|
||||||
|
// Deleted earlier: still deleted, flag untouched.
|
||||||
|
assert!(!exists(&store, "wb-deleted.plugin.js"));
|
||||||
|
// Everything else is as it was.
|
||||||
|
assert!(store.is_enabled("mine.plugin.js") && store.is_enabled("wb-stays.plugin.js"));
|
||||||
|
assert_eq!(fs::read_to_string(store.dir().join("wb-stays.plugin.js")).unwrap(), "stays v1");
|
||||||
|
assert_eq!(marker(store.dir()), ["wb-deleted.plugin.js", "wb-edited.plugin.js", "wb-focus.plugin.js", "wb-keys.plugin.js"]);
|
||||||
|
// Nothing runs twice: no old file is enabled while its flag is on.
|
||||||
|
for row in TABLE {
|
||||||
|
assert!(!(store.is_enabled(row.file) && outcome.flags_on.iter().any(|flag| flag == row.flag)), "{}", row.file);
|
||||||
|
}
|
||||||
|
// The removed files are gone from what the app "last wrote"; the next start does not bring them back.
|
||||||
|
store.ensure().unwrap();
|
||||||
|
assert!(!exists(&store, "wb-focus.plugin.js") && !exists(&store, "wb-keys.plugin.js"));
|
||||||
|
let manifest: BTreeMap<String, String> = serde_json::from_str(&fs::read_to_string(store.dir().join(BUNDLED_FILE)).unwrap()).unwrap();
|
||||||
|
assert_eq!(manifest.keys().collect::<Vec<_>>(), ["wb-stays.plugin.js"]);
|
||||||
|
// Even an app that still lists a superseded file as bundled never writes it again.
|
||||||
|
store.install_bundled(OLD);
|
||||||
|
assert!(!exists(&store, "wb-focus.plugin.js") && !exists(&store, "wb-deleted.plugin.js"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_runs_once_and_later_rows_are_handled_when_they_appear() {
|
||||||
|
let (_root, store) = upgraded();
|
||||||
|
let first = &TABLE[..1];
|
||||||
|
let outcome = store.migrate_superseded(first, |_| Ok(())).unwrap();
|
||||||
|
assert_eq!(outcome.flags_on, ["navigation.focusMode"]);
|
||||||
|
assert!(exists(&store, "wb-keys.plugin.js"), "a file the table does not list yet is left alone");
|
||||||
|
// Again: nothing to do, and the closure is not asked for anything.
|
||||||
|
let again = store.migrate_superseded(first, |_| panic!("already done")).unwrap();
|
||||||
|
assert_eq!(again, Outcome::default());
|
||||||
|
// The owner later drops a file of that name in: it is theirs now, not migrated again.
|
||||||
|
fs::write(store.dir().join("wb-focus.plugin.js"), "mine now").unwrap();
|
||||||
|
store.set_enabled("wb-focus.plugin.js", true).unwrap();
|
||||||
|
// A later version supersedes more files: only the new rows are handled.
|
||||||
|
let later = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty()); Ok(()) }).unwrap();
|
||||||
|
assert_eq!(later.removed, ["wb-keys.plugin.js"]);
|
||||||
|
assert!(store.is_enabled("wb-focus.plugin.js") && exists(&store, "wb-focus.plugin.js"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failure_or_crash_between_steps_is_repeated_safely() {
|
||||||
|
// The flags could not be saved: nothing changed, and the next start tries again.
|
||||||
|
let (_root, store) = upgraded();
|
||||||
|
assert!(store.migrate_superseded(TABLE, |_| Err("DISK: full".into())).is_err());
|
||||||
|
assert!(exists(&store, "wb-focus.plugin.js") && store.is_enabled("wb-focus.plugin.js"));
|
||||||
|
assert!(!store.dir().join(MARKER_FILE).exists());
|
||||||
|
let retry = store.migrate_superseded(TABLE, |_| Ok(())).unwrap();
|
||||||
|
assert_eq!(retry.flags_on, ["navigation.focusMode"]);
|
||||||
|
|
||||||
|
// A crash after the flags were saved and the enabled list rewritten, before the files went
|
||||||
|
// and the marker was written: the flag is already on (saved), so the rerun only cleans up.
|
||||||
|
let (_root, store) = upgraded();
|
||||||
|
let enabled: BTreeSet<&str> = ["wb-edited.plugin.js", "mine.plugin.js", "wb-stays.plugin.js"].into();
|
||||||
|
fs::write(store.dir().join(STATE_FILE), serde_json::to_string(&enabled).unwrap()).unwrap();
|
||||||
|
let rerun = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty(), "flags are only ever turned on, never off"); Ok(()) }).unwrap();
|
||||||
|
assert_eq!(rerun.removed, ["wb-focus.plugin.js", "wb-keys.plugin.js"]);
|
||||||
|
assert!(!exists(&store, "wb-focus.plugin.js"));
|
||||||
|
|
||||||
|
// A crash after the files went, before the marker: the rerun finds nothing and writes it.
|
||||||
|
let (_root, store) = upgraded();
|
||||||
|
store.migrate_superseded(TABLE, |_| Ok(())).unwrap();
|
||||||
|
fs::remove_file(store.dir().join(MARKER_FILE)).unwrap();
|
||||||
|
let rerun = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty()); Ok(()) }).unwrap();
|
||||||
|
assert_eq!((rerun.removed.len(), rerun.kept), (0, vec!["wb-edited.plugin.js".to_owned()]));
|
||||||
|
assert!(store.is_enabled("wb-edited.plugin.js"));
|
||||||
|
assert_eq!(marker(store.dir()).len(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_fresh_install_has_nothing_to_move() {
|
||||||
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let store = PluginStore::new(root.path().join("plugins"), &HOST);
|
||||||
|
store.ensure().unwrap();
|
||||||
|
let outcome = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty()); Ok(()) }).unwrap();
|
||||||
|
assert_eq!(outcome, Outcome::default());
|
||||||
|
assert_eq!(marker(store.dir()).len(), 4);
|
||||||
|
let listed: Vec<String> = store.list().unwrap().into_iter().map(|plugin| plugin.file).collect();
|
||||||
|
assert_eq!(listed, ["wb-stays.plugin.js"], "only what the app ships now");
|
||||||
|
assert!(store.start_scripts().is_empty(), "plugin files stay off until the owner turns them on");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stale_enabled_entry_of_a_deleted_file_goes() {
|
||||||
|
let (_root, store) = upgraded();
|
||||||
|
let enabled: BTreeSet<&str> = ["wb-deleted.plugin.js", "mine.plugin.js"].into();
|
||||||
|
fs::write(store.dir().join(STATE_FILE), serde_json::to_string(&enabled).unwrap()).unwrap();
|
||||||
|
let outcome = store.migrate_superseded(TABLE, |_| Ok(())).unwrap();
|
||||||
|
assert!(outcome.flags_on.is_empty(), "a file the owner deleted does not turn its flag on");
|
||||||
|
assert!(!store.is_enabled("wb-deleted.plugin.js") && store.is_enabled("mine.plugin.js"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_backup_with_old_names_turns_into_flags_unless_it_carries_an_edited_copy() {
|
||||||
|
let enabled = vec!["wb-focus.plugin.js".to_owned(), "mine.plugin.js".to_owned(), "wb-edited.plugin.js".to_owned(), "wb-focus.plugin.js".to_owned()];
|
||||||
|
let files = vec!["mine.plugin.js".to_owned(), "wb-edited.plugin.js".to_owned()];
|
||||||
|
let (keep, flags_on) = map_backup(enabled, &files, TABLE);
|
||||||
|
assert_eq!(keep, ["mine.plugin.js", "wb-edited.plugin.js"]);
|
||||||
|
assert_eq!(flags_on, ["navigation.focusMode"]);
|
||||||
|
let (keep, flags_on) = map_backup(vec!["other.plugin.js".into()], &[], TABLE);
|
||||||
|
assert_eq!((keep.len(), flags_on.len()), (1, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -96,9 +96,16 @@ pub fn links_script(site: &SiteSpec, settings: &ShellSettings) -> String {
|
||||||
tabs::deliver_script(site.runtime_global, "links", "configure", "__btLinks", &links.to_string())
|
tabs::deliver_script(site.runtime_global, "links", "configure", "__btLinks", &links.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Flags a store may hold. It was 64 while every flag was a page tweak; area plugins carry a flag
|
||||||
|
/// per feature. The map is stored sparsely (only values that differ from the app's defaults), so a
|
||||||
|
/// backup written by this version normally still fits an older app's limit of 64.
|
||||||
|
pub const MAX_FEATURES: usize = 256;
|
||||||
|
/// Characters in a flag key.
|
||||||
|
pub const MAX_FEATURE_KEY: usize = 64;
|
||||||
|
|
||||||
/// Feature flags are booleans only, in a small map; the page normalizes them again before use.
|
/// 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> {
|
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()) {
|
if features.len() > MAX_FEATURES || features.iter().any(|(key, value)| key.is_empty() || key.len() > MAX_FEATURE_KEY || !value.is_boolean()) {
|
||||||
return Err("VALIDATION: features must be a small map of booleans".into());
|
return Err("VALIDATION: features must be a small map of booleans".into());
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
@ -175,7 +182,13 @@ mod tests {
|
||||||
assert!(validate_features(&map(json!({ "a": "yes" }))).is_err());
|
assert!(validate_features(&map(json!({ "a": "yes" }))).is_err());
|
||||||
let long: Map<String, Value> = [("x".repeat(65), Value::Bool(true))].into_iter().collect();
|
let long: Map<String, Value> = [("x".repeat(65), Value::Bool(true))].into_iter().collect();
|
||||||
assert!(validate_features(&long).is_err());
|
assert!(validate_features(&long).is_err());
|
||||||
let many: Map<String, Value> = (0..65).map(|n| (format!("f{n}"), Value::Bool(true))).collect();
|
// What an older app wrote (at most 64 flags, the whole map) still imports; the cap is 256 now.
|
||||||
|
let old: Map<String, Value> = (0..64).map(|n| (format!("f{n}"), Value::Bool(n % 2 == 0))).collect();
|
||||||
|
assert!(validate_features(&old).is_ok());
|
||||||
|
let full: Map<String, Value> = (0..MAX_FEATURES).map(|n| (format!("area{n}.feature"), Value::Bool(true))).collect();
|
||||||
|
assert!(validate_features(&full).is_ok());
|
||||||
|
let many: Map<String, Value> = (0..=MAX_FEATURES).map(|n| (format!("f{n}"), Value::Bool(true))).collect();
|
||||||
assert!(validate_features(&many).is_err());
|
assert!(validate_features(&many).is_err());
|
||||||
|
assert!(validate_features(&map(json!({ "": true }))).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -515,6 +515,7 @@ mod tests {
|
||||||
css_element_id: "wb-test-css",
|
css_element_id: "wb-test-css",
|
||||||
example: None,
|
example: None,
|
||||||
bundled: &[],
|
bundled: &[],
|
||||||
|
superseded: &[],
|
||||||
};
|
};
|
||||||
|
|
||||||
const THEME: &[u8] = br#"{"name":"Nord","author":"me","css":"a{}"}"#;
|
const THEME: &[u8] = br#"{"name":"Nord","author":"me","css":"a{}"}"#;
|
||||||
|
|
|
||||||
|
|
@ -153,7 +153,7 @@ export const HOST_COMMANDS = {
|
||||||
shell: [
|
shell: [
|
||||||
'tabs_sync', 'tab_navigate', 'tab_action', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu',
|
'tabs_sync', 'tab_navigate', 'tab_action', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu',
|
||||||
'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set',
|
'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set',
|
||||||
'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'settings_get', 'settings_set',
|
'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'mode_get', 'mode_set', 'settings_get', 'settings_set',
|
||||||
],
|
],
|
||||||
tab: ['tab_shortcut', 'tab_link_drag'],
|
tab: ['tab_shortcut', 'tab_link_drag'],
|
||||||
site: ['open_panel'],
|
site: ['open_panel'],
|
||||||
|
|
@ -384,6 +384,8 @@ function pluginsRs(o) {
|
||||||
' example: Some(("example.plugin.js", include_str!("../../plugins/example.plugin.js"))),',
|
' example: Some(("example.plugin.js", include_str!("../../plugins/example.plugin.js"))),',
|
||||||
' // First-party plugins shipped with the app: written disabled, upgraded only while untouched.',
|
' // First-party plugins shipped with the app: written disabled, upgraded only while untouched.',
|
||||||
' bundled: &[],',
|
' bundled: &[],',
|
||||||
|
' // Plugin files a later version turned into feature flags (waybetter_host::plugins::migrate).',
|
||||||
|
' superseded: &[],',
|
||||||
'};',
|
'};',
|
||||||
'',
|
'',
|
||||||
'#[cfg(test)]',
|
'#[cfg(test)]',
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue