Extract the wayBetter framework core from wayBetter for X
Site-agnostic parts of the X app, behind a small site adapter: - crates/waybetter-host: webview-label security policy and tab rect clamp, account profiles with native-owned accounts (AccountRules), plugin store with bundled-plugin upgrades (PluginHost), signed data-only hotfix channel, update scheduling and crash handshake, tab payloads/link routing/tab-chrome validation, and (feature "tauri") webview helpers and the Windows system menu. - packages/runtime: DOM hub, request hub, plugin API core, OKLab theme color model, split-view rail hiding, link routing and account reporting, each configured by a SiteAdapter. - packages/shell: address bar, pane, link-drop, profile, palette and update-chip models, and window controls with the Tauri API injected. Tests moved/adapted from the app: 45 Rust (headless), 40 TypeScript.
This commit is contained in:
commit
43a9e2e1a7
48 changed files with 9768 additions and 0 deletions
382
crates/waybetter-host/src/plugins.rs
Normal file
382
crates/waybetter-host/src/plugins.rs
Normal file
|
|
@ -0,0 +1,382 @@
|
|||
//! BetterDiscord-style extensions for the site page: `*.plugin.js` files and custom CSS.
|
||||
//!
|
||||
//! Plugins are trusted by the owner who puts them in the folder. They run in the site page with
|
||||
//! full page access. Native code only reads files from its own plugins directory, never from a
|
||||
//! caller-supplied path, and the scripts it builds embed plugin data as JSON string literals.
|
||||
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const PLUGIN_SUFFIX: &str = ".plugin.js";
|
||||
pub const MAX_PLUGIN_BYTES: u64 = 2 * 1024 * 1024;
|
||||
pub const MAX_CSS_BYTES: usize = 512 * 1024;
|
||||
const STATE_FILE: &str = "enabled.json";
|
||||
const CSS_FILE: &str = "custom.css";
|
||||
/// Which first-party plugin content was last written, so upgrades never overwrite user edits.
|
||||
const BUNDLED_FILE: &str = "bundled.json";
|
||||
|
||||
/// What the plugin host needs from the app: where plugins run and what ships with it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PluginHost {
|
||||
/// The page runtime's window global; plugins register under `window.<global>.plugins`.
|
||||
pub runtime_global: &'static str,
|
||||
/// Scripts run only in the top frame of this exact origin, e.g. `https://x.com`.
|
||||
pub origin: &'static str,
|
||||
/// Console prefix, e.g. `wayBetter for X`.
|
||||
pub product: &'static str,
|
||||
/// Element id of the custom CSS `<style>`.
|
||||
pub css_element_id: &'static str,
|
||||
/// Written disabled into a freshly created plugins folder: (file name, source).
|
||||
pub example: Option<(&'static str, &'static str)>,
|
||||
/// First-party plugins, written disabled and upgraded (see [`PluginStore::install_bundled`]).
|
||||
pub bundled: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
fn content_hash(bytes: &[u8]) -> String {
|
||||
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScriptPlugin {
|
||||
pub file: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub version: String,
|
||||
pub author: String,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// A plugin file name must be a bare `name.plugin.js` inside the plugins directory.
|
||||
pub fn valid_file_name(file: &str) -> bool {
|
||||
file.len() > PLUGIN_SUFFIX.len()
|
||||
&& file.len() <= 128
|
||||
&& file.ends_with(PLUGIN_SUFFIX)
|
||||
&& !file.starts_with('.')
|
||||
&& file
|
||||
.bytes()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || b"_-. ".contains(&ch))
|
||||
}
|
||||
|
||||
/// Reads `@name`, `@description`, `@version` and `@author` from the leading `/** … */` block.
|
||||
pub fn parse_meta(file: &str, source: &str) -> ScriptPlugin {
|
||||
let mut plugin = ScriptPlugin {
|
||||
file: file.to_owned(),
|
||||
name: file.trim_end_matches(PLUGIN_SUFFIX).to_owned(),
|
||||
description: String::new(),
|
||||
version: String::new(),
|
||||
author: String::new(),
|
||||
enabled: false,
|
||||
};
|
||||
let trimmed = source.trim_start_matches('\u{feff}').trim_start();
|
||||
let Some(body) = trimmed.strip_prefix("/**") else {
|
||||
return plugin;
|
||||
};
|
||||
let Some(end) = body.find("*/") else {
|
||||
return plugin;
|
||||
};
|
||||
for line in body[..end].lines() {
|
||||
let line = line.trim().trim_start_matches('*').trim();
|
||||
let Some(rest) = line.strip_prefix('@') else {
|
||||
continue;
|
||||
};
|
||||
let (key, value) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
|
||||
let value: String = value.trim().chars().filter(|ch| !ch.is_control()).take(300).collect();
|
||||
match key {
|
||||
"name" if !value.is_empty() => plugin.name = value,
|
||||
"description" => plugin.description = value,
|
||||
"version" => plugin.version = value,
|
||||
"author" => plugin.author = value,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
plugin
|
||||
}
|
||||
|
||||
pub struct PluginStore {
|
||||
dir: PathBuf,
|
||||
host: &'static PluginHost,
|
||||
}
|
||||
|
||||
impl PluginStore {
|
||||
pub fn new(dir: PathBuf, host: &'static PluginHost) -> Self {
|
||||
Self { dir, host }
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
pub fn host(&self) -> &'static PluginHost {
|
||||
self.host
|
||||
}
|
||||
|
||||
/// Creates the folder; on first creation also writes the disabled example plugin. Every call
|
||||
/// installs or upgrades the first-party plugins (see [`Self::install_bundled`]).
|
||||
pub fn ensure(&self) -> Result<(), String> {
|
||||
let fresh = !self.dir.exists();
|
||||
fs::create_dir_all(&self.dir).map_err(|error| format!("PLUGINS: {error}"))?;
|
||||
if fresh {
|
||||
if let Some((file, source)) = self.host.example {
|
||||
let _ = fs::write(self.dir.join(file), source);
|
||||
}
|
||||
}
|
||||
self.install_bundled(self.host.bundled);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes first-party plugins without ever enabling them or touching the owner's work:
|
||||
/// - missing and never installed: written (first run, or a plugin new in this version);
|
||||
/// - missing but installed before: the owner deleted it, so it stays deleted;
|
||||
/// - present and byte-identical to what was last installed: upgraded to the shipped content;
|
||||
/// - present with any other content (edited, or an unrelated file of that name): left alone.
|
||||
pub fn install_bundled(&self, bundled: &[(&str, &str)]) {
|
||||
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 before = manifest.clone();
|
||||
for (file, source) in bundled {
|
||||
if !valid_file_name(file) {
|
||||
continue;
|
||||
}
|
||||
let path = self.dir.join(file);
|
||||
let shipped = content_hash(source.as_bytes());
|
||||
let installed = manifest.get(*file).cloned();
|
||||
match fs::read(&path) {
|
||||
Err(_) if installed.is_none() => {
|
||||
if fs::write(&path, source).is_ok() {
|
||||
manifest.insert((*file).to_owned(), shipped);
|
||||
}
|
||||
}
|
||||
Err(_) => {}
|
||||
Ok(current) => {
|
||||
let current = content_hash(¤t);
|
||||
if current == shipped {
|
||||
manifest.insert((*file).to_owned(), shipped);
|
||||
} else if installed.as_deref() == Some(current.as_str()) && fs::write(&path, source).is_ok() {
|
||||
manifest.insert((*file).to_owned(), shipped);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if manifest != before {
|
||||
if let Ok(json) = serde_json::to_string_pretty(&manifest) {
|
||||
let _ = fs::write(manifest_path, json);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled_set(&self) -> BTreeSet<String> {
|
||||
fs::read_to_string(self.dir.join(STATE_FILE))
|
||||
.ok()
|
||||
.and_then(|raw| serde_json::from_str::<BTreeSet<String>>(&raw).ok())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|file| valid_file_name(file))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_source(&self, file: &str) -> Result<String, String> {
|
||||
if !valid_file_name(file) {
|
||||
return Err("VALIDATION: invalid plugin file name".into());
|
||||
}
|
||||
let path = self.dir.join(file);
|
||||
let meta = fs::metadata(&path).map_err(|_| "PLUGINS: plugin file not found")?;
|
||||
if !meta.is_file() || meta.len() > MAX_PLUGIN_BYTES {
|
||||
return Err("PLUGINS: plugin must be a regular file under 2 MiB".into());
|
||||
}
|
||||
fs::read_to_string(&path).map_err(|_| "PLUGINS: plugin must be UTF-8 text".into())
|
||||
}
|
||||
|
||||
pub fn list(&self) -> Result<Vec<ScriptPlugin>, String> {
|
||||
self.ensure()?;
|
||||
let enabled = self.enabled_set();
|
||||
let mut plugins = Vec::new();
|
||||
for entry in fs::read_dir(&self.dir).map_err(|error| format!("PLUGINS: {error}"))? {
|
||||
let Ok(entry) = entry else { continue };
|
||||
let Some(file) = entry.file_name().to_str().map(str::to_owned) else {
|
||||
continue;
|
||||
};
|
||||
if !valid_file_name(&file) {
|
||||
continue;
|
||||
}
|
||||
let Ok(source) = self.read_source(&file) else {
|
||||
continue;
|
||||
};
|
||||
let mut plugin = parse_meta(&file, &source);
|
||||
plugin.enabled = enabled.contains(&file);
|
||||
plugins.push(plugin);
|
||||
}
|
||||
plugins.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
Ok(plugins)
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, file: &str, enabled: bool) -> Result<(), String> {
|
||||
self.read_source(file)?;
|
||||
let mut set = self.enabled_set();
|
||||
if enabled {
|
||||
set.insert(file.to_owned());
|
||||
} else {
|
||||
set.remove(file);
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&set).map_err(|_| "PLUGINS: serialization failed")?;
|
||||
fs::write(self.dir.join(STATE_FILE), json).map_err(|error| format!("PLUGINS: {error}"))
|
||||
}
|
||||
|
||||
/// Start scripts for every enabled plugin, in name order.
|
||||
pub fn start_scripts(&self) -> Vec<String> {
|
||||
let enabled = self.enabled_set();
|
||||
enabled
|
||||
.iter()
|
||||
.filter_map(|file| self.start_script(file).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn start_script(&self, file: &str) -> Result<String, String> {
|
||||
let source = self.read_source(file)?;
|
||||
start_script(self.host, file, &source)
|
||||
}
|
||||
|
||||
pub fn css(&self) -> String {
|
||||
fs::read_to_string(self.dir.join(CSS_FILE)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn set_css(&self, css: &str) -> Result<(), String> {
|
||||
if css.len() > MAX_CSS_BYTES {
|
||||
return Err("VALIDATION: custom CSS is limited to 512 KiB".into());
|
||||
}
|
||||
self.ensure()?;
|
||||
fs::write(self.dir.join(CSS_FILE), css).map_err(|error| format!("PLUGINS: {error}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn js_string(value: &str) -> Result<String, String> {
|
||||
serde_json::to_string(value).map_err(|_| "PLUGINS: serialization failed".into())
|
||||
}
|
||||
|
||||
/// Wraps a CommonJS-style plugin (`module.exports = class { start() {} stop() {} }`).
|
||||
/// Native code evaluates the result in the site tab, so the page's CSP does not block it.
|
||||
pub fn start_script(host: &PluginHost, file: &str, source: &str) -> Result<String, String> {
|
||||
let id = js_string(file)?;
|
||||
let PluginHost { runtime_global: global, origin, product, .. } = host;
|
||||
Ok(format!(
|
||||
"(()=>{{const XW=window.{global};if(!XW||window.top!==window||location.origin!=='{origin}')return;\
|
||||
const id={id};if(XW.plugins[id])return;\
|
||||
try{{const module={{exports:{{}}}};const exports=module.exports;\
|
||||
(function(module,exports){{\n{source}\n}})(module,exports);\
|
||||
let P=module.exports&&module.exports.default?module.exports.default:module.exports;\
|
||||
const inst=typeof P==='function'?(P.prototype&&(P.prototype.start||P.prototype.stop)?new P():P()):P;\
|
||||
XW.plugins[id]=inst||{{}};delete XW.errors[id];if(inst&&typeof inst.start==='function')inst.start();\
|
||||
console.info('[{product}] started',id);}}\
|
||||
catch(e){{XW.errors[id]=String(e&&e.stack||e);console.error('[{product}] plugin failed',id,e);}}}})();"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn stop_script(host: &PluginHost, file: &str) -> Result<String, String> {
|
||||
let id = js_string(file)?;
|
||||
let PluginHost { runtime_global: global, product, .. } = host;
|
||||
Ok(format!(
|
||||
"(()=>{{const XW=window.{global};if(!XW)return;const id={id};const p=XW.plugins[id];\
|
||||
if(!p)return;delete XW.plugins[id];\
|
||||
try{{if(typeof p.stop==='function')p.stop();console.info('[{product}] stopped',id);}}\
|
||||
catch(e){{console.error('[{product}] plugin stop failed',id,e);}}}})();"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn css_script(host: &PluginHost, css: &str) -> Result<String, String> {
|
||||
let css = js_string(css)?;
|
||||
let PluginHost { origin, css_element_id, .. } = host;
|
||||
Ok(format!(
|
||||
"(()=>{{if(window.top!==window||location.origin!=='{origin}')return;\
|
||||
const id='{css_element_id}';let s=document.getElementById(id);\
|
||||
if(!s){{s=document.createElement('style');s.id=id;(document.head||document.documentElement).appendChild(s);}}\
|
||||
s.textContent={css};}})();"
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
static HOST: PluginHost = PluginHost {
|
||||
runtime_global: "Demo",
|
||||
origin: "https://site.test",
|
||||
product: "wayBetter for Test",
|
||||
css_element_id: "demo-css",
|
||||
example: Some(("example.plugin.js", "/**\n * @name Example\n */\nmodule.exports = class { start(){} stop(){} };")),
|
||||
bundled: &[("wb-one.plugin.js", "/** @name One */ module.exports = {};")],
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn plugin_file_names_cannot_escape_the_plugins_folder() {
|
||||
assert!(valid_file_name("hide-trends.plugin.js"));
|
||||
assert!(valid_file_name("My Plugin.plugin.js"));
|
||||
for bad in ["../x.plugin.js", "a/b.plugin.js", r"a\b.plugin.js", ".plugin.js", ".hidden.plugin.js", "x.js", "C:x.plugin.js", ""] {
|
||||
assert!(!valid_file_name(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meta_header_is_parsed_and_defaults_to_file_name() {
|
||||
let source = "/**\n * @name Hide Trends\n * @description Hides trends\n * @version 1.2.0\n * @author Someone\n */\nmodule.exports = class {};";
|
||||
let plugin = parse_meta("hide.plugin.js", source);
|
||||
assert_eq!((plugin.name.as_str(), plugin.description.as_str(), plugin.version.as_str()), ("Hide Trends", "Hides trends", "1.2.0"));
|
||||
assert_eq!(plugin.author, "Someone");
|
||||
assert_eq!(parse_meta("bare.plugin.js", "module.exports = {}").name, "bare");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_lists_toggles_and_persists_css() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = PluginStore::new(root.path().join("plugins"), &HOST);
|
||||
let listed = store.list().unwrap();
|
||||
assert_eq!(listed.len(), 2, "fresh folder gets the example and the bundled plugin");
|
||||
assert!(listed.iter().all(|plugin| !plugin.enabled));
|
||||
store.set_enabled("example.plugin.js", true).unwrap();
|
||||
assert_eq!(store.start_scripts().len(), 1);
|
||||
assert!(store.set_enabled("../escape.plugin.js", true).is_err());
|
||||
store.set_enabled("example.plugin.js", false).unwrap();
|
||||
assert!(store.start_scripts().is_empty());
|
||||
store.set_css("body{color:red}").unwrap();
|
||||
assert_eq!(store.css(), "body{color:red}");
|
||||
assert!(store.set_css(&"a".repeat(MAX_CSS_BYTES + 1)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_plugins_upgrade_only_untouched_copies() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = PluginStore::new(root.path().to_path_buf(), &HOST);
|
||||
let path = root.path().join("wb-a.plugin.js");
|
||||
store.install_bundled(&[("wb-a.plugin.js", "v1")]);
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "v1");
|
||||
store.install_bundled(&[("wb-a.plugin.js", "v2")]);
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "v2", "untouched copy is upgraded");
|
||||
fs::write(&path, "mine").unwrap();
|
||||
store.install_bundled(&[("wb-a.plugin.js", "v3")]);
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "mine", "edited copy is left alone");
|
||||
fs::remove_file(&path).unwrap();
|
||||
store.install_bundled(&[("wb-a.plugin.js", "v4")]);
|
||||
assert!(!path.exists(), "a deleted bundled plugin stays deleted");
|
||||
let foreign = root.path().join("wb-b.plugin.js");
|
||||
fs::write(&foreign, "foreign").unwrap();
|
||||
store.install_bundled(&[("wb-b.plugin.js", "shipped")]);
|
||||
assert_eq!(fs::read_to_string(&foreign).unwrap(), "foreign", "a foreign file of that name is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_are_scoped_to_the_site_and_embed_data_as_literals() {
|
||||
let start = start_script(&HOST, "a\"b.plugin.js", "module.exports = {}").unwrap();
|
||||
assert!(start.starts_with("(()=>{const XW=window.Demo;if(!XW||window.top!==window||location.origin!=='https://site.test')return;"));
|
||||
assert!(start.contains(r#"const id="a\"b.plugin.js";"#));
|
||||
assert!(start.contains("[wayBetter for Test] started"));
|
||||
let stop = stop_script(&HOST, "x.plugin.js").unwrap();
|
||||
assert!(stop.contains("window.Demo") && stop.contains("[wayBetter for Test] stopped"));
|
||||
let css = css_script(&HOST, "</style><script>").unwrap();
|
||||
assert!(css.contains("const id='demo-css'") && css.contains(r#"s.textContent="</style><script>";"#));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue