Nacre/src/store/scripts.rs
2026-11-11 17:27:07 -06:00

255 lines
9.1 KiB
Rust

//! User scripts and user styles: Nacre's stand-in for extensions (Servo cannot run Chrome
//! extensions). Scripts use the userscript header everyone knows:
//!
//! ```text
//! // ==UserScript==
//! // @name Example
//! // @match https://*.example.com/*
//! // @exclude https://example.com/private/*
//! // @run-at document-end
//! // ==/UserScript==
//! ```
//!
//! Styles use the same header inside a CSS comment (`/* ==UserStyle== ... */`) with `@match` too.
//! Servo injects user content into every page, so each one is wrapped in a URL check.
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::util;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
Script,
Style,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunAt {
DocumentStart,
DocumentEnd,
DocumentIdle,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct UserContent {
pub id: u64,
pub kind: Kind,
pub enabled: bool,
pub source: String,
/// Where it was installed from (for updates), or "".
#[serde(default)]
pub origin_url: String,
#[serde(default)]
pub installed: u64,
}
/// What the header says.
#[derive(Clone, Debug, PartialEq)]
pub struct Header {
pub name: String,
pub description: String,
pub version: String,
pub matches: Vec<String>,
pub excludes: Vec<String>,
pub run_at: RunAt,
}
impl UserContent {
pub fn header(&self) -> Header {
parse_header(&self.source, self.kind)
}
}
pub fn parse_header(source: &str, kind: Kind) -> Header {
let (open, close) = match kind {
Kind::Script => ("==UserScript==", "==/UserScript=="),
Kind::Style => ("==UserStyle==", "==/UserStyle=="),
};
let mut header = Header { name: String::new(), description: String::new(), version: String::new(), matches: Vec::new(), excludes: Vec::new(), run_at: RunAt::DocumentEnd };
let mut inside = false;
for line in source.lines() {
let line = line.trim().trim_start_matches("//").trim_start_matches("/*").trim_start_matches('*').trim();
if line.contains(open) {
inside = true;
continue;
}
if line.contains(close) {
break;
}
if !inside {
continue;
}
let Some(rest) = line.strip_prefix('@') else { continue };
let (key, value) = rest.split_once(char::is_whitespace).map(|(k, v)| (k, v.trim())).unwrap_or((rest, ""));
match key {
"name" => header.name = value.to_owned(),
"description" => header.description = value.to_owned(),
"version" => header.version = value.to_owned(),
"match" | "include" => header.matches.push(value.to_owned()),
"exclude" | "exclude-match" => header.excludes.push(value.to_owned()),
"run-at" => {
header.run_at = match value {
"document-start" => RunAt::DocumentStart,
"document-idle" => RunAt::DocumentIdle,
_ => RunAt::DocumentEnd,
}
},
_ => {},
}
}
if header.name.is_empty() {
header.name = match kind {
Kind::Script => "Untitled script".to_owned(),
Kind::Style => "Untitled style".to_owned(),
};
}
if header.matches.is_empty() {
header.matches.push("*://*/*".to_owned());
}
header
}
/// Turn a match pattern (`https://*.example.com/*`, `*://*/*`, `<all_urls>`, or a glob) into a
/// JavaScript regular expression source.
pub fn pattern_to_regex(pattern: &str) -> String {
if pattern == "<all_urls>" || pattern == "*" {
return "^(https?|file):".to_owned();
}
let mut out = String::from("^");
let (scheme, rest) = pattern.split_once("://").unwrap_or(("*", pattern));
out.push_str(&if scheme == "*" { "https?".to_owned() } else { escape_regex(scheme) });
out.push_str(":\\/\\/");
let (host, path) = match rest.find('/') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, "/*"),
};
if host == "*" {
out.push_str("[^/]*");
} else if let Some(domain) = host.strip_prefix("*.") {
out.push_str("([^/]*\\.)?");
out.push_str(&escape_regex(domain));
} else {
out.push_str(&escape_regex(host).replace("\\*", "[^/]*"));
}
out.push_str(&escape_regex(path).replace("\\*", ".*"));
out.push('$');
out
}
fn escape_regex(text: &str) -> String {
let mut out = String::with_capacity(text.len() * 2);
for c in text.chars() {
if "\\^$.|?*+()[]{}/".contains(c) {
out.push('\\');
}
out.push(c);
}
out
}
/// JavaScript that runs `body` only on matching pages and at the right time. Servo user scripts
/// run before the page's own scripts, which is "document-start".
pub fn wrap_for_page(item: &UserContent) -> String {
let header = item.header();
let matches: Vec<String> = header.matches.iter().map(|p| util::js_string(&pattern_to_regex(p))).collect();
let excludes: Vec<String> = header.excludes.iter().map(|p| util::js_string(&pattern_to_regex(p))).collect();
let check = format!(
"var __m=[{}].some(function(r){{return new RegExp(r).test(location.href)}});var __x=[{}].some(function(r){{return new RegExp(r).test(location.href)}});if(!__m||__x)return;",
matches.join(","),
excludes.join(",")
);
match item.kind {
Kind::Script => {
let run = match header.run_at {
RunAt::DocumentStart => "__run();".to_owned(),
RunAt::DocumentEnd => "if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',__run,{once:true})}else{__run()}".to_owned(),
RunAt::DocumentIdle => "if(document.readyState==='complete'){setTimeout(__run,0)}else{window.addEventListener('load',function(){setTimeout(__run,0)},{once:true})}".to_owned(),
};
format!(
"(function(){{{check}function __run(){{try{{(function(){{\n{}\n}})()}}catch(e){{console.error('[user script {}]',e)}}}}{run}}})();",
item.source,
header.name.replace(['\'', '\\', '\n'], " ")
)
},
Kind::Style => {
// Strip the header comment, then add the CSS as a <style> as early as possible.
format!(
"(function(){{{check}var css={};function add(){{var s=document.createElement('style');s.dataset.nacreUserStyle='{}';s.textContent=css;(document.head||document.documentElement).appendChild(s)}}if(document.documentElement){{add()}}else{{document.addEventListener('readystatechange',add,{{once:true}})}}}})();",
util::js_string(&item.source),
item.id
)
},
}
}
pub struct Scripts {
path: PathBuf,
pub items: Vec<UserContent>,
read_only: bool,
}
impl Scripts {
pub fn load(path: PathBuf, read_only: bool) -> Scripts {
let items = util::load_json(&path);
Scripts { path, items, read_only }
}
pub fn add(&mut self, kind: Kind, source: &str, origin_url: &str) -> u64 {
let id = self.items.iter().map(|i| i.id).max().unwrap_or(0) + 1;
// Installing the same script again replaces it.
let name = parse_header(source, kind).name;
self.items.retain(|i| !(i.kind == kind && i.header().name == name && (origin_url.is_empty() || i.origin_url == origin_url)));
self.items.push(UserContent { id, kind, enabled: true, source: source.to_owned(), origin_url: origin_url.to_owned(), installed: util::now() });
self.save();
id
}
pub fn set_source(&mut self, id: u64, source: &str) {
if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
item.source = source.to_owned();
}
self.save();
}
pub fn set_enabled(&mut self, id: u64, enabled: bool) {
if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
item.enabled = enabled;
}
self.save();
}
pub fn remove(&mut self, id: u64) {
self.items.retain(|i| i.id != id);
self.save();
}
/// JavaScript for every enabled item.
pub fn page_scripts(&self) -> Vec<String> {
self.items.iter().filter(|i| i.enabled).map(wrap_for_page).collect()
}
fn save(&self) {
if !self.read_only && let Err(error) = util::save_json(&self.path, &self.items) {
log::error!("could not save user scripts: {error}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn header_and_patterns() {
let src = "// ==UserScript==\n// @name Hello\n// @match https://*.example.com/*\n// @run-at document-start\n// ==/UserScript==\nalert(1)";
let h = parse_header(src, Kind::Script);
assert_eq!(h.name, "Hello");
assert_eq!(h.run_at, RunAt::DocumentStart);
assert_eq!(pattern_to_regex("https://*.example.com/*"), "^https:\\/\\/([^/]*\\.)?example\\.com\\/.*$");
assert_eq!(pattern_to_regex("*://*/*"), "^https?:\\/\\/[^/]*\\/.*$");
}
}