//! Plugin commands in the shell's command palette. //! //! A site tab may report the palette commands its plugins registered (`api.commands.register`, //! waybetter runtime `commands.ts`) as `{ id, title, keywords }` strings about itself. The app //! accepts them only from `tab-*` webviews that are on the site right now ([`SiteSpec::is_origin`]), //! validates and caps them here, keeps them per tab (a new page load clears them) and forwards them //! to the shell. Running one is a shell-only app command: native code checks the command is one this //! tab reported and asks that tab's page to `run` it ([`run_script`]); the command's code only ever //! runs in the page. use crate::site::SiteSpec; use serde::{Deserialize, Serialize}; pub const MAX_COMMANDS: usize = 48; pub const MAX_TITLE: usize = 80; pub const MAX_KEYWORDS: usize = 160; const MAX_COMMAND_ID: usize = 64; /// Shell event carrying `{ id, commands }` for one tab. pub const EVENT: &str = "tab-commands"; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct PaletteCommand { pub id: String, pub title: String, #[serde(default)] pub keywords: String, } /// `:`: the owner is `_` or a plugin file name (`valid_file_name`), the command id /// letters, digits, `.`, `_`, `-` (1–64, starting with a letter or digit). pub fn valid_command_id(id: &str) -> bool { let Some((owner, command)) = id.split_once(':') else { return false }; let owner_ok = owner == "_" || super::valid_file_name(owner); let command_ok = !command.is_empty() && command.len() <= MAX_COMMAND_ID && command.as_bytes()[0].is_ascii_alphanumeric() && command.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)); owner_ok && command_ok } fn plain(text: &str, max: usize, required: bool) -> bool { let count = text.chars().count(); count <= max && (!required || !text.trim().is_empty()) && !text.chars().any(char::is_control) } /// The list a tab reported, validated as a whole: any bad entry rejects the report. pub fn validate(list: Vec) -> Result, String> { if list.len() > MAX_COMMANDS { return Err(format!("VALIDATION: at most {MAX_COMMANDS} palette commands per tab")); } let mut seen: Vec<&str> = Vec::new(); for command in &list { if !valid_command_id(&command.id) || seen.contains(&command.id.as_str()) { return Err("VALIDATION: invalid palette command id".into()); } if !plain(&command.title, MAX_TITLE, true) || !plain(&command.keywords, MAX_KEYWORDS, false) { return Err("VALIDATION: palette command titles are 1-80 and keywords at most 160 plain characters".into()); } seen.push(&command.id); } Ok(list) } /// The page script that runs command `id` (already checked against the tab's list) in a site tab: /// it does nothing unless the page is the top frame on the site's primary origin. pub fn run_script(site: &SiteSpec, id: &str) -> Result { if !valid_command_id(id) { return Err("VALIDATION: invalid palette command id".into()); } let id = serde_json::to_string(id).map_err(|_| "VALIDATION: invalid palette command id")?; let (global, origin) = (site.runtime_global, site.primary_origin()); Ok(format!( "(()=>{{const W=window.{global};const C=W&&W.api&&W.api.commands;\ if(window.top===window&&location.origin==='{origin}'&&C&&typeof C.run==='function')C.run({id});}})();" )) } #[cfg(test)] mod tests { use super::*; use crate::site::testing::SITE; fn command(id: &str, title: &str) -> PaletteCommand { PaletteCommand { id: id.into(), title: title.into(), keywords: "focus hide".into() } } #[test] fn accepts_plugin_owned_ids_titles_and_keywords_only() { let list = vec![command("bt-focus-mode.plugin.js:toggle", "Focus Mode: toggle"), command("_:later", "Later")]; assert_eq!(validate(list.clone()).unwrap(), list); assert!(validate(Vec::new()).unwrap().is_empty(), "an empty list clears the tab's commands"); // Only the three string fields exist on the wire. let extra = serde_json::from_value::(serde_json::json!({ "id": "_:a", "title": "A", "keywords": "", "run": "alert(1)" })); assert!(extra.is_err()); } #[test] fn rejects_bad_ids_long_or_control_text_duplicates_and_too_many() { for id in ["toggle", ":toggle", "_:", "../x.plugin.js:a", "x.js:a", "_:-a", "_:has space", "_:a:b", &format!("_:{}", "a".repeat(65))] { assert!(validate(vec![command(id, "T")]).is_err(), "{id}"); } assert!(validate(vec![command("_:a", "")]).is_err()); assert!(validate(vec![command("_:a", " ")]).is_err()); assert!(validate(vec![command("_:a", &"t".repeat(MAX_TITLE + 1))]).is_err()); assert!(validate(vec![command("_:a", "line\nbreak")]).is_err()); assert!(validate(vec![PaletteCommand { keywords: "k".repeat(MAX_KEYWORDS + 1), ..command("_:a", "A") }]).is_err()); assert!(validate(vec![command("_:a", "A"), command("_:a", "B")]).is_err()); let many = (0..=MAX_COMMANDS).map(|n| command(&format!("_:c{n}"), "T")).collect(); assert!(validate(many).is_err()); } #[test] fn run_script_embeds_the_id_as_a_literal_and_stays_on_the_site() { let script = run_script(&SITE, "bt-focus-mode.plugin.js:toggle").unwrap(); assert!(script.contains(r#"C.run("bt-focus-mode.plugin.js:toggle")"#)); assert!(script.contains("const W=window.BetterTwttr;")); assert!(script.contains("location.origin==='https://x.com'")); assert!(run_script(&SITE, "_:a\");alert(1);(\"").is_err()); } }