Store: Open With (files the OS hands over) and the icons and builtin catalog kinds

Open With: store_commands keeps each existing file the OS hands over (launch
argument, a second launch forwarded by single-instance with its working
directory, a macOS file:// open-URL) under a random id (Store::receive_file:
name says what it is, regular file, size cap, 8 kept, 15 minutes) and queues
LinkEvent.opened {id, name, kind}. The shell-only install_stage_opened {id}
reads that one file once and stages it exactly like a dropped file; it takes
an id only (testkit asserts that), so the shell cannot name a path. The shell
shows the same install screen; nothing installs without it. The NSIS template
lists the app under "Open with" for the declared extensions (OpenWithProgids)
and never makes it the default program, unlike Tauri's own macro.

Catalog kinds: icons (an icon pack, *.icons.json, at most 120 KB; validate_icons,
staged and committed as text for the shell, the install screen draws every icon,
.icons.json is no longer read as a theme) and builtin (a feature the app
already has, such as an area plugin: no url, sha256, size or file; never staged;
the Store view lists it as Built in with the app's own switch via the areas
prop). Rust: Kind, CatalogItem.check, verify_item, install links refuse builtin.
JS: storeModel, installController (requestOpened, icons adapter), InstallDialog,
StoreView, StoreSection (remove an icon pack, area switches), words. CLI and
JSON Schema: kinds, optional url/sha256/size on builtin, icons size cap; the
test schema validator learns not and if/then/else. docs/STORE.md.
This commit is contained in:
CRTkafa 2026-10-01 14:23:23 +07:00
parent 1fae0a7236
commit 7091bca25d
21 changed files with 1015 additions and 90 deletions

View file

@ -1360,12 +1360,15 @@ impl App {
let builder = tauri::Builder::<Wry>::default() let builder = tauri::Builder::<Wry>::default()
// Must be first: a second launch focuses the running window instead of fighting over // Must be first: a second launch focuses the running window instead of fighting over
// the app's data and WebView profile (and hands over its link). // the app's data and WebView profile (and hands over its link).
.plugin(tauri_plugin_single_instance::init(|app, _, _| { .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
if let Some(window) = app.get_window(policy::MAIN_LABEL) { if let Some(window) = app.get_window(policy::MAIN_LABEL) {
let _ = window.unminimize(); let _ = window.unminimize();
let _ = window.show(); let _ = window.show();
let _ = window.set_focus(); let _ = window.set_focus();
} }
// A double-click or "Open with" on a file while the app runs: its path arrives here.
#[cfg(feature = "net")]
crate::store_commands::opened_args(app, &_args, &_cwd);
})); }));
// Install links (after single-instance, which forwards a second launch's link). // Install links (after single-instance, which forwards a second launch's link).
let builder = if config.deep_link { builder.plugin(tauri_plugin_deep_link::init()) } else { builder }; let builder = if config.deep_link { builder.plugin(tauri_plugin_deep_link::init()) } else { builder };

View file

@ -55,6 +55,7 @@ pub const STORE: &[&str] = &[
"install_pending", "install_pending",
"install_stage_link", "install_stage_link",
"install_stage_file", "install_stage_file",
"install_stage_opened",
"install_cancel", "install_cancel",
"install_commit", "install_commit",
"plugin_remove", "plugin_remove",

View file

@ -20,6 +20,8 @@ pub const DEFAULT_HOSTS: &[AllowedHost] = &[
/// The catalog format this code reads. Format 2: every item names the apps it is for (`apps`). /// The catalog format this code reads. Format 2: every item names the apps it is for (`apps`).
pub const CATALOG_FORMAT: u32 = 2; pub const CATALOG_FORMAT: u32 = 2;
pub const MAX_THEME_BYTES: usize = 2 * 1024 * 1024; pub const MAX_THEME_BYTES: usize = 2 * 1024 * 1024;
/// An icon pack file (the runtime's `ICON_LIMITS.packBytes`).
pub const MAX_ICONS_BYTES: usize = 120_000;
pub const MAX_CATALOG_BYTES: usize = 1024 * 1024; pub const MAX_CATALOG_BYTES: usize = 1024 * 1024;
pub const MAX_SIGNATURE_BYTES: usize = 512; pub const MAX_SIGNATURE_BYTES: usize = 512;
pub const MAX_LINK_CHARS: usize = 2048; pub const MAX_LINK_CHARS: usize = 2048;
@ -61,6 +63,11 @@ pub enum Kind {
Plugin, Plugin,
/// A string pack: data that replaces the site's own UI strings (`store::strings`). /// A string pack: data that replaces the site's own UI strings (`store::strings`).
Strings, Strings,
/// An icon pack (`*.icons.json`): path data and small drawings, never code.
Icons,
/// Catalog only: a feature that ships inside the app (an area plugin). The Store lists it as
/// built in with its switch; there is nothing to download, stage or install.
Builtin,
} }
impl Kind { impl Kind {
@ -69,7 +76,9 @@ impl Kind {
"theme" => Ok(Kind::Theme), "theme" => Ok(Kind::Theme),
"plugin" => Ok(Kind::Plugin), "plugin" => Ok(Kind::Plugin),
"strings" => Ok(Kind::Strings), "strings" => Ok(Kind::Strings),
_ => Err("VALIDATION: kind must be \"theme\", \"plugin\" or \"strings\"".into()), "icons" => Ok(Kind::Icons),
"builtin" => Ok(Kind::Builtin),
_ => Err("VALIDATION: kind must be \"theme\", \"plugin\", \"strings\", \"icons\" or \"builtin\"".into()),
} }
} }
@ -78,6 +87,8 @@ impl Kind {
Kind::Theme => "theme", Kind::Theme => "theme",
Kind::Plugin => "plugin", Kind::Plugin => "plugin",
Kind::Strings => "strings", Kind::Strings => "strings",
Kind::Icons => "icons",
Kind::Builtin => "builtin",
} }
} }
@ -86,6 +97,8 @@ impl Kind {
Kind::Theme => MAX_THEME_BYTES, Kind::Theme => MAX_THEME_BYTES,
Kind::Plugin => MAX_PLUGIN_BYTES as usize, Kind::Plugin => MAX_PLUGIN_BYTES as usize,
Kind::Strings => super::strings::MAX_STRINGS_BYTES, Kind::Strings => super::strings::MAX_STRINGS_BYTES,
Kind::Icons => MAX_ICONS_BYTES,
Kind::Builtin => 0,
} }
} }
} }
@ -163,7 +176,10 @@ pub fn parse_install_link(config: &StoreConfig, link: &str) -> Result<InstallLin
return Err("LINK: repeated parameter".into()); return Err("LINK: repeated parameter".into());
} }
} }
let kind = Kind::parse(kind.as_deref().ok_or("LINK: missing kind")?).map_err(|_| "LINK: kind must be theme or plugin")?; let kind = Kind::parse(kind.as_deref().ok_or("LINK: missing kind")?).map_err(|_| "LINK: kind must be theme, plugin, strings or icons")?;
if kind == Kind::Builtin {
return Err("LINK: built-in items cannot be installed".into());
}
let target = Url::parse(url.as_deref().ok_or("LINK: missing url")?).map_err(|_| "LINK: url is not a URL")?; let target = Url::parse(url.as_deref().ok_or("LINK: missing url")?).map_err(|_| "LINK: url is not a URL")?;
if !allowed_download_url(config.allowed_hosts, &target) { if !allowed_download_url(config.allowed_hosts, &target) {
return Err(format!("LINK: only https links on {} can be installed", hosts_text(config.allowed_hosts))); return Err(format!("LINK: only https links on {} can be installed", hosts_text(config.allowed_hosts)));
@ -244,6 +260,62 @@ pub fn validate_theme(bytes: &[u8]) -> Result<ThemeInfo, String> {
}) })
} }
/// What the confirmation screen shows about an icon pack (the shell parses the rest and draws it).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IconsInfo {
pub id: String,
pub name: String,
pub author: String,
pub license: String,
pub glyphs: usize,
}
/// An icon pack file: at most [`MAX_ICONS_BYTES`], UTF-8 JSON, an object with an `id`
/// (`[a-z0-9-]{1,40}`), a non-empty `name` and a `glyphs` object. It is data: the shell's own
/// sanitizer (`parseIconPackJson`) keeps only valid path data and small drawings.
pub fn validate_icons(bytes: &[u8]) -> Result<IconsInfo, String> {
if bytes.is_empty() {
return Err("VALIDATION: the icon pack file is empty".into());
}
if bytes.len() > MAX_ICONS_BYTES {
return Err("VALIDATION: icon packs are limited to 120 KB".into());
}
let text = std::str::from_utf8(bytes).map_err(|_| "VALIDATION: an icon pack must be UTF-8 JSON")?;
let value: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|_| "VALIDATION: this file is not valid JSON")?;
let object = value.as_object().ok_or("VALIDATION: an icon pack is a JSON object")?;
let id = object.get("id").and_then(serde_json::Value::as_str).unwrap_or_default();
if !valid_id(id) {
return Err("VALIDATION: an icon pack needs an \"id\" of lowercase letters, digits and dashes".into());
}
let name = short(object.get("name"), 60);
if name.trim().is_empty() {
return Err("VALIDATION: an icon pack needs a \"name\"".into());
}
let glyphs = object.get("glyphs").and_then(serde_json::Value::as_object).map(|glyphs| glyphs.len()).unwrap_or(0);
if glyphs == 0 {
return Err("VALIDATION: an icon pack needs a \"glyphs\" object with at least one icon".into());
}
Ok(IconsInfo { id: id.to_owned(), name, author: short(object.get("author"), 60), license: short(object.get("license"), 60), glyphs })
}
/// What a file name says it is: `.plugin.js` a plugin, `.strings.json` a string pack,
/// `.icons.json` an icon pack, any other `.json` a theme; anything else nothing.
pub fn kind_for_file_name(name: &str) -> Option<Kind> {
let lower = name.to_ascii_lowercase();
if lower.ends_with(plugins::PLUGIN_SUFFIX) {
Some(Kind::Plugin)
} else if lower.ends_with(".strings.json") {
Some(Kind::Strings)
} else if lower.ends_with(".icons.json") {
Some(Kind::Icons)
} else if lower.ends_with(".json") {
Some(Kind::Theme)
} else {
None
}
}
/// Validates a plugin for installation (see `plugins::validate_plugin`). /// Validates a plugin for installation (see `plugins::validate_plugin`).
pub fn validate_plugin(file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> { pub fn validate_plugin(file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> {
plugins::validate_plugin(file, bytes) plugins::validate_plugin(file, bytes)
@ -279,11 +351,15 @@ pub struct CatalogItem {
pub category: String, pub category: String,
#[serde(default)] #[serde(default)]
pub tags: Vec<String>, pub tags: Vec<String>,
/// Where the file is (every kind but `builtin`, which has nothing to download).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub url: String, pub url: String,
/// Plugins: the file name it is installed under. /// Plugins: the file name it is installed under.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>, pub file: Option<String>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub sha256: String, pub sha256: String,
#[serde(default, skip_serializing_if = "is_zero")]
pub size: u64, pub size: u64,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub preview: Option<String>, pub preview: Option<String>,
@ -321,6 +397,10 @@ impl Catalog {
} }
} }
fn is_zero(value: &u64) -> bool {
*value == 0
}
fn valid_id(id: &str) -> bool { fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') !id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
} }
@ -358,9 +438,22 @@ impl CatalogItem {
if self.tags.len() > 12 || self.tags.iter().any(|tag| !valid_text(tag, 32)) { if self.tags.len() > 12 || self.tags.iter().any(|tag| !valid_text(tag, 32)) {
return bad("tags"); return bad("tags");
} }
let url = Url::parse(&self.url).map_err(|_| format!("STORE: item {}: invalid url", self.id))?; if self.kind == Kind::Builtin {
if url.scheme() != "https" || url.as_str().len() > MAX_LINK_CHARS || hosts.is_some_and(|hosts| !allowed_download_url(hosts, &url)) { // Part of the app: nothing to download, so nothing to hash or point at.
return bad("url (host not allowed)"); if !self.url.is_empty() || !self.sha256.is_empty() || self.size != 0 || self.file.is_some() || self.permissions.is_some() || self.colors.is_some() || self.language.is_some() {
return bad("built-in item fields");
}
} else {
let url = Url::parse(&self.url).map_err(|_| format!("STORE: item {}: invalid url", self.id))?;
if url.scheme() != "https" || url.as_str().len() > MAX_LINK_CHARS || hosts.is_some_and(|hosts| !allowed_download_url(hosts, &url)) {
return bad("url (host not allowed)");
}
if self.sha256.len() != 64 || !self.sha256.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
return bad("sha256");
}
if self.size == 0 || self.size > self.kind.max_bytes() as u64 {
return bad("size");
}
} }
if let Some(preview) = &self.preview { if let Some(preview) = &self.preview {
let ok = Url::parse(preview).is_ok_and(|url| url.scheme() == "https" && hosts.is_none_or(|hosts| allowed_download_url(hosts, &url))); let ok = Url::parse(preview).is_ok_and(|url| url.scheme() == "https" && hosts.is_none_or(|hosts| allowed_download_url(hosts, &url)));
@ -368,12 +461,6 @@ impl CatalogItem {
return bad("preview"); return bad("preview");
} }
} }
if self.sha256.len() != 64 || !self.sha256.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
return bad("sha256");
}
if self.size == 0 || self.size > self.kind.max_bytes() as u64 {
return bad("size");
}
// Any item may name its licence and credit its authors; only a string pack has a language. // Any item may name its licence and credit its authors; only a string pack has a language.
if !self.license.as_deref().is_none_or(|v| !v.trim().is_empty() && valid_text(v, 60)) || !self.credits.as_deref().is_none_or(|v| valid_text(v, 600)) { if !self.license.as_deref().is_none_or(|v| !v.trim().is_empty() && valid_text(v, 60)) || !self.credits.as_deref().is_none_or(|v| valid_text(v, 600)) {
return bad("license or credits"); return bad("license or credits");
@ -393,6 +480,12 @@ impl CatalogItem {
} }
} }
} }
Kind::Icons => {
if self.file.is_some() || self.permissions.is_some() || self.colors.is_some() {
return bad("icon pack fields");
}
}
Kind::Builtin => {}
Kind::Strings => { Kind::Strings => {
if self.file.is_some() || self.permissions.is_some() || self.colors.is_some() { if self.file.is_some() || self.permissions.is_some() || self.colors.is_some() {
return bad("string pack fields"); return bad("string pack fields");
@ -473,6 +566,9 @@ pub fn verify_catalog(config: &StoreConfig, body: &[u8], signature: &str) -> Res
/// A downloaded item must be exactly what the signed catalog describes. /// A downloaded item must be exactly what the signed catalog describes.
pub fn verify_item(item: &CatalogItem, bytes: &[u8]) -> Result<(), String> { pub fn verify_item(item: &CatalogItem, bytes: &[u8]) -> Result<(), String> {
if item.kind == Kind::Builtin {
return Err("STORE: built-in items are part of the app; there is nothing to download".into());
}
if bytes.len() as u64 != item.size { if bytes.len() as u64 != item.size {
return Err("STORE: the download's size does not match the signed catalog".into()); return Err("STORE: the download's size does not match the signed catalog".into());
} }
@ -795,6 +891,104 @@ pub(crate) mod tests {
assert!(verify_catalog(c, &body, &sign(&key, &body)).unwrap_err().contains("update the app")); assert!(verify_catalog(c, &body, &sign(&key, &body)).unwrap_err().contains("update the app"));
} }
const ICONS: &[u8] = br#"{"id":"line-2","name":"Line 2","author":"me","license":"CC0-1.0","glyphs":{"home":{"d":"M3 3h18v18H3z"}}}"#;
fn icons_item(body: &[u8]) -> serde_json::Value {
serde_json::json!({
"apps": ["x"], "kind": "icons", "id": "line-2", "name": "Line 2", "version": "1.0.0", "category": "icons",
"url": "https://waybetter.fyi/store/icons/line-2.icons.json", "sha256": sha256_hex(body), "size": body.len(), "license": "CC0-1.0"
})
}
fn builtin_item() -> serde_json::Value {
serde_json::json!({ "apps": ["x"], "kind": "builtin", "id": "compose", "name": "Compose+", "version": "1.0.0", "description": "Writing tools.", "category": "writing" })
}
#[test]
fn icon_packs_and_built_in_items_are_catalog_kinds() {
let (key, public) = test_key(7);
let c = config("x", &[public]);
let body = catalog_json(serde_json::json!([icons_item(ICONS), builtin_item()]));
let catalog = verify_catalog(c, &body, &sign(&key, &body)).unwrap();
assert_eq!(catalog.items.iter().map(|item| item.kind).collect::<Vec<_>>(), [Kind::Icons, Kind::Builtin]);
verify_item(&catalog.items[0], ICONS).unwrap();
assert!(verify_item(&catalog.items[0], b"{}").is_err());
assert!(verify_item(&catalog.items[1], b"").unwrap_err().contains("built-in"), "nothing to download for a built-in item");
// A built-in item serializes without file fields (the signed bytes stay what the builder wrote).
let json = serde_json::to_value(&catalog.items[1]).unwrap();
for field in ["url", "sha256", "size", "file"] {
assert!(json.get(field).is_none(), "{field}");
}
// Built-in items carry no file, hash, size, url, permissions, colors or language; icon packs no plugin or theme fields.
let mut cases: Vec<(&str, serde_json::Value)> = Vec::new();
for (what, patch) in [
("url", serde_json::json!({ "url": "https://waybetter.fyi/a" })),
("sha256", serde_json::json!({ "sha256": sha256_hex(b"x") })),
("size", serde_json::json!({ "size": 5 })),
("file", serde_json::json!({ "file": "a.plugin.js" })),
("permissions", serde_json::json!({ "permissions": ["ui"] })),
("language", serde_json::json!({ "language": "eo" })),
("colors", serde_json::json!({ "colors": { "bg": "#000000", "text": "#ffffff", "accent": "#ff0000" } })),
] {
let mut item = builtin_item();
for (k, v) in patch.as_object().unwrap() {
item[k] = v.clone();
}
cases.push((what, item));
}
for (what, patch) in [("file", serde_json::json!({ "file": "a.plugin.js" })), ("permissions", serde_json::json!({ "permissions": ["ui"] })), ("language", serde_json::json!({ "language": "eo" }))] {
let mut item = icons_item(ICONS);
for (k, v) in patch.as_object().unwrap() {
item[k] = v.clone();
}
cases.push((what, item));
}
let mut no_url = icons_item(ICONS);
no_url.as_object_mut().unwrap().remove("url");
cases.push(("icon pack without url", no_url));
let mut big = icons_item(ICONS);
big["size"] = serde_json::json!(MAX_ICONS_BYTES + 1);
cases.push(("icon pack over the cap", big));
for (what, item) in cases {
let body = catalog_json(serde_json::json!([item]));
assert!(verify_catalog(c, &body, &sign(&key, &body)).is_err(), "accepted bad {what}");
}
// Another app's built-in items are not this app's.
let mut other = builtin_item();
other["apps"] = serde_json::json!(["kick"]);
let body = catalog_json(serde_json::json!([other]));
assert!(verify_catalog(c, &body, &sign(&key, &body)).unwrap().items.is_empty());
// Links and the shell's kind names: icons yes, built-in never.
assert_eq!(parse_install_link(c, "waybetter://install?kind=icons&url=https://waybetter.fyi/store/icons/line-2.icons.json").unwrap().kind, Kind::Icons);
assert!(parse_install_link(c, "waybetter://install?kind=builtin&url=https://waybetter.fyi/a.json").unwrap_err().contains("built-in"));
}
#[test]
fn icon_packs_are_small_json_objects_with_an_id_a_name_and_glyphs() {
let info = validate_icons(ICONS).unwrap();
assert_eq!((info.id.as_str(), info.name.as_str(), info.license.as_str(), info.glyphs), ("line-2", "Line 2", "CC0-1.0", 1));
for bad in [
&b""[..], b"[]", b"{not json", br#"{"name":"A","glyphs":{"home":{}}}"#, br#"{"id":"Bad Id","name":"A","glyphs":{"home":{}}}"#,
br#"{"id":"a","glyphs":{"home":{}}}"#, br#"{"id":"a","name":"A"}"#, br#"{"id":"a","name":"A","glyphs":{}}"#,
] {
assert!(validate_icons(bad).is_err(), "accepted {}", String::from_utf8_lossy(bad));
}
let big = format!(r#"{{"id":"a","name":"A","glyphs":{{"home":{{"d":"{}"}}}}}}"#, "M".repeat(MAX_ICONS_BYTES));
assert!(validate_icons(big.as_bytes()).unwrap_err().contains("120 KB"));
}
#[test]
fn file_names_say_what_a_file_is() {
assert_eq!(kind_for_file_name("tool.plugin.js"), Some(Kind::Plugin));
assert_eq!(kind_for_file_name("TOOL.PLUGIN.JS"), Some(Kind::Plugin));
assert_eq!(kind_for_file_name("eo.strings.json"), Some(Kind::Strings));
assert_eq!(kind_for_file_name("line.icons.json"), Some(Kind::Icons), "not a theme");
assert_eq!(kind_for_file_name("nord.json"), Some(Kind::Theme));
for other in ["script.js", "photo.png", "notes.txt", "json", ""] {
assert_eq!(kind_for_file_name(other), None, "{other}");
}
}
#[test] #[test]
fn versions_compare_numerically() { fn versions_compare_numerically() {
assert!(newer_version("1.10.0", "1.9.3")); assert!(newer_version("1.10.0", "1.9.3"));

View file

@ -4,12 +4,13 @@
//! and passes a function that runs a plugin start/stop script in its site tabs. //! and passes a function that runs a plugin start/stop script in its site tabs.
use super::catalog::{ use super::catalog::{
self as dist, Catalog, CatalogItem, InstallLink, InstallRecord, InstallRecords, Kind, SourceKind, StoreConfig, ThemeInfo, self as dist, Catalog, CatalogItem, IconsInfo, InstallLink, InstallRecord, InstallRecords, Kind, SourceKind, StoreConfig, ThemeInfo,
}; };
use super::strings::{self as packs, StringsInfo, StringsList, StringsStore}; use super::strings::{self as packs, StringsInfo, StringsList, StringsStore};
use crate::plugins::{self, PluginHost, PluginStore, ScriptPlugin, PLUGIN_SUFFIX}; use crate::plugins::{self, PluginHost, PluginStore, ScriptPlugin};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, VecDeque}; use std::collections::{BTreeMap, HashMap, VecDeque};
use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard}; use std::sync::{Mutex, MutexGuard};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@ -20,7 +21,8 @@ pub const RECORDS_FILE: &str = "store-installed.json";
/// The last verified catalog and its signature (verified again when read back). /// The last verified catalog and its signature (verified again when read back).
pub const CATALOG_CACHE: &str = "store-catalog.json"; pub const CATALOG_CACHE: &str = "store-catalog.json";
pub const CATALOG_SIG_CACHE: &str = "store-catalog.json.sig"; pub const CATALOG_SIG_CACHE: &str = "store-catalog.json.sig";
/// Shell event: a validated install link (`{ link: { kind, url } }`), a "Share my setup" link /// Shell event: a validated install link (`{ link: { kind, url } }`), a file the OS handed over
/// ("Open with", double-click: `{ opened: { id, name, kind } }`), a "Share my setup" link
/// (`{ setup }`: its text, for the shell's preview) or `{ error }`. /// (`{ setup }`: its text, for the shell's preview) or `{ error }`.
pub const EVENT_LINK: &str = "install-link"; pub const EVENT_LINK: &str = "install-link";
/// "Share my setup" links: `waybetter://setup?app=…&d=…`. Native code only checks the shape and /// "Share my setup" links: `waybetter://setup?app=…&d=…`. Native code only checks the shape and
@ -31,6 +33,8 @@ const MAX_SETUP_LINK: usize = 24 * 1024;
/// Links received before the shell asked for them (startup, or while the shell reloads). /// Links received before the shell asked for them (startup, or while the shell reloads).
const MAX_PENDING: usize = 8; const MAX_PENDING: usize = 8;
const MAX_STAGED: usize = 8; const MAX_STAGED: usize = 8;
/// Files the OS handed over that the shell has not asked for yet.
const MAX_OPENED: usize = 8;
const STAGED_TTL: Duration = Duration::from_secs(15 * 60); const STAGED_TTL: Duration = Duration::from_secs(15 * 60);
/// The confirmation screen enables Install after a moment; a commit faster than this was not read. /// The confirmation screen enables Install after a moment; a commit faster than this was not read.
pub const MIN_REVIEW: Duration = Duration::from_millis(600); pub const MIN_REVIEW: Duration = Duration::from_millis(600);
@ -47,6 +51,19 @@ pub struct LinkEvent {
/// A "Share my setup" link, as text (see [`SETUP_LINK`]). /// A "Share my setup" link, as text (see [`SETUP_LINK`]).
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub setup: Option<String>, pub setup: Option<String>,
/// A file the OS handed to the app; the shell asks for it by `id` (`install_stage_opened`).
#[serde(skip_serializing_if = "Option::is_none")]
pub opened: Option<OpenedFile>,
}
/// A file the OS handed to the app. Only its random id, its name and what it would be reach the
/// shell; the path stays in native code and the shell cannot name a path of its own.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenedFile {
pub id: String,
pub name: String,
pub kind: Kind,
} }
/// `Some` when `raw` is a setup link: its text when it has the plain shape (the path, a query of /// `Some` when `raw` is a setup link: its text when it has the plain shape (the path, a query of
@ -97,6 +114,8 @@ pub struct InstallPreview {
pub theme: Option<ThemeInfo>, pub theme: Option<ThemeInfo>,
/// String packs: what the pack says about itself (the shell adds coverage from the inventory). /// String packs: what the pack says about itself (the shell adds coverage from the inventory).
pub strings: Option<StringsInfo>, pub strings: Option<StringsInfo>,
/// Icon packs: what the pack says about itself (the shell parses and draws the rest).
pub icons: Option<IconsInfo>,
pub findings: Vec<&'static str>, pub findings: Vec<&'static str>,
pub existing: Option<Existing>, pub existing: Option<Existing>,
pub store: Option<CatalogItem>, pub store: Option<CatalogItem>,
@ -112,6 +131,8 @@ pub struct InstallOutcome {
pub theme_text: Option<String>, pub theme_text: Option<String>,
/// String packs: the installed packs after installing. /// String packs: the installed packs after installing.
pub strings: Option<StringsList>, pub strings: Option<StringsList>,
/// Icon packs: the exact JSON the owner confirmed; the shell adds it (sanitized) to its packs.
pub icons_text: Option<String>,
} }
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug, Serialize)]
@ -161,8 +182,16 @@ struct CatalogCache {
fetched_at: String, fetched_at: String,
} }
struct Opened {
path: PathBuf,
name: String,
kind: Kind,
created: Instant,
}
struct Inner { struct Inner {
pending: VecDeque<LinkEvent>, pending: VecDeque<LinkEvent>,
opened: HashMap<String, Opened>,
staged: HashMap<String, Staged>, staged: HashMap<String, Staged>,
catalog: Option<CatalogCache>, catalog: Option<CatalogCache>,
records: InstallRecords, records: InstallRecords,
@ -202,7 +231,7 @@ impl Store {
config, config,
plugins, plugins,
data_dir, data_dir,
inner: Mutex::new(Inner { pending: VecDeque::new(), staged: HashMap::new(), catalog: None, records }), inner: Mutex::new(Inner { pending: VecDeque::new(), opened: HashMap::new(), staged: HashMap::new(), catalog: None, records }),
} }
} }
@ -242,14 +271,19 @@ impl Store {
/// A link reached the app (OS deep link, second launch): validate it and queue it for the /// A link reached the app (OS deep link, second launch): validate it and queue it for the
/// shell. Returns the event to emit ([`EVENT_LINK`]). Nothing is downloaded or installed here. /// shell. Returns the event to emit ([`EVENT_LINK`]). Nothing is downloaded or installed here.
pub fn receive_link(&self, raw: &str) -> LinkEvent { pub fn receive_link(&self, raw: &str) -> LinkEvent {
let event = match setup_link(raw) { let mut event = LinkEvent { link: None, error: None, setup: None, opened: None };
Some(Ok(text)) => LinkEvent { link: None, error: None, setup: Some(text) }, match setup_link(raw) {
Some(Err(error)) => LinkEvent { link: None, error: Some(error), setup: None }, Some(Ok(text)) => event.setup = Some(text),
Some(Err(error)) => event.error = Some(error),
None => match dist::parse_install_link(self.config, raw) { None => match dist::parse_install_link(self.config, raw) {
Ok(link) => LinkEvent { link: Some(link), error: None, setup: None }, Ok(link) => event.link = Some(link),
Err(error) => LinkEvent { link: None, error: Some(error), setup: None }, Err(error) => event.error = Some(error),
}, },
}; }
self.queue(event)
}
fn queue(&self, event: LinkEvent) -> LinkEvent {
let mut inner = self.lock(); let mut inner = self.lock();
if inner.pending.len() >= MAX_PENDING { if inner.pending.len() >= MAX_PENDING {
inner.pending.pop_front(); inner.pending.pop_front();
@ -258,6 +292,62 @@ impl Store {
event event
} }
/// A file the OS handed over (a double-click or "Open with", at launch or to the running app):
/// check its name and size, keep its path under a random id and queue the event for the shell.
/// The file is read only when the shell asks ([`Self::stage_opened`]), and what it shows is the
/// install screen: nothing is written without the owner's Install there.
pub fn receive_file(&self, path: &Path) -> LinkEvent {
let mut event = LinkEvent { link: None, error: None, setup: None, opened: None };
match self.keep_opened(path) {
Ok(opened) => event.opened = Some(opened),
Err(error) => event.error = Some(error),
}
self.queue(event)
}
fn keep_opened(&self, path: &Path) -> Result<OpenedFile, String> {
let name = path.file_name().and_then(|name| name.to_str()).ok_or("FILE: this file's name cannot be read")?.to_owned();
let kind = dist::kind_for_file_name(&name)
.ok_or("FILE: only a theme (.json), a plugin (.plugin.js), a string pack (.strings.json) or an icon pack (.icons.json) can be opened here")?;
let meta = std::fs::metadata(path).map_err(|_| "FILE: this file cannot be read")?;
if !meta.is_file() {
return Err("FILE: this is not a file".into());
}
if meta.len() > kind.max_bytes() as u64 {
return Err("FILE: the file is larger than allowed".into());
}
let id = new_token();
let mut inner = self.lock();
inner.opened.retain(|_, opened| opened.created.elapsed() < STAGED_TTL);
while inner.opened.len() >= MAX_OPENED {
let oldest = inner.opened.iter().min_by_key(|(_, opened)| opened.created).map(|(id, _)| id.clone());
match oldest {
Some(id) => inner.opened.remove(&id),
None => break,
};
}
inner.opened.insert(id.clone(), Opened { path: path.to_path_buf(), name: name.clone(), kind, created: Instant::now() });
Ok(OpenedFile { id, name, kind })
}
/// Reads the file kept under `id` (single use) and stages it like a dropped file.
pub fn stage_opened(&self, id: &str) -> Result<InstallPreview, String> {
let opened = self.lock().opened.remove(id).filter(|opened| opened.created.elapsed() < STAGED_TTL);
let Some(opened) = opened else {
return Err("INSTALL: this file is no longer waiting; open it again".into());
};
let max = opened.kind.max_bytes();
let mut bytes = Vec::new();
std::fs::File::open(&opened.path)
.and_then(|file| file.take(max as u64 + 1).read_to_end(&mut bytes))
.map_err(|_| "FILE: this file cannot be read")?;
if bytes.len() > max {
return Err("VALIDATION: the file is larger than allowed".into());
}
let file = (opened.kind == Kind::Plugin).then(|| opened.name.clone());
self.stage(opened.kind, file, bytes, SourceKind::File, None, None)
}
/// Links that arrived before the shell listened (drained). /// Links that arrived before the shell listened (drained).
pub fn take_pending(&self) -> Vec<LinkEvent> { pub fn take_pending(&self) -> Vec<LinkEvent> {
self.lock().pending.drain(..).collect() self.lock().pending.drain(..).collect()
@ -270,7 +360,7 @@ impl Store {
let link = dist::parse_install_link(self.config, &dist::install_link(self.config, kind, url))?; let link = dist::parse_install_link(self.config, &dist::install_link(self.config, kind, url))?;
let file = match kind { let file = match kind {
Kind::Plugin => Some(dist::plugin_file_from_url(&Url::parse(&link.url).map_err(|_| "VALIDATION: invalid URL")?)?), Kind::Plugin => Some(dist::plugin_file_from_url(&Url::parse(&link.url).map_err(|_| "VALIDATION: invalid URL")?)?),
Kind::Theme | Kind::Strings => None, Kind::Theme | Kind::Strings | Kind::Icons | Kind::Builtin => None,
}; };
Ok((link, file)) Ok((link, file))
} }
@ -291,6 +381,7 @@ impl Store {
} }
let text = String::from_utf8(bytes.clone()).map_err(|_| "VALIDATION: not UTF-8 text")?; let text = String::from_utf8(bytes.clone()).map_err(|_| "VALIDATION: not UTF-8 text")?;
let mut strings = None; let mut strings = None;
let mut icons = None;
let (plugin, theme, findings, version, existing) = match kind { let (plugin, theme, findings, version, existing) = match kind {
Kind::Plugin => { Kind::Plugin => {
let file = file.as_deref().ok_or("VALIDATION: missing plugin file name")?; let file = file.as_deref().ok_or("VALIDATION: missing plugin file name")?;
@ -325,6 +416,18 @@ impl Store {
let version = store.as_ref().map(|item| item.version.clone()).unwrap_or_default(); let version = store.as_ref().map(|item| item.version.clone()).unwrap_or_default();
(None, Some(info), Vec::new(), version, None) (None, Some(info), Vec::new(), version, None)
} }
Kind::Icons => {
let info = dist::validate_icons(&bytes)?;
let version = store.as_ref().map(|item| item.version.clone()).unwrap_or_default();
let existing = inner.records.items.get(&InstallRecords::key(Kind::Icons, &info.id)).map(|record| Existing {
version: record.version.clone(),
enabled: false,
same: record.sha256 == dist::sha256_hex(&bytes),
});
icons = Some(info);
(None, None, Vec::new(), version, existing)
}
Kind::Builtin => return Err("VALIDATION: built-in items are part of the app; there is nothing to install".into()),
}; };
let label = match source { let label = match source {
SourceKind::Store => "wayBetter Store (signed catalog, sha256 verified)".to_owned(), SourceKind::Store => "wayBetter Store (signed catalog, sha256 verified)".to_owned(),
@ -345,6 +448,7 @@ impl Store {
plugin, plugin,
theme, theme,
strings, strings,
icons,
findings, findings,
existing, existing,
store: store.clone(), store: store.clone(),
@ -367,16 +471,9 @@ impl Store {
/// A file dropped on the window (the shell read it with the File API; validated here). /// A file dropped on the window (the shell read it with the File API; validated here).
pub fn stage_file(&self, name: &str, text: String) -> Result<InstallPreview, String> { pub fn stage_file(&self, name: &str, text: String) -> Result<InstallPreview, String> {
let lower = name.to_ascii_lowercase(); let kind = dist::kind_for_file_name(name)
let (kind, file) = if lower.ends_with(PLUGIN_SUFFIX) { .ok_or("VALIDATION: drop a theme (.json), a plugin (.plugin.js), a string pack (.strings.json) or an icon pack (.icons.json)")?;
(Kind::Plugin, Some(name.to_owned())) let file = (kind == Kind::Plugin).then(|| name.to_owned());
} else if lower.ends_with(".strings.json") {
(Kind::Strings, None)
} else if lower.ends_with(".json") {
(Kind::Theme, None)
} else {
return Err("VALIDATION: drop a theme (.json), a plugin (.plugin.js) or a string pack (.strings.json)".into());
};
if text.len() > kind.max_bytes() { if text.len() > kind.max_bytes() {
return Err("VALIDATION: the file is larger than allowed".into()); return Err("VALIDATION: the file is larger than allowed".into());
} }
@ -449,7 +546,7 @@ impl Store {
store.set_enabled(&file, true)?; store.set_enabled(&file, true)?;
run(&script); run(&script);
} }
Ok(InstallOutcome { kind: Kind::Plugin, plugins: Some(store.list()?), theme_text: None, strings: None }) Ok(InstallOutcome { kind: Kind::Plugin, plugins: Some(store.list()?), theme_text: None, strings: None, icons_text: None })
} }
Kind::Strings => { Kind::Strings => {
let info = packs::validate_strings(&staged.bytes)?; let info = packs::validate_strings(&staged.bytes)?;
@ -460,7 +557,7 @@ impl Store {
let records = inner.records.clone(); let records = inner.records.clone();
drop(inner); drop(inner);
self.save_records(&records); self.save_records(&records);
Ok(InstallOutcome { kind: Kind::Strings, plugins: None, theme_text: None, strings: Some(local.list()) }) Ok(InstallOutcome { kind: Kind::Strings, plugins: None, theme_text: None, strings: Some(local.list()), icons_text: None })
} }
Kind::Theme => { Kind::Theme => {
let id = theme_id.filter(|id| valid_theme_id(id)).ok_or("VALIDATION: invalid theme id")?; let id = theme_id.filter(|id| valid_theme_id(id)).ok_or("VALIDATION: invalid theme id")?;
@ -469,8 +566,18 @@ impl Store {
drop(inner); drop(inner);
self.save_records(&records); self.save_records(&records);
let text = String::from_utf8(staged.bytes).map_err(|_| "VALIDATION: not UTF-8")?; let text = String::from_utf8(staged.bytes).map_err(|_| "VALIDATION: not UTF-8")?;
Ok(InstallOutcome { kind: Kind::Theme, plugins: None, theme_text: Some(text), strings: None }) Ok(InstallOutcome { kind: Kind::Theme, plugins: None, theme_text: Some(text), strings: None, icons_text: None })
} }
Kind::Icons => {
let info = dist::validate_icons(&staged.bytes)?;
inner.records.insert(InstallRecords::key(Kind::Icons, &info.id), record(staged.version.clone()));
let records = inner.records.clone();
drop(inner);
self.save_records(&records);
let text = String::from_utf8(staged.bytes).map_err(|_| "VALIDATION: not UTF-8")?;
Ok(InstallOutcome { kind: Kind::Icons, plugins: None, theme_text: None, strings: None, icons_text: Some(text) })
}
Kind::Builtin => Err("INSTALL: built-in items are part of the app".into()),
} }
} }
@ -741,6 +848,105 @@ mod tests {
assert!(store.commit(&other.token, true, Some("other".into()), |_| {}).is_err()); assert!(store.commit(&other.token, true, Some("other".into()), |_| {}).is_err());
} }
const ICONS: &str = r#"{"id":"line-2","name":"Line 2","author":"me","license":"CC0-1.0","glyphs":{"home":{"d":"M3 3h18v18H3z"}}}"#;
#[test]
fn icon_packs_install_as_text_for_the_shell_and_are_never_themes() {
let (_dir, store, _, _) = store_with_catalog();
assert!(store.stage_file("bad.icons.json", r#"{"name":"A"}"#.into()).unwrap_err().contains("id"), "an icon pack is not read as a theme");
let dropped = store.stage_file("line-2.icons.json", ICONS.into()).unwrap();
assert_eq!(dropped.kind, Kind::Icons);
assert_eq!(dropped.icons.as_ref().map(|info| (info.id.as_str(), info.glyphs)), Some(("line-2", 1)));
assert!(dropped.plugin.is_none() && dropped.theme.is_none() && !dropped.source.signed);
reviewed();
let outcome = store.commit(&dropped.token, false, None, |_| panic!("icon packs run nothing")).unwrap();
assert_eq!((outcome.kind, outcome.icons_text.as_deref()), (Kind::Icons, Some(ICONS)));
assert!(outcome.theme_text.is_none() && outcome.plugins.is_none());
assert_eq!(store.records().items["icons:line-2"].source, SourceKind::File);
// Staging the same pack again says it is installed; forgetting it clears the record.
let again = store.stage_file("line-2.icons.json", ICONS.into()).unwrap();
assert!(again.existing.as_ref().is_some_and(|existing| existing.same));
store.forget("icons", "line-2").unwrap();
assert!(store.records().items.is_empty());
assert!(store.stage_file("big.icons.json", format!(r#"{{"id":"a","name":"A","glyphs":{{"home":{{"d":"{}"}}}}}}"#, "M".repeat(dist::MAX_ICONS_BYTES))).unwrap_err().contains("larger"));
}
#[test]
fn built_in_items_have_nothing_to_stage() {
let (_dir, store, _, _) = store_with_catalog();
let entry: CatalogItem = serde_json::from_value(serde_json::json!({ "apps": ["x"], "kind": "builtin", "id": "compose", "name": "Compose+", "version": "1.0.0" })).unwrap();
assert!(store.stage_store_download(entry, Vec::new()).unwrap_err().contains("built-in"));
assert!(store.stage(Kind::Builtin, None, b"{}".to_vec(), SourceKind::File, None, None).unwrap_err().contains("built-in"));
}
#[test]
fn files_the_os_hands_over_are_kept_under_an_id_and_staged_like_a_drop() {
let (dir, store, _, _) = store_with_catalog();
let theme = dir.path().join("nord.json");
std::fs::write(&theme, THEME).unwrap();
let event = store.receive_file(&theme);
let opened = event.opened.clone().expect("a theme file is offered");
assert_eq!((opened.name.as_str(), opened.kind), ("nord.json", Kind::Theme));
assert!(event.link.is_none() && event.error.is_none() && event.setup.is_none());
// The shell sees an id and a name, never the path.
let wire = serde_json::to_string(&event).unwrap();
assert!(!wire.contains("path") && !wire.contains(dir.path().file_name().unwrap().to_str().unwrap()), "{wire}");
assert_eq!(store.take_pending().len(), 1, "queued for a shell that was not listening yet");
let preview = store.stage_opened(&opened.id).unwrap();
assert_eq!((preview.kind, preview.source.kind.clone()), (Kind::Theme, SourceKind::File));
assert_eq!(preview.theme.as_ref().unwrap().name, "Nord");
reviewed();
let outcome = store.commit(&preview.token, true, Some("nord-3".into()), |_| {}).unwrap();
assert_eq!(outcome.theme_text.as_deref().map(str::as_bytes), Some(THEME));
// Single use, and an id the OS did not hand over is refused (the shell cannot name a path).
assert!(store.stage_opened(&opened.id).unwrap_err().contains("no longer waiting"));
assert!(store.stage_opened("../nord.json").unwrap_err().contains("no longer waiting"));
assert!(store.stage_opened(&theme.to_string_lossy()).is_err());
// A plugin keeps its file name; an icon pack and a string pack are told apart from a theme.
let plugin = dir.path().join("tool.plugin.js");
std::fs::write(&plugin, PLUGIN).unwrap();
let opened = store.receive_file(&plugin).opened.unwrap();
let preview = store.stage_opened(&opened.id).unwrap();
assert_eq!((preview.kind, preview.file.as_deref()), (Kind::Plugin, Some("tool.plugin.js")));
let pack = dir.path().join("line-2.icons.json");
std::fs::write(&pack, ICONS).unwrap();
assert_eq!(store.receive_file(&pack).opened.unwrap().kind, Kind::Icons);
let strings = dir.path().join("eo.strings.json");
std::fs::write(&strings, "{}").unwrap();
assert_eq!(store.receive_file(&strings).opened.unwrap().kind, Kind::Strings);
// Refused up front, with an error for the shell: other files, folders, missing and oversize files.
let other = dir.path().join("photo.png");
std::fs::write(&other, "x").unwrap();
let big = dir.path().join("big.json");
std::fs::write(&big, vec![b'a'; dist::MAX_THEME_BYTES + 1]).unwrap();
for bad in [other, big, dir.path().to_path_buf(), dir.path().join("missing.json")] {
let event = store.receive_file(&bad);
assert!(event.opened.is_none() && event.error.as_deref().is_some_and(|error| error.starts_with("FILE:")), "{}: {:?}", bad.display(), event.error);
}
// A file that grew after it was offered is refused when read; one that vanished says so.
let late = dir.path().join("late.json");
std::fs::write(&late, THEME).unwrap();
let opened = store.receive_file(&late).opened.unwrap();
std::fs::write(&late, vec![b'a'; dist::MAX_THEME_BYTES + 1]).unwrap();
assert!(store.stage_opened(&opened.id).unwrap_err().contains("larger"));
let gone = dir.path().join("gone.json");
std::fs::write(&gone, THEME).unwrap();
let opened = store.receive_file(&gone).opened.unwrap();
std::fs::remove_file(&gone).unwrap();
assert!(store.stage_opened(&opened.id).unwrap_err().starts_with("FILE:"));
// Bounded: only the newest ones are kept.
let ids: Vec<String> = (0..MAX_OPENED + 3)
.map(|_| {
std::thread::sleep(Duration::from_millis(2));
store.receive_file(&theme).opened.unwrap().id
})
.collect();
assert_eq!(store.lock().opened.len(), MAX_OPENED);
assert!(store.stage_opened(&ids[0]).is_err() && store.stage_opened(ids.last().unwrap()).is_ok());
}
#[test] #[test]
fn staging_is_bounded() { fn staging_is_bounded() {
let (_dir, store, _, _) = store_with_catalog(); let (_dir, store, _, _) = store_with_catalog();

View file

@ -13,6 +13,7 @@ use crate::host::{emit_shell, eval_in_site_tabs, shell_only};
use crate::plugins::ScriptPlugin; use crate::plugins::ScriptPlugin;
use crate::policy; use crate::policy;
use crate::store::{delivery_script, InstallOutcome, InstallPreview, InstallRecords, LinkEvent, Store, StoreItemRef, StoreView, StringsList, EVENT_LINK}; use crate::store::{delivery_script, InstallOutcome, InstallPreview, InstallRecords, LinkEvent, Store, StoreItemRef, StoreView, StringsList, EVENT_LINK};
use std::path::{Path, PathBuf};
use tauri::{AppHandle, Manager, State, Webview}; use tauri::{AppHandle, Manager, State, Webview};
use tauri_plugin_deep_link::DeepLinkExt; use tauri_plugin_deep_link::DeepLinkExt;
@ -40,18 +41,63 @@ pub(crate) fn init(app: &AppHandle, config: &AppConfig) {
received(app, url.as_str()); received(app, url.as_str());
} }
} }
// Launched by a double-click or "Open with" on a file (Windows/Linux pass its path as an argument).
let args: Vec<String> = std::env::args().collect();
opened_args(app, &args, "");
}
/// Most files taken from one launch's arguments.
const MAX_OPENED_ARGS: usize = 8;
/// The files named in a launch's arguments (the first launch's own, or a second launch forwarded
/// by single-instance, with its working directory): flags and links are not files and are skipped;
/// each file that exists is kept under a random id and offered to the shell
/// ([`Store::receive_file`]), and the window comes forward. Nothing is read or installed here.
pub(crate) fn opened_args(app: &AppHandle, args: &[String], cwd: &str) {
let paths = file_args(args, cwd);
if paths.is_empty() {
return;
}
let Some(store) = app.try_state::<Store>() else { return };
for path in paths {
emit_shell(app, EVENT_LINK, store.receive_file(&path));
}
bring_forward(app);
}
/// The existing files among a launch's arguments (the first argument is the program itself).
fn file_args(args: &[String], cwd: &str) -> Vec<PathBuf> {
args.iter()
.skip(1)
.filter(|arg| !arg.starts_with('-') && !arg.contains("://"))
.map(|arg| if Path::new(arg).is_absolute() || cwd.is_empty() { PathBuf::from(arg) } else { Path::new(cwd).join(arg) })
.filter(|path| path.is_file())
.take(MAX_OPENED_ARGS)
.collect()
}
fn bring_forward(app: &AppHandle) {
if let Some(window) = app.get_window(policy::MAIN_LABEL) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
} }
/// A `waybetter://` link reached the app: validate it, queue it for the shell and bring the window /// A `waybetter://` link reached the app: validate it, queue it for the shell and bring the window
/// forward. Nothing is downloaded or installed until the shell's screen asks for it. /// forward. Nothing is downloaded or installed until the shell's screen asks for it.
fn received(app: &AppHandle, raw: &str) { fn received(app: &AppHandle, raw: &str) {
let Some(store) = app.try_state::<Store>() else { return }; let Some(store) = app.try_state::<Store>() else { return };
emit_shell(app, EVENT_LINK, store.receive_link(raw)); // macOS hands a double-clicked file over as an open-URL event with a `file://` URL.
if let Some(window) = app.get_window(policy::MAIN_LABEL) { let event = match url::Url::parse(raw).ok().filter(|url| url.scheme() == "file") {
let _ = window.unminimize(); Some(url) => match url.to_file_path() {
let _ = window.show(); Ok(path) => store.receive_file(&path),
let _ = window.set_focus(); Err(()) => store.receive_file(Path::new("")),
} },
None => store.receive_link(raw),
};
emit_shell(app, EVENT_LINK, event);
bring_forward(app);
} }
fn store(app: &AppHandle) -> Result<State<'_, Store>, String> { fn store(app: &AppHandle) -> Result<State<'_, Store>, String> {
@ -83,6 +129,15 @@ pub(crate) async fn install_stage_file(webview: Webview, app: AppHandle, name: S
store(&app)?.stage_file(&name, text) store(&app)?.stage_file(&name, text)
} }
/// A file the OS handed to the app (a double-click or "Open with"), asked for by the random id the
/// `install-link` event carried: native code reads it and stages it exactly like a dropped file,
/// for the same install screen. The shell never supplies a path; an unknown id is refused.
#[tauri::command]
pub(crate) async fn install_stage_opened(webview: Webview, app: AppHandle, id: String) -> Result<InstallPreview, String> {
shell_only(&webview)?;
store(&app)?.stage_opened(&id)
}
#[tauri::command] #[tauri::command]
pub(crate) async fn install_cancel(webview: Webview, app: AppHandle, token: String) -> Result<(), String> { pub(crate) async fn install_cancel(webview: Webview, app: AppHandle, token: String) -> Result<(), String> {
shell_only(&webview)?; shell_only(&webview)?;
@ -189,6 +244,7 @@ pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Sen
install_pending, install_pending,
install_stage_link, install_stage_link,
install_stage_file, install_stage_file,
install_stage_opened,
install_cancel, install_cancel,
install_commit, install_commit,
plugin_remove, plugin_remove,
@ -203,3 +259,30 @@ pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Sen
strings_apply strings_apply
] ]
} }
#[cfg(test)]
mod tests {
use super::*;
fn args(list: &[&str]) -> Vec<String> {
list.iter().map(|arg| (*arg).to_owned()).collect()
}
#[test]
fn launch_arguments_name_files_never_flags_or_links() {
let dir = std::env::temp_dir().join(format!("wb-opened-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let theme = dir.join("nord.json");
std::fs::write(&theme, "{}").unwrap();
let absolute = theme.to_string_lossy().into_owned();
let found = file_args(&args(&["wayBetter.exe", "--diag", "waybetter://install?kind=theme&url=https://waybetter.fyi/a.json", "file:///x.json", "missing.json", &absolute]), "");
assert_eq!(found, [theme.clone()], "the program, flags, links and missing files are skipped");
// A second launch's relative name is resolved against its own working directory.
let found = file_args(&args(&["wayBetter.exe", "nord.json"]), &dir.to_string_lossy());
assert_eq!(found, [dir.join("nord.json")]);
assert!(file_args(&args(&["wayBetter.exe", &dir.to_string_lossy()]), "").is_empty(), "a folder is not a file");
let many: Vec<String> = std::iter::once("wayBetter.exe".to_owned()).chain((0..20).map(|_| absolute.clone())).collect();
assert_eq!(file_args(&many, "").len(), MAX_OPENED_ARGS);
std::fs::remove_dir_all(&dir).unwrap();
}
}

View file

@ -217,6 +217,11 @@ pub fn assert_store_guards() {
for command in commands::STORE { for command in commands::STORE {
assert_guarded(source, command, "shell_only(&webview)?"); assert_guarded(source, command, "shell_only(&webview)?");
} }
// A file the OS handed over is asked for by its random id: the command takes no path, so the
// shell cannot make native code read a file of its own choosing.
let at = source.find("fn install_stage_opened(").expect("install_stage_opened exists");
let signature = &source[at..at + source[at..].find(')').expect("signature")];
assert!(signature.contains("id: String") && !signature.contains("path") && !signature.contains("PathBuf"), "install_stage_opened takes an id only: {signature}");
} }
/// The media commands' wrappers check their caller first. Runs against the host's source. /// The media commands' wrappers check their caller first. Runs against the host's source.

View file

@ -34,16 +34,20 @@ JSON Schema: `waybetter/store-catalog.schema.json` (npm package). The rules apps
| --- | --- | | --- | --- |
| `format` | `2`. An app that reads another format says "update the app". Format 1 (before `apps`) is gone. | | `format` | `2`. An app that reads another format says "update the app". Format 1 (before `apps`) is gone. |
| `apps` | 1–16 distinct app ids (`[a-z0-9-]{1,32}`), e.g. `"x"`; an item for several apps lists each. | | `apps` | 1–16 distinct app ids (`[a-z0-9-]{1,32}`), e.g. `"x"`; an item for several apps lists each. |
| `kind`, `id` | `theme`, `plugin` or `strings` (a string pack, docs/STRING-PACKS.md); `[a-z0-9-]{1,40}`, unique per app and kind. | | `kind`, `id` | `theme`, `plugin`, `strings` (a string pack, docs/STRING-PACKS.md), `icons` (an icon pack, `*.icons.json`: data, at most 120 KB, its own `id` is what it is installed under) or `builtin` (a feature that ships inside the app, below); `[a-z0-9-]{1,40}`, unique per app and kind. |
| `name`, `author`, `version`, `description`, `category`, `tags` | plain text (no control characters), ≤ 60 / 60 / 32 / 600 / 32 characters, ≤ 12 tags of ≤ 32. Known categories show in the reader's language (`wb.store.category.*`). | | `name`, `author`, `version`, `description`, `category`, `tags` | plain text (no control characters), ≤ 60 / 60 / 32 / 600 / 32 characters, ≤ 12 tags of ≤ 32. Known categories show in the reader's language (`wb.store.category.*`). |
| `url`, `preview` | https; for the reading app's own items, on its download hosts (below). | | `url`, `preview` | https; for the reading app's own items, on its download hosts (below). |
| `file` | plugins only: `name.plugin.js` (letters, digits, `-_. `), unique per app ignoring case. | | `file` | plugins only: `name.plugin.js` (letters, digits, `-_. `), unique per app ignoring case. |
| `sha256`, `size` | of the exact file; size 1 byte … 2 MiB. | | `url`, `sha256`, `size` | of the exact file; size 1 byte … 2 MiB (icon packs 120 KB). Absent on a `builtin` item, which has nothing to download and must not carry them. |
| `permissions` | plugins only: the header's `@permissions` (`null` = no line, legacy). | | `permissions` | plugins only: the header's `@permissions` (`null` = no line, legacy). |
| `colors` | themes only: `#rrggbb` swatches for the card. | | `colors` | themes only: `#rrggbb` swatches for the card. |
| `language` | string packs only, required: the pack's language tag. | | `language` | string packs only, required: the pack's language tag. |
| `license`, `credits` | any kind, optional: its licence (≤ 60 characters, e.g. an SPDX id) and who made, translated or reviewed it (≤ 600). The install screen shows them. | | `license`, `credits` | any kind, optional: its licence (≤ 60 characters, e.g. an SPDX id) and who made, translated or reviewed it (≤ 600). The install screen shows them. |
**Built-in items.** `builtin` lists something the app already has, such as one of its area plugins, so the Store can show it with the app's own switch (`StoreView`'s `areas` prop: whether the app has that id, whether it is on, turning it on or off). It has no `url`, `sha256`, `size`, `file`, `permissions`, `colors` or `language`; `Store::stage_*` refuses it, `verify_item` has nothing to verify, and an install link cannot name it. It is data for display only. An app that does not know the id just shows "Built in".
**Old apps.** An app from before a kind existed refuses the whole signed catalog that lists it (unknown kind: "catalog schema", the Store shows as unreachable). Publish a catalog with a new kind only once the apps that read it ship the kind.
Also refused: unknown fields anywhere, more than 500 items, a catalog over 1 MiB, a signature file Also refused: unknown fields anywhere, more than 500 items, a catalog over 1 MiB, a signature file
over 512 bytes. A malformed item for another app refuses the whole catalog (one file, one set of over 512 bytes. A malformed item for another app refuses the whole catalog (one file, one set of
rules); another app's download hosts are not held to this app's list. rules); another app's download hosts are not held to this app's list.
@ -95,6 +99,12 @@ end in `name.plugin.js`, the name it is saved under. A link only proposes an ins
for the shell (`install-link` event, `install_pending` for links that arrived before the shell for the shell (`install-link` event, `install_pending` for links that arrived before the shell
listened) and nothing is downloaded until the shell asks. listened) and nothing is downloaded until the shell asks.
## Open with, double-click
The OS can hand the app a file ("Open with", a double-click, a second launch while the app runs: single-instance forwards its arguments and working directory; macOS an open-URL event with a `file://` URL). `store_commands` keeps each existing file's path under a random id (`Store::receive_file`: a name that says what it is, `kind_for_file_name`, a regular file, within the kind's size cap; at most 8 kept, 15 minutes) and queues a `LinkEvent { opened: { id, name, kind } }` for the shell like a link. The shell asks for it with `install_stage_opened {id}`: native code reads that one file (once; size checked again while reading), validates it exactly as `stage_file` does and stages it, and the shell shows the same install screen as for a dropped file. The command takes an id only: the shell cannot name a path, and an id the OS did not hand over is refused. Nothing installs without the screen. File names: `.plugin.js` plugin, `.strings.json` string pack, `.icons.json` icon pack, any other `.json` a theme.
The app declares the types in `tauri.conf.json` (`bundle.fileAssociations`: `js` and `json`, role Viewer, rank Alternate). A plugin is `name.plugin.js` and Windows only knows the last part, so the framework's installer template (`windows/installer.nsi`) lists the app under "Open with" (`OpenWithProgids`) and never makes it the default program for `.js` or `.json` files, unlike Tauri's own association macro.
## Trust model ## Trust model
- Only the app's local shell webview may call the install commands; site tabs and web pages never - Only the app's local shell webview may call the install commands; site tabs and web pages never
@ -128,7 +138,7 @@ pub static STORE: StoreConfig = StoreConfig {
Commands, each starting with `shell_only(&webview)?` and listed only in the shell's capability: Commands, each starting with `shell_only(&webview)?` and listed only in the shell's capability:
`install_pending` → `take_pending`, `install_stage_link {kind,url}` → `stage_link`, `install_pending` → `take_pending`, `install_stage_link {kind,url}` → `stage_link`,
`install_stage_file {name,text}` → `stage_file`, `install_cancel {token}` → `cancel`, `install_stage_file {name,text}` → `stage_file`, `install_stage_opened {id}` → `stage_opened` (a file the OS handed over, by its random id), `install_cancel {token}` → `cancel`,
`install_commit {token,enable,themeId}` → `commit(…, run)` where `run` evaluates a plugin `install_commit {token,enable,themeId}` → `commit(…, run)` where `run` evaluates a plugin
start/stop script in the site's tabs, `plugin_remove {file}` → `remove_plugin`, `install_records` start/stop script in the site's tabs, `plugin_remove {file}` → `remove_plugin`, `install_records`
→ `records`, `install_forget {kind,name}` → `forget`, `store_catalog {refresh}` → `catalog`, → `records`, `install_forget {kind,name}` → `forget`, `store_catalog {refresh}` → `catalog`,

View file

@ -1,6 +1,6 @@
// A small JSON Schema (draft 2020-12) validator for the keywords theme.schema.json uses: type, // A small JSON Schema (draft 2020-12) validator for the keywords theme.schema.json uses: type,
// required, properties, additionalProperties, enum, const, pattern, min/maxLength, minimum, // required, properties, additionalProperties, enum, const, pattern, min/maxLength, minimum,
// maximum, items, minItems, maxItems, uniqueItems, allOf, oneOf, anyOf and local $ref (theme and // maximum, items, minItems, maxItems, uniqueItems, allOf, oneOf, anyOf, not, if/then/else and local $ref (theme and
// store catalog schemas). Returns a list of error paths. // store catalog schemas). Returns a list of error paths.
const typeOf = value => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value); const typeOf = value => (value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value);
@ -50,5 +50,10 @@ export function validate(schema, value, root = schema, path = '$') {
if (passing !== 1) errors.push(`${path}: matches ${passing} of oneOf (needs exactly 1)`); if (passing !== 1) errors.push(`${path}: matches ${passing} of oneOf (needs exactly 1)`);
} }
if (schema.anyOf && !schema.anyOf.some(option => validate(option, value, root, path).length === 0)) errors.push(`${path}: matches none of anyOf`); if (schema.anyOf && !schema.anyOf.some(option => validate(option, value, root, path).length === 0)) errors.push(`${path}: matches none of anyOf`);
if (schema.not && validate(schema.not, value, root, path).length === 0) errors.push(`${path}: matches a schema it must not match`);
if (schema.if) {
const branch = validate(schema.if, value, root, path).length === 0 ? schema.then : schema.else;
if (branch) errors.push(...validate(branch, value, root, path));
}
return errors; return errors;
} }

View file

@ -7,6 +7,7 @@
import { useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react'; import { useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { GlyphPaths } from './frame/iconPack.tsx';
import type { InstallController, InstallRequest } from './installController.ts'; import type { InstallController, InstallRequest } from './installController.ts';
import type { StoreText } from './storeMessages.ts'; import type { StoreText } from './storeMessages.ts';
import { formatBytes, permissionBadges, previewLines, type InstallKind, type InstallPreview } from './storeModel.ts'; import { formatBytes, permissionBadges, previewLines, type InstallKind, type InstallPreview } from './storeModel.ts';
@ -57,6 +58,7 @@ const G = {
warn: 'M12 4l9 16H3zM12 10v4M12 17h.01', warn: 'M12 4l9 16H3zM12 10v4M12 17h.01',
copy: 'M9 9h10v10H9zM5 15V5h10', copy: 'M9 9h10v10H9zM5 15V5h10',
close: 'M6 6l12 12M18 6L6 18', close: 'M6 6l12 12M18 6L6 18',
icons: 'M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM17 14v6M14 17h6',
strings: 'M4 5h9M8.5 3v2M11 5c-.8 3.8-3.4 6.6-7 8M6.5 8.5c1.1 1.6 2.7 3 4.5 3.8M13 21l4-9 4 9M14.4 18h5.2', strings: 'M4 5h9M8.5 3v2M11 5c-.8 3.8-3.4 6.6-7 8M6.5 8.5c1.1 1.6 2.7 3 4.5 3.8M13 21l4-9 4 9M14.4 18h5.2',
}; };
@ -101,25 +103,27 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
const [armed, setArmed] = useState(false); const [armed, setArmed] = useState(false);
// On by default only when it is from the signed store or declares its permissions and the code // On by default only when it is from the signed store or declares its permissions and the code
// scan found nothing to point out; otherwise the owner turns it on deliberately. // scan found nothing to point out; otherwise the owner turns it on deliberately.
const [enable, setEnable] = useState(preview.kind === 'theme' || preview.kind === 'strings' || (!preview.existing && (preview.source.signed || (preview.plugin?.permissions != null && preview.findings.length === 0)))); const [enable, setEnable] = useState(preview.kind === 'theme' || preview.kind === 'strings' || preview.kind === 'icons' || (!preview.existing && (preview.source.signed || (preview.plugin?.permissions != null && preview.findings.length === 0))));
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
useEffect(() => { const timer = setTimeout(() => setArmed(true), REVIEW_MS); return () => clearTimeout(timer); }, [preview.token]); useEffect(() => { const timer = setTimeout(() => setArmed(true), REVIEW_MS); return () => clearTimeout(timer); }, [preview.token]);
const strings = preview.kind === 'strings' ? preview.strings ?? null : null; const strings = preview.kind === 'strings' ? preview.strings ?? null : null;
const summary = strings ? props.stringsSummary?.(preview.text) ?? null : null; const summary = strings ? props.stringsSummary?.(preview.text) ?? null : null;
const name = plugin?.name ?? facts?.name ?? preview.theme?.name ?? strings?.name ?? t('wb.install.untitled'); const pack = preview.kind === 'icons' ? request.pack ?? null : null;
const author = plugin?.author || facts?.author || preview.theme?.author || strings?.authors.join(', ') || ''; const icons = preview.kind === 'icons' ? preview.icons ?? null : null;
const name = plugin?.name ?? facts?.name ?? preview.theme?.name ?? strings?.name ?? pack?.name ?? icons?.name ?? t('wb.install.untitled');
const author = plugin?.author || facts?.author || preview.theme?.author || strings?.authors.join(', ') || pack?.author || icons?.author || '';
const version = preview.version || preview.store?.version || ''; const version = preview.version || preview.store?.version || '';
const updating = preview.existing && !preview.existing.same; const updating = preview.existing && !preview.existing.same;
const verb = preview.existing?.same ? t('wb.install.reinstall') : updating || ready?.replaces ? t('wb.install.update') : t('wb.store.install'); const verb = preview.existing?.same ? t('wb.install.reinstall') : updating || ready?.replaces ? t('wb.install.update') : t('wb.store.install');
const step = preview.existing?.same ? 'reinstall' : updating || ready?.replaces ? 'update' : 'install'; const step = preview.existing?.same ? 'reinstall' : updating || ready?.replaces ? 'update' : 'install';
const eyebrow = preview.kind === 'strings' ? t(`wb.install.eyebrow.strings.${step}`) : t(`wb.install.eyebrow.${step}`, { kind: preview.kind }); const eyebrow = preview.kind === 'strings' ? t(`wb.install.eyebrow.strings.${step}`) : preview.kind === 'icons' ? t(`wb.install.eyebrow.icons.${step}`) : t(`wb.install.eyebrow.${step}`, { kind: preview.kind });
const badges = preview.kind === 'plugin' ? permissionBadges(plugin?.permissions, t, site) : []; const badges = preview.kind === 'plugin' ? permissionBadges(plugin?.permissions, t, site) : [];
const installing = request.status === 'installing'; const installing = request.status === 'installing';
const description = plugin?.description || facts?.description || strings?.description; const description = plugin?.description || facts?.description || strings?.description || pack?.description;
return <> return <>
<header className="wbi-head"> <header className="wbi-head">
<div className={`wbi-tile is-${preview.kind}`} style={facts?.tile ? { background: facts.tile.background, color: facts.tile.color, boxShadow: `inset 0 0 0 1px ${facts.tile.border}` } : undefined}> <div className={`wbi-tile is-${preview.kind}`} style={facts?.tile ? { background: facts.tile.background, color: facts.tile.color, boxShadow: `inset 0 0 0 1px ${facts.tile.border}` } : undefined}>
<Glyph d={preview.kind === 'plugin' ? G.plugin : preview.kind === 'strings' ? G.strings : G.theme} size={22}/> <Glyph d={preview.kind === 'plugin' ? G.plugin : preview.kind === 'strings' ? G.strings : preview.kind === 'icons' ? G.icons : G.theme} size={22}/>
</div> </div>
<div className="wbi-title"> <div className="wbi-title">
<span className="wbi-eyebrow">{eyebrow}</span> <span className="wbi-eyebrow">{eyebrow}</span>
@ -184,13 +188,27 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
{summary && summary.sample.length > 0 && <div className="wbi-findings"><strong>{t('wb.install.strings.sample')}</strong>{summary.sample.map(text => <span key={text}>{text}</span>)}</div>} {summary && summary.sample.length > 0 && <div className="wbi-findings"><strong>{t('wb.install.strings.sample')}</strong>{summary.sample.map(text => <span key={text}>{text}</span>)}</div>}
</section>} </section>}
{pack && <section className="wbi-perms wbi-icons" aria-label={t('wb.store.iconsItem')}>
<p className="wbi-note is-ok"><Glyph d={G.check} size={14}/>{t('wb.install.icons.dataOnly')}</p>
<dl className="wbi-facts">
<Fact label={t('wb.install.icons.license')}>{pack.license}</Fact>
<Fact label={t('wb.install.icons.count')}>{t('wb.install.icons.countValue', { count: Object.keys(pack.glyphs).length })}</Fact>
{pack.source && <Fact label={t('wb.install.icons.source')} wide>{pack.source}</Fact>}
{pack.credits && <Fact label={t('wb.install.credits')} wide>{pack.credits}</Fact>}
</dl>
<div className="wbi-pack-grid" aria-hidden="true">
{(Object.keys(pack.glyphs) as Array<keyof typeof pack.glyphs>).map(glyph => <span key={glyph} title={glyph}><svg viewBox="0 0 24 24"><GlyphPaths glyph={pack.glyphs[glyph]!} pack={pack}/></svg></span>)}
</div>
{(ready?.warnings.length ?? 0) > 0 && <ul className="wbi-warnings">{ready!.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>}
</section>}
{theme !== null && <section className="wbi-theme"> {theme !== null && <section className="wbi-theme">
{props.renderThemePreview?.(theme)} {props.renderThemePreview?.(theme)}
{(ready?.warnings.length ?? 0) > 0 && <ul className="wbi-warnings">{ready!.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>} {(ready?.warnings.length ?? 0) > 0 && <ul className="wbi-warnings">{ready!.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>}
</section>} </section>}
{facts?.css ? <CodePreview t={t} text={facts.css} label={t('wb.install.themeCss', { site })}/> : null} {facts?.css ? <CodePreview t={t} text={facts.css} label={t('wb.install.themeCss', { site })}/> : null}
<CodePreview t={t} text={preview.text} label={preview.kind === 'plugin' ? t('wb.install.code') : preview.kind === 'strings' ? t('wb.install.strings.file') : t('wb.install.themeFile')}/> <CodePreview t={t} text={preview.text} label={preview.kind === 'plugin' ? t('wb.install.code') : preview.kind === 'strings' ? t('wb.install.strings.file') : preview.kind === 'icons' ? t('wb.install.icons.file') : t('wb.install.themeFile')}/>
</div> </div>
<footer className="wbi-foot"> <footer className="wbi-foot">
@ -216,6 +234,8 @@ function Done<Theme>({ request, props }: { request: Extract<InstallRequest<Theme
? (request.enabled ? t('wb.install.done.pluginOn', { site }) : t('wb.install.done.pluginOff')) ? (request.enabled ? t('wb.install.done.pluginOn', { site }) : t('wb.install.done.pluginOff'))
: request.kind === 'strings' : request.kind === 'strings'
? (request.enabled ? t('wb.install.done.stringsOn', { site }) : t('wb.install.done.stringsOff')) ? (request.enabled ? t('wb.install.done.stringsOn', { site }) : t('wb.install.done.stringsOff'))
: request.kind === 'icons'
? (request.enabled ? t('wb.install.done.iconsOn') : t('wb.install.done.iconsOff'))
: (request.enabled ? t('wb.install.done.themeOn') : t('wb.install.done.themeOff'))}</p> : (request.enabled ? t('wb.install.done.themeOn') : t('wb.install.done.themeOff'))}</p>
{request.fonts.length > 0 && <p className="wbi-muted">{t('wb.install.done.fonts', { fonts: request.fonts.join(', ') })}</p>} {request.fonts.length > 0 && <p className="wbi-muted">{t('wb.install.done.fonts', { fonts: request.fonts.join(', ') })}</p>}
<div className="wbi-state-actions"> <div className="wbi-state-actions">

View file

@ -8,7 +8,7 @@
import { useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from 'react'; import { useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from 'react';
import type { InstallController } from './installController.ts'; import type { InstallController } from './installController.ts';
import type { StoreText } from './storeMessages.ts'; import type { StoreText } from './storeMessages.ts';
import { categoryLabel, errorText, filterItems, itemState, permissionBadges, type ItemState, type StoreCatalogView, type StoreItem } from './storeModel.ts'; import { categoryLabel, errorText, filterItems, itemState, permissionBadges, type ItemState, type StoreCatalogView, type StoreItem, type StoreKind } from './storeModel.ts';
type ButtonProps = { children: ReactNode; onClick?(): void; tone?: 'plain' | 'primary' | 'ghost' | 'danger'; size?: 'sm' | 'md'; disabled?: boolean; title?: string }; type ButtonProps = { children: ReactNode; onClick?(): void; tone?: 'plain' | 'primary' | 'ghost' | 'danger'; size?: 'sm' | 'md'; disabled?: boolean; title?: string };
type Option<T extends string> = { value: T; label: string }; type Option<T extends string> = { value: T; label: string };
@ -46,6 +46,14 @@ export type StoreViewProps<Theme> = {
/** Theme ids that ship with the app, and the owner's own theme ids now. */ /** Theme ids that ship with the app, and the owner's own theme ids now. */
builtinThemes: readonly string[]; builtinThemes: readonly string[];
userThemes: readonly string[]; userThemes: readonly string[];
/** The owner's installed icon pack ids now (an icon pack the owner removed in Appearance shows as installable again). */
userIcons?: readonly string[];
/**
* The app's area plugins, for items of kind `builtin`: whether the app has one by this id, whether
* its switch is on, and turning it on or off. Without it (or for an id it does not have) a built-in
* item only says it is built in.
*/
areas?: { has(id: string): boolean; on(id: string): boolean; set(id: string, on: boolean): Promise<void> };
/** Removes an installed item (plugin file, or the owner's copy of a store theme); false: nothing to remove. */ /** Removes an installed item (plugin file, or the owner's copy of a store theme); false: nothing to remove. */
onRemove(item: StoreItem, view: StoreCatalogView): Promise<boolean>; onRemove(item: StoreItem, view: StoreCatalogView): Promise<boolean>;
/** Makes a built-in theme the current one. */ /** Makes a built-in theme the current one. */
@ -70,9 +78,18 @@ function Preview({ item }: { item: StoreItem }) {
</div>; </div>;
} }
function Action({ item, state, busy, t, ui, onInstall, onRemove, onUse }: { item: StoreItem; state: ItemState; busy: boolean; t: StoreText; ui: StoreControls; onInstall(): void; onRemove(): void; onUse(): void }) { function Action({ item, state, busy, t, ui, areas, onInstall, onRemove, onUse, onArea }: { item: StoreItem; state: ItemState; busy: boolean; t: StoreText; ui: StoreControls; areas?: StoreViewProps<unknown>['areas']; onInstall(): void; onRemove(): void; onUse(): void; onArea(on: boolean): void }) {
const { Button } = ui; const { Button } = ui;
const [asking, setAsking] = useState(false); const [asking, setAsking] = useState(false);
if (state.state === 'area') {
const known = areas?.has(item.id) ?? false;
const on = known && areas!.on(item.id);
return <div className="wbs-actions"><span className="wbs-state">{t('wb.store.builtinItem')}{known && ` · ${on ? t('wb.store.areaOn') : t('wb.store.areaOff')}`}</span>
{known && <label className="wbs-switch" title={t('wb.store.areaSwitch', { name: item.name })}>
<input type="checkbox" role="switch" checked={on} aria-label={t('wb.store.areaSwitch', { name: item.name })} onChange={event => onArea(event.target.checked)}/><span aria-hidden="true"/>
</label>}
</div>;
}
if (state.state === 'builtin') return <div className="wbs-actions"><span className="wbs-state">{t('wb.store.builtIn')}</span><Button size="sm" onClick={onUse}>{t('wb.store.use')}</Button></div>; if (state.state === 'builtin') return <div className="wbs-actions"><span className="wbs-state">{t('wb.store.builtIn')}</span><Button size="sm" onClick={onUse}>{t('wb.store.use')}</Button></div>;
if (state.state === 'install') return <div className="wbs-actions"><Button size="sm" tone="primary" disabled={busy} onClick={onInstall}>{t('wb.store.install')}</Button></div>; if (state.state === 'install') return <div className="wbs-actions"><Button size="sm" tone="primary" disabled={busy} onClick={onInstall}>{t('wb.store.install')}</Button></div>;
const remove = asking const remove = asking
@ -90,7 +107,7 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
const [view, setView] = useState<StoreCatalogView | null>(null); const [view, setView] = useState<StoreCatalogView | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const [kind, setKind] = useState<'all' | 'theme' | 'plugin' | 'strings'>('all'); const [kind, setKind] = useState<StoreKind | 'all'>('all');
const [category, setCategory] = useState<string>('all'); const [category, setCategory] = useState<string>('all');
const request = useSyncExternalStore(controller.subscribe, controller.current, controller.current); const request = useSyncExternalStore(controller.subscribe, controller.current, controller.current);
@ -109,7 +126,7 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
useEffect(() => { if (request === null) void load(false); }, [request === null]); useEffect(() => { if (request === null) void load(false); }, [request === null]);
const items = view?.catalog?.items ?? []; const items = view?.catalog?.items ?? [];
const context = { plugins: view?.plugins ?? {}, records: view?.records.items ?? {}, builtinThemes: props.builtinThemes, userThemes: props.userThemes }; const context = { plugins: view?.plugins ?? {}, records: view?.records.items ?? {}, builtinThemes: props.builtinThemes, userThemes: props.userThemes, userIcons: props.userIcons };
const categories = useMemo(() => [...new Set(items.filter(item => kind === 'all' || item.kind === kind).map(item => item.category))].sort(), [items, kind]); const categories = useMemo(() => [...new Set(items.filter(item => kind === 'all' || item.kind === kind).map(item => item.category))].sort(), [items, kind]);
const shown = filterItems(items, query, kind, category); const shown = filterItems(items, query, kind, category);
const updates = items.filter(item => itemState(item, context).state === 'update'); const updates = items.filter(item => itemState(item, context).state === 'update');
@ -137,7 +154,7 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
<p className="wbs-intro">{t('wb.store.intro')}</p> <p className="wbs-intro">{t('wb.store.intro')}</p>
<div className="wbs-toolbar"> <div className="wbs-toolbar">
<SearchField label={t('wb.store.search')} placeholder={t('wb.store.searchPlaceholder')} value={query} onChange={setQuery}/> <SearchField label={t('wb.store.search')} placeholder={t('wb.store.searchPlaceholder')} value={query} onChange={setQuery}/>
<Segmented label={t('wb.store.kind')} size="sm" value={kind} onChange={next => { setKind(next); setCategory('all'); }} options={[{ value: 'all', label: t('wb.store.all') }, { value: 'theme', label: t('wb.store.themes') }, { value: 'plugin', label: t('wb.store.pluginsTab') }, ...(items.some(item => item.kind === 'strings') ? [{ value: 'strings' as const, label: t('wb.store.strings') }] : [])]}/> <Segmented label={t('wb.store.kind')} size="sm" value={kind} onChange={next => { setKind(next); setCategory('all'); }} options={[{ value: 'all', label: t('wb.store.all') }, { value: 'theme', label: t('wb.store.themes') }, { value: 'plugin', label: t('wb.store.pluginsTab') }, ...(items.some(item => item.kind === 'icons') ? [{ value: 'icons' as const, label: t('wb.store.icons') }] : []), ...(items.some(item => item.kind === 'strings') ? [{ value: 'strings' as const, label: t('wb.store.strings') }] : []), ...(items.some(item => item.kind === 'builtin') ? [{ value: 'builtin' as const, label: t('wb.store.builtinTab') }] : [])]}/>
<Button size="sm" tone="ghost" disabled={loading} onClick={() => void load(true)}>{loading ? t('wb.store.checking') : t('wb.store.refresh')}</Button> <Button size="sm" tone="ghost" disabled={loading} onClick={() => void load(true)}>{loading ? t('wb.store.checking') : t('wb.store.refresh')}</Button>
</div> </div>
<div className="wbs-cats" role="group" aria-label={t('wb.store.categories')}> <div className="wbs-cats" role="group" aria-label={t('wb.store.categories')}>
@ -159,14 +176,15 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
<div className="wbs-card-body"> <div className="wbs-card-body">
<header> <header>
<h3>{item.name}</h3> <h3>{item.name}</h3>
<Badge>{item.kind === 'theme' ? t('wb.store.theme') : item.kind === 'strings' ? t('wb.store.stringsItem') : t('wb.store.plugin')}</Badge> <Badge>{item.kind === 'theme' ? t('wb.store.theme') : item.kind === 'strings' ? t('wb.store.stringsItem') : item.kind === 'icons' ? t('wb.store.iconsItem') : item.kind === 'builtin' ? t('wb.store.builtinItem') : t('wb.store.plugin')}</Badge>
</header> </header>
<p className="wbs-meta">{item.author && `${t('wb.store.by', { author: item.author })} · `}v{item.version} · {item.kind === 'strings' && item.language ? item.language : categoryLabel(item.category, t)}{item.license ? ` · ${item.license}` : ''}</p> <p className="wbs-meta">{item.author && `${t('wb.store.by', { author: item.author })} · `}v{item.version} · {item.kind === 'strings' && item.language ? item.language : categoryLabel(item.category, t)}{item.license ? ` · ${item.license}` : ''}</p>
<p className="wbs-desc">{item.description}</p> <p className="wbs-desc">{item.description}</p>
{item.kind === 'plugin' && <ul className="wbs-perms" aria-label={t('wb.store.permissions')}> {item.kind === 'plugin' && <ul className="wbs-perms" aria-label={t('wb.store.permissions')}>
{permissionBadges(item.permissions, t, site).map(badge => <li key={badge.id} className={`is-${badge.tone}`} title={badge.detail}>{badge.label}</li>)} {permissionBadges(item.permissions, t, site).map(badge => <li key={badge.id} className={`is-${badge.tone}`} title={badge.detail}>{badge.label}</li>)}
</ul>} </ul>}
<Action item={item} state={state} busy={request !== null} t={t} ui={ui} <Action item={item} state={state} busy={request !== null} t={t} ui={ui} areas={props.areas}
onArea={on => void props.areas?.set(item.id, on).catch(error => notify(errorText(error), true))}
onInstall={() => void controller.requestStoreItem(item)} onInstall={() => void controller.requestStoreItem(item)}
onRemove={() => void removeItem(item)} onRemove={() => void removeItem(item)}
onUse={() => void props.onUse(item).then(() => notify(t('wb.store.themeNow', { name: item.name }))).catch(error => notify(errorText(error), true))}/> onUse={() => void props.onUse(item).then(() => notify(t('wb.store.themeNow', { name: item.name }))).catch(error => notify(errorText(error), true))}/>

View file

@ -1,11 +1,12 @@
// The install screen's state machine, shared by every wayBetter app. Requests come from // The install screen's state machine, shared by every wayBetter app. Requests come from
// `waybetter://install` links (the native `install-link` event, plus links that arrived before the // `waybetter://install` links (the native `install-link` event, plus links that arrived before the
// shell listened), files dropped on the window and the Store view. Each request is staged natively // shell listened), files dropped on the window, files the OS handed over ("Open with") and the Store view. Each request is staged natively
// (downloaded/validated, hashed) and shown on the install screen; nothing is written until the owner // (downloaded/validated, hashed) and shown on the install screen; nothing is written until the owner
// presses Install there. The app supplies how it talks to native code (Tauri `invoke`/`listen`) and // presses Install there. The app supplies how it talks to native code (Tauri `invoke`/`listen`) and
// how its themes are parsed and saved; plugins need nothing app-specific. // how its themes are parsed and saved; plugins need nothing app-specific.
import { freeThemeId, installedThemeId, kindForFile, MAX_FILE_BYTES, errorText, type InstallKind, type InstallPreview, type InstallRecord, type LinkEvent, type StoreItem } from './storeModel.ts'; import { parseIconPackJson, type IconPack } from '../../runtime/src/themeIcons.ts';
import { freeThemeId, installedThemeId, kindForFile, MAX_FILE_BYTES, errorText, type InstallKind, type InstallPreview, type InstallRecord, type LinkEvent, type OpenedFile, type StoreItem } from './storeModel.ts';
import type { StoreText } from './storeMessages.ts'; import type { StoreText } from './storeMessages.ts';
/** How the controller reaches native code (the app passes Tauri's `invoke` and `listen`). */ /** How the controller reaches native code (the app passes Tauri's `invoke` and `listen`). */
@ -46,8 +47,8 @@ export type ThemeAdapter<Theme> = {
export type InstallRequest<Theme> = export type InstallRequest<Theme> =
| { status: 'loading'; title: string; detail: string } | { status: 'loading'; title: string; detail: string }
| { status: 'ready'; preview: InstallPreview; theme: Theme | null; warnings: string[]; replaces: string | null } | { status: 'ready'; preview: InstallPreview; theme: Theme | null; warnings: string[]; replaces: string | null; pack?: IconPack | null }
| { status: 'installing'; preview: InstallPreview; theme: Theme | null } | { status: 'installing'; preview: InstallPreview; theme: Theme | null; pack?: IconPack | null }
| { status: 'done'; kind: InstallKind; name: string; themeId?: string; fonts: string[]; enabled: boolean } | { status: 'done'; kind: InstallKind; name: string; themeId?: string; fonts: string[]; enabled: boolean }
| { status: 'error'; title: string; message: string }; | { status: 'error'; title: string; message: string };
@ -62,6 +63,12 @@ export type InstallControllerOptions<Theme> = {
onPluginsChanged?(): void; onPluginsChanged?(): void;
/** A theme was installed (the app refreshes its store/theme views). */ /** A theme was installed (the app refreshes its store/theme views). */
onThemesChanged?(): void; onThemesChanged?(): void;
/**
* Adds the icon pack the owner confirmed (already sanitized) to the app's icon packs, replacing
* one with the same id, and makes it the current pack when `enable`. Absent: icon packs cannot
* be installed (the screen says so).
*/
icons?: { save(pack: IconPack, options: { enable: boolean }): Promise<void> };
/** A string pack was installed (the app hands the site tabs the packs that are on). */ /** A string pack was installed (the app hands the site tabs the packs that are on). */
onStringsChanged?(): void | Promise<void>; onStringsChanged?(): void | Promise<void>;
/** /**
@ -78,6 +85,8 @@ export type InstallController<Theme> = {
requestLink(link: { kind: InstallKind; url: string }): Promise<void>; requestLink(link: { kind: InstallKind; url: string }): Promise<void>;
/** A file dropped on the window. */ /** A file dropped on the window. */
requestFile(file: { name: string; size: number; text(): Promise<string> }): Promise<void>; requestFile(file: { name: string; size: number; text(): Promise<string> }): Promise<void>;
/** A file the OS handed to the app ("Open with", double-click), asked for by its id: staged natively like a dropped file. */
requestOpened(file: OpenedFile): Promise<void>;
/** A store item: downloaded natively and checked against the signed catalog. */ /** A store item: downloaded natively and checked against the signed catalog. */
requestStoreItem(item: StoreItem): Promise<void>; requestStoreItem(item: StoreItem): Promise<void>;
linkRejected(error: string): void; linkRejected(error: string): void;
@ -106,6 +115,12 @@ export function createInstallController<Theme>(options: InstallControllerOptions
/** Parses a staged theme the way the app's import does, and finds the theme it would update. */ /** Parses a staged theme the way the app's import does, and finds the theme it would update. */
async function prepared(preview: InstallPreview): Promise<InstallRequest<Theme>> { async function prepared(preview: InstallPreview): Promise<InstallRequest<Theme>> {
if (preview.kind === 'plugin' || preview.kind === 'strings') return { status: 'ready', preview, theme: null, warnings: [], replaces: null }; if (preview.kind === 'plugin' || preview.kind === 'strings') return { status: 'ready', preview, theme: null, warnings: [], replaces: null };
if (preview.kind === 'icons') {
if (!options.icons) return { status: 'error', title: t('wb.install.err.icons'), message: t('wb.install.err.iconsNone', { site: options.site }) };
const parsed = parseIconPackJson(preview.text);
if ('error' in parsed) return { status: 'error', title: t('wb.install.err.icons'), message: parsed.error };
return { status: 'ready', preview, theme: null, warnings: parsed.warnings, replaces: null, pack: parsed.pack };
}
const parsed = themes.parse(preview.text); const parsed = themes.parse(preview.text);
if ('error' in parsed) return { status: 'error', title: t('wb.install.err.theme'), message: parsed.error }; if ('error' in parsed) return { status: 'error', title: t('wb.install.err.theme'), message: parsed.error };
const userThemes = await themes.userThemes(); const userThemes = await themes.userThemes();
@ -142,16 +157,20 @@ export function createInstallController<Theme>(options: InstallControllerOptions
return; return;
} }
if (file.size > MAX_FILE_BYTES[kind]) { if (file.size > MAX_FILE_BYTES[kind]) {
set({ status: 'error', title: t('wb.install.err.large', { file: file.name }), message: kind === 'strings' ? t('wb.install.err.stringsLarge') : t('wb.install.err.largeHint', { kind }) }); set({ status: 'error', title: t('wb.install.err.large', { file: file.name }), message: kind === 'strings' ? t('wb.install.err.stringsLarge') : kind === 'icons' ? t('wb.install.err.iconsLarge') : t('wb.install.err.largeHint', { kind }) });
return; return;
} }
await stage(t('wb.install.stage.named', { name: file.name }), t('wb.install.stage.fileDetail'), async () => backend.invoke<InstallPreview>('install_stage_file', { name: file.name, text: await file.text() })); await stage(t('wb.install.stage.named', { name: file.name }), t('wb.install.stage.fileDetail'), async () => backend.invoke<InstallPreview>('install_stage_file', { name: file.name, text: await file.text() }));
}, },
requestOpened(file) {
return stage(t('wb.install.stage.named', { name: file.name }), t('wb.install.stage.fileDetail'), () => backend.invoke<InstallPreview>('install_stage_opened', { id: file.id }));
},
requestStoreItem(item) { requestStoreItem(item) {
return stage(t('wb.install.stage.named', { name: item.name }), t('wb.install.stage.storeDetail'), () => backend.invoke<InstallPreview>('store_stage', { item: { kind: item.kind, id: item.id } })); return stage(t('wb.install.stage.named', { name: item.name }), t('wb.install.stage.storeDetail'), () => backend.invoke<InstallPreview>('store_stage', { item: { kind: item.kind, id: item.id } }));
}, },
linkRejected(error) { linkRejected(error) {
set({ status: 'error', title: t('wb.install.err.link'), message: error.replace(/^LINK: /, '') }); // `FILE:` errors are about a file the OS handed over, `LINK:` ones about a link.
set({ status: 'error', title: error.startsWith('FILE: ') ? t('wb.install.err.opened') : t('wb.install.err.link'), message: error.replace(/^(LINK|FILE): /, '') });
}, },
async cancel() { async cancel() {
const request = current; const request = current;
@ -163,8 +182,18 @@ export function createInstallController<Theme>(options: InstallControllerOptions
const request = current; const request = current;
if (!request || request.status !== 'ready') return; if (!request || request.status !== 'ready') return;
const { preview } = request; const { preview } = request;
set({ status: 'installing', preview, theme: request.theme }); set({ status: 'installing', preview, theme: request.theme, pack: request.pack });
try { try {
if (preview.kind === 'icons') {
const outcome = await backend.invoke<{ iconsText: string | null }>('install_commit', { token: preview.token, enable, themeId: null });
// The exact bytes native code staged and hashed; parsed and sanitized again here.
const parsed = parseIconPackJson(outcome.iconsText ?? '');
if ('error' in parsed) throw new Error(parsed.error);
await options.icons!.save(parsed.pack, { enable });
options.onThemesChanged?.();
set({ status: 'done', kind: 'icons', name: parsed.pack.name, fonts: [], enabled: enable });
return;
}
if (preview.kind === 'plugin') { if (preview.kind === 'plugin') {
await backend.invoke('install_commit', { token: preview.token, enable, themeId: null }); await backend.invoke('install_commit', { token: preview.token, enable, themeId: null });
options.onPluginsChanged?.(); options.onPluginsChanged?.();
@ -189,7 +218,7 @@ export function createInstallController<Theme>(options: InstallControllerOptions
options.onThemesChanged?.(); options.onThemesChanged?.();
set({ status: 'done', kind: 'theme', name: themes.facts(parsed.theme).name, themeId: id, fonts: saved.fonts, enabled: saved.enabled }); set({ status: 'done', kind: 'theme', name: themes.facts(parsed.theme).name, themeId: id, fonts: saved.fonts, enabled: saved.enabled });
} catch (error) { } catch (error) {
set({ status: 'error', title: preview.kind === 'strings' ? t('wb.install.err.stringsNotInstalled') : t('wb.install.err.notInstalled', { kind: preview.kind }), message: errorText(error) }); set({ status: 'error', title: preview.kind === 'strings' ? t('wb.install.err.stringsNotInstalled') : preview.kind === 'icons' ? t('wb.install.err.iconsNotInstalled') : t('wb.install.err.notInstalled', { kind: preview.kind }), message: errorText(error) });
} }
}, },
start() { start() {
@ -198,6 +227,7 @@ export function createInstallController<Theme>(options: InstallControllerOptions
const handle = (event: LinkEvent) => { const handle = (event: LinkEvent) => {
if (event.setup) options.onSetupLink?.(event.setup); if (event.setup) options.onSetupLink?.(event.setup);
else if (event.link) void controller.requestLink(event.link); else if (event.link) void controller.requestLink(event.link);
else if (event.opened) void controller.requestOpened(event.opened);
else if (event.error) controller.linkRejected(event.error); else if (event.error) controller.linkRejected(event.error);
}; };
// Native code queues every link and also emits it; a handled event clears the queue so a // Native code queues every link and also emits it; a handled event clears the queue so a

View file

@ -2,6 +2,7 @@
// app's built-in and own themes, and removal of installed items. Native code verifies the catalog's // app's built-in and own themes, and removal of installed items. Native code verifies the catalog's
// Ed25519 signature, keeps the app's items, then checks each download's sha256. Installing always // Ed25519 signature, keeps the app's items, then checks each download's sha256. Installing always
// goes through the shell's install screen (InstallDialog), never straight from here. // goes through the shell's install screen (InstallDialog), never straight from here.
import { areaFlag, type FeatureTable } from '../../../runtime/src/featureTable.ts';
import { invoke } from '../frame/bridge.ts'; import { invoke } from '../frame/bridge.ts';
import { useT } from '../frame/hooks.ts'; import { useT } from '../frame/hooks.ts';
import { relativeTime } from '../frame/i18n.ts'; import { relativeTime } from '../frame/i18n.ts';
@ -10,6 +11,7 @@ import type { StoreCatalogView, StoreItem } from '../storeModel.ts';
import { StoreView, type StoreControls } from '../StoreView.tsx'; import { StoreView, type StoreControls } from '../StoreView.tsx';
import '../store.css'; import '../store.css';
import { Badge, Button, EmptyState, SearchField, Segmented, useSettingsQuery } from './controls.tsx'; import { Badge, Button, EmptyState, SearchField, Segmented, useSettingsQuery } from './controls.tsx';
import { featureTable, flagsChanged, useFlags } from './PluginFeatures.tsx';
import { panelSite, panelThemes, type Notify } from './site.ts'; import { panelSite, panelThemes, type Notify } from './site.ts';
import { useThemeState } from './themes.ts'; import { useThemeState } from './themes.ts';
import './plugins.css'; import './plugins.css';
@ -17,15 +19,44 @@ import './plugins.css';
const CONTROLS: Partial<StoreControls> = { Button, SearchField, Segmented, EmptyState, Badge }; const CONTROLS: Partial<StoreControls> = { Button, SearchField, Segmented, EmptyState, Badge };
const RELOAD_ON = ['bt-plugins-changed', 'bt-store-changed', 'bt-strings-changed']; const RELOAD_ON = ['bt-plugins-changed', 'bt-store-changed', 'bt-strings-changed'];
type Areas = NonNullable<Parameters<typeof StoreView>[0]['areas']>;
/** The Store with the app's area plugins as switches for its built-in items (an app without a feature table has none). */
export function StoreSection({ notify }: { notify: Notify }) { export function StoreSection({ notify }: { notify: Notify }) {
const table = featureTable();
return table ? <WithAreas table={table} notify={notify}/> : <Store notify={notify}/>;
}
function WithAreas({ table, notify }: { table: FeatureTable; notify: Notify }) {
const [flags, choose] = useFlags(table, notify);
const areas: Areas = {
has: id => table.areas.some(area => area.id === id),
on: id => flags?.[areaFlag(id)] ?? false,
set: async (id, on) => { if (await choose({ [areaFlag(id)]: on })) flagsChanged(); },
};
return <Store notify={notify} areas={flags ? areas : undefined}/>;
}
function Store({ notify, areas }: { notify: Notify; areas?: Areas }) {
const t = useT(); const t = useT();
const { store, catalog } = panelThemes(); const { store, catalog } = panelThemes();
const themes = useThemeState(); const themes = useThemeState();
const settingsQuery = useSettingsQuery(); const settingsQuery = useSettingsQuery();
if (settingsQuery) return null; if (settingsQuery) return null;
const userThemes = themes.choice.themes.map(theme => theme.id); const userThemes = themes.choice.themes.map(theme => theme.id);
const userIcons = (themes.choice.packs ?? []).map(pack => pack.id);
async function remove(item: StoreItem, view: StoreCatalogView): Promise<boolean> { async function remove(item: StoreItem, view: StoreCatalogView): Promise<boolean> {
if (item.kind === 'builtin') return false;
if (item.kind === 'icons') {
const found = Object.entries(view.records.items).find(([key, value]) => key.startsWith('icons:') && value.storeId === item.id && userIcons.includes(key.slice(6)));
const id = found?.[0].slice(6);
if (!id) return false;
const choice = themes.choice;
await store.setChoice({ ...choice, packs: (choice.packs ?? []).filter(pack => pack.id !== id), ...(choice.icons === id ? { icons: undefined } : {}) });
await invoke('install_forget', { kind: 'icons', name: id });
return true;
}
if (item.kind === 'strings') { if (item.kind === 'strings') {
await invoke('strings_remove', { id: item.id }); await invoke('strings_remove', { id: item.id });
window.dispatchEvent(new CustomEvent('bt-strings-changed')); window.dispatchEvent(new CustomEvent('bt-strings-changed'));
@ -52,6 +83,8 @@ export function StoreSection({ notify }: { notify: Notify }) {
controller={panelSite().store!.controller} controller={panelSite().store!.controller}
builtinThemes={catalog.builtins.map(theme => theme.id)} builtinThemes={catalog.builtins.map(theme => theme.id)}
userThemes={userThemes} userThemes={userThemes}
userIcons={userIcons}
areas={areas}
onRemove={remove} onRemove={remove}
onUse={item => store.setChoice({ ...themes.choice, preset: item.id, overrides: {}, accent: null })} onUse={item => store.setChoice({ ...themes.choice, preset: item.id, overrides: {}, accent: null })}
notify={notify} notify={notify}

View file

@ -228,3 +228,19 @@
/* String packs on the install screen: what is ignored or cannot be replaced yet. */ /* String packs on the install screen: what is ignored or cannot be replaced yet. */
.wbi-strings-notes { margin: 6px 0 0; padding-left: 18px; color: var(--wb-muted, inherit); font-size: 12.5px; } .wbi-strings-notes { margin: 6px 0 0; padding-left: 18px; color: var(--wb-muted, inherit); font-size: 12.5px; }
/* Icon packs on the install screen: every drawing of the pack, as the shell will draw it. */
.wbi-pack-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(32px, 1fr)); gap: 6px; padding: 8px 0 0; }
.wbi-pack-grid span { display: grid; place-items: center; height: 32px; border-radius: 8px; background: rgb(var(--wb-text-rgb) / .06); color: var(--wb-text); }
.wbi-pack-grid svg { width: 20px; height: 20px; }
/* The switch of a built-in (area plugin) item in the Store. */
.wbs-switch { position: relative; display: inline-block; width: 34px; height: 20px; flex: none; cursor: pointer; }
.wbs-switch input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; }
.wbs-switch span { position: absolute; inset: 0; border-radius: 999px; background: rgb(var(--wb-text-rgb) / .22); transition: background .15s; pointer-events: none; }
.wbs-switch span::after { content: ''; position: absolute; top: 2px; inset-inline-start: 2px; width: 16px; height: 16px; border-radius: 50%; background: #fff; transition: transform .15s; }
.wbs-switch input:checked + span { background: var(--wb-accent, #1d9bf0); }
.wbs-switch input:checked + span::after { transform: translateX(14px); }
.wbs-switch input:focus-visible + span { outline: 2px solid var(--wb-accent, #1d9bf0); outline-offset: 2px; }
[dir="rtl"] .wbs-switch input:checked + span::after { transform: translateX(-14px); }
@media (prefers-reduced-motion: reduce) { .wbs-switch span, .wbs-switch span::after { transition: none; } }

View file

@ -34,6 +34,7 @@ export const STORE_MESSAGES = {
'wb.store.category.tools': 'Tools', 'wb.store.category.tools': 'Tools',
'wb.store.category.dark': 'Dark', 'wb.store.category.dark': 'Dark',
'wb.store.category.light': 'Light', 'wb.store.category.light': 'Light',
'wb.store.category.icons': 'Icons',
'wb.store.builtIn': 'Built in', 'wb.store.builtIn': 'Built in',
'wb.store.use': 'Use', 'wb.store.use': 'Use',
'wb.store.install': 'Install', 'wb.store.install': 'Install',
@ -122,6 +123,29 @@ export const STORE_MESSAGES = {
'wb.install.openStrings': 'Open Languages', 'wb.install.openStrings': 'Open Languages',
'wb.store.strings': 'Languages', 'wb.store.strings': 'Languages',
'wb.store.stringsItem': 'String pack', 'wb.store.stringsItem': 'String pack',
'wb.install.eyebrow.icons.install': 'Install icon pack',
'wb.install.eyebrow.icons.update': 'Update icon pack',
'wb.install.eyebrow.icons.reinstall': 'Reinstall icon pack',
'wb.install.err.icons': 'This icon pack cannot be installed',
'wb.install.err.iconsNone': '{site} cannot install icon packs here.',
'wb.install.err.iconsLarge': 'Icon packs are limited to 120 KB.',
'wb.install.err.iconsNotInstalled': 'The icon pack was not installed',
'wb.install.err.opened': 'This file cannot be installed',
'wb.install.icons.dataOnly': 'Data only: drawings as path data and small pictures. No code and no styles; nothing in it runs.',
'wb.install.icons.license': 'License',
'wb.install.icons.source': 'Drawings from',
'wb.install.icons.count': 'Icons',
'wb.install.icons.countValue': '{count, plural, one {# icon} other {# icons}}',
'wb.install.icons.file': 'The pack file',
'wb.install.done.iconsOn': 'It is your icon pack now. Switch back any time in Appearance.',
'wb.install.done.iconsOff': 'It is in your icon packs in Appearance.',
'wb.store.icons': 'Icons',
'wb.store.iconsItem': 'Icon pack',
'wb.store.builtinTab': 'Built in',
'wb.store.builtinItem': 'Built in',
'wb.store.areaSwitch': 'Turn {name} on or off',
'wb.store.areaOn': 'On',
'wb.store.areaOff': 'Off',
'wb.strings.section': 'Languages', 'wb.strings.section': 'Languages',
'wb.strings.title': 'String packs', 'wb.strings.title': 'String packs',
'wb.strings.intro': 'A string pack replaces {site}’s own words with text: a language {site} does not offer, a better translation, or your own wording. Packs apply in this order; a later one wins where two change the same word. Words no pack changes stay exactly as {site} shows them.', 'wb.strings.intro': 'A string pack replaces {site}’s own words with text: a language {site} does not offer, a better translation, or your own wording. Packs apply in this order; a later one wins where two change the same word. Words no pack changes stay exactly as {site} shows them.',

View file

@ -6,7 +6,9 @@
import { STORE_MESSAGES, type StoreKey, type StoreText } from './storeMessages.ts'; import { STORE_MESSAGES, type StoreKey, type StoreText } from './storeMessages.ts';
import type { StringsInfo } from './stringPacksModel.ts'; import type { StringsInfo } from './stringPacksModel.ts';
export type InstallKind = 'theme' | 'plugin' | 'strings'; export type InstallKind = 'theme' | 'plugin' | 'strings' | 'icons';
/** What a catalog item can be: anything installable, or a feature that ships inside the app (`builtin`, shown with its switch). */
export type StoreKind = InstallKind | 'builtin';
export type SourceKind = 'store' | 'link' | 'file'; export type SourceKind = 'store' | 'link' | 'file';
export type PermissionTone = 'plain' | 'warn' | 'ok'; export type PermissionTone = 'plain' | 'warn' | 'ok';
export type PermissionBadge = { id: string; label: string; detail: string; tone: PermissionTone }; export type PermissionBadge = { id: string; label: string; detail: string; tone: PermissionTone };
@ -15,8 +17,9 @@ export type PermissionBadge = { id: string; label: string; detail: string; tone:
export type StoreItem = { export type StoreItem = {
/** The wayBetter apps it is for; native code only hands an app its own items. */ /** The wayBetter apps it is for; native code only hands an app its own items. */
apps?: string[]; apps?: string[];
kind: InstallKind; id: string; name: string; author: string; version: string; description: string; kind: StoreKind; id: string; name: string; author: string; version: string; description: string;
category: string; tags: string[]; url: string; file?: string; sha256: string; size: number; /** `url`, `sha256` and `size` are absent on a built-in item (nothing to download). */
category: string; tags: string[]; url?: string; file?: string; sha256?: string; size?: number;
preview?: string; permissions?: string[] | null; colors?: { bg: string; surface?: string; text: string; accent: string } | null; preview?: string; permissions?: string[] | null; colors?: { bg: string; surface?: string; text: string; accent: string } | null;
/** String packs: the pack's language tag. */ /** String packs: the pack's language tag. */
language?: string; language?: string;
@ -53,6 +56,8 @@ export type InstallPreview = {
version: string; version: string;
plugin: ScriptPluginMeta | null; plugin: ScriptPluginMeta | null;
theme: { name: string; author: string; description: string; cssChars: number } | null; theme: { name: string; author: string; description: string; cssChars: number } | null;
/** Icon packs: what the pack says about itself (the shell parses and draws the rest). */
icons?: { id: string; name: string; author: string; license: string; glyphs: number } | null;
/** String packs: what the pack says about itself (coverage comes from the site's inventory). */ /** String packs: what the pack says about itself (coverage comes from the site's inventory). */
strings?: StringsInfo | null; strings?: StringsInfo | null;
findings: string[]; findings: string[];
@ -61,7 +66,10 @@ export type InstallPreview = {
}; };
/** The `install-link` event and `install_pending` entries (waybetter-host `LinkEvent`). */ /** The `install-link` event and `install_pending` entries (waybetter-host `LinkEvent`). */
export type LinkEvent = { link?: { kind: InstallKind; url: string }; error?: string; setup?: string }; export type LinkEvent = { link?: { kind: InstallKind; url: string }; opened?: OpenedFile; error?: string; setup?: string };
/** A file the OS handed to the app ("Open with", double-click): its random id (`install_stage_opened`), name and what it would be. The path never reaches the shell. */
export type OpenedFile = { id: string; name: string; kind: InstallKind };
/** Plugin permissions (waybetter-host `PERMISSIONS`, runtime `permissions.ts`) and how much they allow. */ /** Plugin permissions (waybetter-host `PERMISSIONS`, runtime `permissions.ts`) and how much they allow. */
export const PERMISSION_TONES: Readonly<Record<string, PermissionTone>> = { export const PERMISSION_TONES: Readonly<Record<string, PermissionTone>> = {
@ -97,17 +105,18 @@ export function categoryLabel(id: string, t: StoreText): string {
return lookup(t, `wb.store.category.${id}`, undefined, id); return lookup(t, `wb.store.category.${id}`, undefined, id);
} }
/** What a dropped file is, by name: `.plugin.js` → plugin, `.strings.json` → string pack, `.json` → theme, else nothing. */ /** What a dropped file is, by name: `.plugin.js` → plugin, `.strings.json` → string pack, `.icons.json` → icon pack, `.json` → theme, else nothing. */
export function kindForFile(name: string): InstallKind | null { export function kindForFile(name: string): InstallKind | null {
const lower = name.toLowerCase(); const lower = name.toLowerCase();
if (lower.endsWith('.plugin.js')) return 'plugin'; if (lower.endsWith('.plugin.js')) return 'plugin';
if (lower.endsWith('.strings.json')) return 'strings'; if (lower.endsWith('.strings.json')) return 'strings';
if (lower.endsWith('.icons.json')) return 'icons';
if (lower.endsWith('.json')) return 'theme'; if (lower.endsWith('.json')) return 'theme';
return null; return null;
} }
/** Largest file the shell reads before handing it to native validation (same caps as native). */ /** Largest file the shell reads before handing it to native validation (same caps as native). */
export const MAX_FILE_BYTES: Readonly<Record<InstallKind, number>> = { theme: 2 * 1024 * 1024, plugin: 2 * 1024 * 1024, strings: 2 * 1024 * 1024 }; export const MAX_FILE_BYTES: Readonly<Record<InstallKind, number>> = { theme: 2 * 1024 * 1024, plugin: 2 * 1024 * 1024, strings: 2 * 1024 * 1024, icons: 120_000 };
/** A free theme id: `wanted`, else `wanted-2`, `-3`, … (the way an import names copies). */ /** A free theme id: `wanted`, else `wanted-2`, `-3`, … (the way an import names copies). */
export function freeThemeId(wanted: string, taken: Iterable<string>): string { export function freeThemeId(wanted: string, taken: Iterable<string>): string {
@ -133,6 +142,8 @@ export function newerVersion(a: string, b: string): boolean {
export type ItemState = export type ItemState =
| { state: 'install' } | { state: 'install' }
| { state: 'builtin' } | { state: 'builtin' }
/** A feature that ships inside the app (an area plugin); the Store shows its switch. */
| { state: 'area' }
| { state: 'installed'; version: string; enabled?: boolean } | { state: 'installed'; version: string; enabled?: boolean }
| { state: 'update'; version: string; enabled?: boolean } | { state: 'update'; version: string; enabled?: boolean }
/** Installed but changed locally (edited file, or a copy from somewhere else): the store leaves it alone unless asked. */ /** Installed but changed locally (edited file, or a copy from somewhere else): the store leaves it alone unless asked. */
@ -145,6 +156,8 @@ export type ItemContext = {
builtinThemes: readonly string[]; builtinThemes: readonly string[];
/** The owner's own theme ids right now. */ /** The owner's own theme ids right now. */
userThemes: readonly string[]; userThemes: readonly string[];
/** The owner's installed icon pack ids right now (absent: trust the install records). */
userIcons?: readonly string[];
}; };
/** /**
@ -161,6 +174,14 @@ export function itemState(item: StoreItem, context: ItemContext): ItemState {
if (newerVersion(item.version, installed.version)) return { state: 'update', ...base }; if (newerVersion(item.version, installed.version)) return { state: 'update', ...base };
return { state: 'modified', ...base }; return { state: 'modified', ...base };
} }
if (item.kind === 'builtin') return { state: 'area' };
if (item.kind === 'icons') {
const found = Object.entries(context.records).find(([key, value]) => key.startsWith('icons:') && value.storeId === item.id && (context.userIcons?.includes(key.slice(6)) ?? true));
if (!found) return { state: 'install' };
const [, value] = found;
if (value.sha256 === item.sha256) return { state: 'installed', version: value.version };
return newerVersion(item.version, value.version) ? { state: 'update', version: value.version } : { state: 'installed', version: value.version };
}
if (item.kind === 'strings') { if (item.kind === 'strings') {
const record = context.records[`strings:${item.id}`]; const record = context.records[`strings:${item.id}`];
if (!record) return { state: 'install' }; if (!record) return { state: 'install' };
@ -184,7 +205,7 @@ export function installedThemeId(item: StoreItem, records: Record<string, Instal
} }
/** Search and category filter for the store list. */ /** Search and category filter for the store list. */
export function filterItems(items: readonly StoreItem[], query: string, kind: InstallKind | 'all', category: string | 'all'): StoreItem[] { export function filterItems(items: readonly StoreItem[], query: string, kind: StoreKind | 'all', category: string | 'all'): StoreItem[] {
const words = query.toLowerCase().split(/\s+/).filter(Boolean); const words = query.toLowerCase().split(/\s+/).filter(Boolean);
return items.filter(item => (kind === 'all' || item.kind === kind) && (category === 'all' || item.category === category) return items.filter(item => (kind === 'all' || item.kind === kind) && (category === 'all' || item.category === category)
&& words.every(word => [item.name, item.description, item.author, item.category, item.language ?? '', ...item.tags, ...(item.permissions ?? [])].join(' ').toLowerCase().includes(word))); && words.every(word => [item.name, item.description, item.author, item.category, item.language ?? '', ...item.tags, ...(item.permissions ?? [])].join(' ').toLowerCase().includes(word)));

View file

@ -0,0 +1,144 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { formatMessage } from '../../runtime/src/i18n.ts';
import type { IconPack } from '../../runtime/src/themeIcons.ts';
import { createInstallController, type StoreBackend, type ThemeAdapter } from '../src/installController.ts';
import { STORE_MESSAGES, type StoreText } from '../src/storeMessages.ts';
import { filterItems, itemState, kindForFile, MAX_FILE_BYTES, type InstallKind, type InstallPreview, type StoreItem } from '../src/storeModel.ts';
const t: StoreText = (key, params) => formatMessage(STORE_MESSAGES[key], params);
const settle = () => new Promise(resolve => setTimeout(resolve, 0));
const THEME = '{"name":"Nord","id":"nord"}';
const ICONS = '{"id":"line-2","name":"Line 2","author":"me","license":"CC0-1.0","glyphs":{"home":{"d":"M3 3h18v18H3z"}}}';
type Theme = { id: string; name: string };
function harness(options: { pending?: unknown[]; withIcons?: boolean } = {}) {
const calls: Array<[string, Record<string, unknown> | undefined]> = [];
const listeners = new Map<string, (payload: unknown) => void>();
const preview = (kind: InstallKind, text: string): InstallPreview => ({
token: `tok-${calls.length}`, kind, source: { kind: 'file', url: null, label: 'A file you dropped', signed: false },
sha256: 'f'.repeat(64), size: text.length, file: null, text, version: '', plugin: null, theme: null, findings: [], existing: null, store: null,
icons: kind === 'icons' ? { id: 'line-2', name: 'Line 2', author: 'me', license: 'CC0-1.0', glyphs: 1 } : null,
});
const backend: StoreBackend = {
async invoke<T>(command: string, args?: Record<string, unknown>) {
calls.push([command, args]);
if (command === 'install_records') return { items: {} } as T;
if (command === 'install_pending') return (options.pending ?? []) as T;
if (command === 'install_stage_opened') return preview(args!.id === 'icons-id' ? 'icons' : 'theme', args!.id === 'icons-id' ? ICONS : THEME) as T;
if (command === 'install_stage_file') return preview(String(args!.name).endsWith('.icons.json') ? 'icons' : 'theme', String(args!.name).endsWith('.icons.json') ? ICONS : THEME) as T;
if (command === 'install_commit') return { themeText: args!.themeId ? THEME : null, iconsText: args!.themeId ? null : ICONS } as T;
return undefined as T;
},
async listen<T>(event: string, handler: (payload: T) => void) {
listeners.set(event, handler as (payload: unknown) => void);
return () => { listeners.delete(event); };
},
};
const savedThemes: string[] = [];
const themes: ThemeAdapter<Theme> = {
parse: text => { try { const value = JSON.parse(text) as Theme; return value.name ? { theme: value, warnings: [] } : { error: 'no name' }; } catch { return { error: 'not JSON' }; } },
userThemes: async () => [],
builtinThemes: ['x'],
idOf: theme => theme.id,
facts: theme => ({ name: theme.name }),
save: async (theme, id, opts) => { savedThemes.push(id); return { enabled: opts.enable, fonts: [] }; },
};
const savedPacks: Array<[IconPack, { enable: boolean }]> = [];
const controller = createInstallController({
backend, t, site: 'X', theme: themes,
...(options.withIcons === false ? {} : { icons: { save: async (pack: IconPack, opts: { enable: boolean }) => { savedPacks.push([pack, opts]); } } }),
});
return { controller, calls, listeners, savedThemes, savedPacks };
}
test('a file the OS handed over is staged by its id and installs only after the screen is confirmed', async () => {
const h = harness();
const stop = h.controller.start();
await settle();
h.listeners.get('install-link')!({ opened: { id: 'abc123', name: 'nord.json', kind: 'theme' } });
await settle();
const stage = h.calls.find(c => c[0] === 'install_stage_opened')!;
assert.deepEqual(stage[1], { id: 'abc123' }, 'only the id goes to native code; the shell has no path');
assert.equal(h.controller.current()?.status, 'ready', 'the same install screen as a dropped file');
assert.ok(!h.calls.some(c => c[0] === 'install_commit') && h.savedThemes.length === 0, 'nothing is written before Install');
await h.controller.confirm(true);
assert.deepEqual(h.savedThemes, ['nord']);
assert.equal(h.controller.current()?.status, 'done');
stop();
});
test('a file opened before the shell listened is shown from the pending queue', async () => {
const h = harness({ pending: [{ opened: { id: 'abc123', name: 'nord.json', kind: 'theme' } }] });
const stop = h.controller.start();
await settle();
assert.equal(h.calls.filter(c => c[0] === 'install_stage_opened').length, 1);
assert.equal(h.controller.current()?.status, 'ready');
stop();
});
test('a file the OS handed over that is refused says why, in the words for a file', async () => {
const h = harness();
const stop = h.controller.start();
await settle();
h.listeners.get('install-link')!({ error: 'FILE: only a theme (.json), a plugin (.plugin.js), a string pack (.strings.json) or an icon pack (.icons.json) can be opened here' });
await settle();
const state = h.controller.current();
assert.equal(state?.status, 'error');
assert.deepEqual(state && state.status === 'error' ? [state.title, state.message.startsWith('only a theme')] : null, ['This file cannot be installed', true]);
assert.ok(!h.calls.some(c => c[0] === 'install_stage_opened'));
stop();
});
test('icon packs: told apart from themes by name, staged like any file, parsed again from the committed bytes', async () => {
assert.equal(kindForFile('line-2.icons.json'), 'icons');
assert.equal(kindForFile('nord.json'), 'theme');
assert.equal(MAX_FILE_BYTES.icons, 120_000);
const h = harness();
const stop = h.controller.start();
await settle();
await h.controller.requestFile({ name: 'line-2.icons.json', size: ICONS.length, text: async () => ICONS });
const ready = h.controller.current();
assert.equal(ready?.status, 'ready');
assert.equal(ready?.status === 'ready' ? ready.pack?.name : null, 'Line 2', 'the screen can draw the pack');
assert.ok(!h.calls.some(c => c[0] === 'install_commit') && h.savedPacks.length === 0, 'nothing is written before Install');
await h.controller.confirm(true);
assert.deepEqual(h.calls.find(c => c[0] === 'install_commit')![1], { token: (ready as { preview: InstallPreview }).preview.token, enable: true, themeId: null });
assert.deepEqual(h.savedPacks.map(([pack, opts]) => [pack.id, Object.keys(pack.glyphs), opts.enable]), [['line-2', ['home'], true]]);
assert.deepEqual(h.controller.current(), { status: 'done', kind: 'icons', name: 'Line 2', fonts: [], enabled: true });
assert.equal(h.savedThemes.length, 0, 'an icon pack is not a theme');
stop();
});
test('icon packs: too large, not installable without the app\'s support,', async () => {
const h = harness();
await h.controller.requestFile({ name: 'big.icons.json', size: MAX_FILE_BYTES.icons + 1, text: async () => ICONS });
const state = h.controller.current();
assert.equal(state?.status === 'error' ? state.message : '', 'Icon packs are limited to 120 KB.');
const bare = harness({ withIcons: false });
await bare.controller.requestFile({ name: 'line-2.icons.json', size: ICONS.length, text: async () => ICONS });
assert.equal(bare.controller.current()?.status, 'error');
assert.ok(!bare.calls.some(c => c[0] === 'install_commit'));
});
const item = (patch: Partial<StoreItem>): StoreItem => ({
apps: ['x'], kind: 'icons', id: 'line-2', name: 'Line 2', author: 'me', version: '1.1.0', description: 'Thin lines', category: 'icons', tags: [],
url: 'https://waybetter.fyi/store/icons/line-2.icons.json', sha256: 'a'.repeat(64), size: 100, ...patch,
});
test('the Store: icon packs follow their install records and the packs the owner still has; built-in items are areas', () => {
const base = { plugins: {}, records: {}, builtinThemes: [], userThemes: [] as string[] };
assert.equal(itemState(item({}), base).state, 'install');
const records = { 'icons:line-2-copy': { kind: 'icons' as const, source: 'store' as const, storeId: 'line-2', version: '1.0.0', sha256: 'b'.repeat(64), installedAt: '' } };
assert.equal(itemState(item({}), { ...base, records }).state, 'update', 'no list of packs: the records decide');
assert.equal(itemState(item({}), { ...base, records, userIcons: ['line-2-copy'] }).state, 'update');
assert.equal(itemState(item({}), { ...base, records, userIcons: [] }).state, 'install', 'a pack the owner removed in Appearance is not installed');
assert.equal(itemState(item({ sha256: 'b'.repeat(64) }), { ...base, records, userIcons: ['line-2-copy'] }).state, 'installed');
const area = item({ kind: 'builtin', id: 'compose', name: 'Compose+', url: undefined, sha256: undefined, size: undefined, category: 'writing' });
assert.equal(itemState(area, base).state, 'area');
const all = [item({}), area];
assert.deepEqual(filterItems(all, '', 'builtin', 'all').map(i => i.id), ['compose']);
assert.deepEqual(filterItems(all, '', 'icons', 'all').map(i => i.id), ['line-2']);
});

View file

@ -25,6 +25,9 @@ export const DEFAULT_HOSTS = [
]; ];
export const PERMISSIONS = ['storage', 'ui', 'clipboard', 'account', 'users', 'commands', 'network', 'network:none']; export const PERMISSIONS = ['storage', 'ui', 'clipboard', 'account', 'users', 'commands', 'network', 'network:none'];
const MAX_BYTES = 2 * 1024 * 1024; const MAX_BYTES = 2 * 1024 * 1024;
/** An icon pack file (the runtime's `ICON_LIMITS.packBytes`). */
const MAX_ICONS_BYTES = 120_000;
const KINDS = ['theme', 'plugin', 'strings', 'icons', 'builtin'];
const MAX_ITEMS = 500; const MAX_ITEMS = 500;
const MAX_CATALOG_BYTES = 1024 * 1024; const MAX_CATALOG_BYTES = 1024 * 1024;
// SPKI DER prefix of an Ed25519 public key; the raw 32 bytes follow it. // SPKI DER prefix of an Ed25519 public key; the raw 32 bytes follow it.
@ -84,7 +87,7 @@ export function itemProblems(item, hosts) {
if (!item || typeof item !== 'object' || Array.isArray(item)) return ['not an object']; if (!item || typeof item !== 'object' || Array.isArray(item)) return ['not an object'];
for (const key of Object.keys(item)) if (!ITEM_FIELDS.has(key)) bad.push(`unknown field ${key}`); for (const key of Object.keys(item)) if (!ITEM_FIELDS.has(key)) bad.push(`unknown field ${key}`);
if (!Array.isArray(item.apps) || !item.apps.length || item.apps.length > 16 || !item.apps.every(validAppId) || new Set(item.apps).size !== item.apps.length) bad.push('apps'); if (!Array.isArray(item.apps) || !item.apps.length || item.apps.length > 16 || !item.apps.every(validAppId) || new Set(item.apps).size !== item.apps.length) bad.push('apps');
if (item.kind !== 'theme' && item.kind !== 'plugin' && item.kind !== 'strings') bad.push('kind'); if (!KINDS.includes(item.kind)) bad.push('kind');
// Any item may name its licence and credit its authors; only a string pack has a language. // Any item may name its licence and credit its authors; only a string pack has a language.
if ((item.license !== undefined && (!text(item.license, 60) || !String(item.license).trim())) || (item.credits !== undefined && !text(item.credits, 600))) bad.push('license or credits'); if ((item.license !== undefined && (!text(item.license, 60) || !String(item.license).trim())) || (item.credits !== undefined && !text(item.credits, 600))) bad.push('license or credits');
if (item.kind !== 'strings' && item.language !== undefined) bad.push('language'); if (item.kind !== 'strings' && item.language !== undefined) bad.push('language');
@ -92,10 +95,18 @@ export function itemProblems(item, hosts) {
if (!text(item.name, 60) || !String(item.name).trim() || !text(item.author ?? '', 60) || !text(item.description ?? '', 600)) bad.push('name, author or description'); if (!text(item.name, 60) || !String(item.name).trim() || !text(item.author ?? '', 60) || !text(item.description ?? '', 600)) bad.push('name, author or description');
if (!text(item.version, 32) || !item.version || !text(item.category ?? '', 32)) bad.push('version or category'); if (!text(item.version, 32) || !item.version || !text(item.category ?? '', 32)) bad.push('version or category');
if (item.tags !== undefined && (!Array.isArray(item.tags) || item.tags.length > 12 || !item.tags.every(tag => text(tag, 32)))) bad.push('tags'); if (item.tags !== undefined && (!Array.isArray(item.tags) || item.tags.length > 12 || !item.tags.every(tag => text(tag, 32)))) bad.push('tags');
if (typeof item.url !== 'string' || !item.url.startsWith('https://') || (hosts && !allowedUrl(item.url, hosts))) bad.push('url (host not allowed)'); if (item.kind === 'builtin') {
// A feature that ships inside the app (an area plugin): nothing to download, so nothing to point at or hash.
for (const key of ['url', 'sha256', 'size', 'file', 'permissions', 'colors', 'language']) if (item[key] !== undefined) bad.push('built-in item fields');
} else {
if (typeof item.url !== 'string' || !item.url.startsWith('https://') || (hosts && !allowedUrl(item.url, hosts))) bad.push('url (host not allowed)');
}
if (item.preview !== undefined && (typeof item.preview !== 'string' || !item.preview.startsWith('https://') || (hosts && !allowedUrl(item.preview, hosts)))) bad.push('preview'); if (item.preview !== undefined && (typeof item.preview !== 'string' || !item.preview.startsWith('https://') || (hosts && !allowedUrl(item.preview, hosts)))) bad.push('preview');
if (typeof item.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(item.sha256)) bad.push('sha256'); if (item.kind !== 'builtin') {
if (!Number.isInteger(item.size) || item.size <= 0 || item.size > MAX_BYTES) bad.push('size'); if (typeof item.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(item.sha256)) bad.push('sha256');
if (!Number.isInteger(item.size) || item.size <= 0 || item.size > (item.kind === 'icons' ? MAX_ICONS_BYTES : MAX_BYTES)) bad.push('size');
}
if (item.kind === 'icons' && (item.file !== undefined || item.permissions !== undefined || item.colors !== undefined)) bad.push('icon pack fields');
if (item.kind === 'plugin') { if (item.kind === 'plugin') {
if (!validFileName(item.file) || item.colors != null) bad.push('plugin file'); if (!validFileName(item.file) || item.colors != null) bad.push('plugin file');
const p = item.permissions; const p = item.permissions;
@ -152,6 +163,8 @@ export function catalogProblems(catalog, { app, hosts = DEFAULT_HOSTS } = {}) {
* description, category, tags, file (plugins), permissions (plugins), colors (themes), language * description, category, tags, file (plugins), permissions (plugins), colors (themes), language
* (string packs), license, credits, * (string packs), license, credits,
* path ('plugins/x.plugin.js'), bytes (Buffer|string), preview?: { path, bytes } }] } * path ('plugins/x.plugin.js'), bytes (Buffer|string), preview?: { path, bytes } }] }
* Kinds: theme, plugin, strings, icons (an icon pack, `icons/<id>.icons.json`) and builtin (a
* feature that ships inside the app, shown in the Store as built in: no path or bytes).
*/ */
export async function buildStore(config, options = {}) { export async function buildStore(config, options = {}) {
const app = config.app; const app = config.app;
@ -181,12 +194,16 @@ export async function buildStore(config, options = {}) {
const files = new Map(); const files = new Map();
const toBytes = value => (Buffer.isBuffer(value) ? value : Buffer.from(String(value), 'utf8')); const toBytes = value => (Buffer.isBuffer(value) ? value : Buffer.from(String(value), 'utf8'));
for (const entry of entries) { for (const entry of entries) {
const bytes = toBytes(entry.bytes); const item = { apps: [app], kind: entry.kind, id: entry.id, name: entry.name, author: entry.author ?? '', version: entry.version, description: entry.description ?? '', category: entry.category ?? '', tags: entry.tags ?? [] };
files.set(entry.path, { target: inside(entry.path), bytes }); // A built-in item has no file: the app already has it.
const item = { apps: [app], kind: entry.kind, id: entry.id, name: entry.name, author: entry.author ?? '', version: entry.version, description: entry.description ?? '', category: entry.category ?? '', tags: entry.tags ?? [], url: `${base}${entry.path}` }; if (entry.kind !== 'builtin') {
if (entry.kind === 'plugin') item.file = entry.file; const bytes = toBytes(entry.bytes);
item.sha256 = sha256(bytes); files.set(entry.path, { target: inside(entry.path), bytes });
item.size = bytes.length; item.url = `${base}${entry.path}`;
if (entry.kind === 'plugin') item.file = entry.file;
item.sha256 = sha256(bytes);
item.size = bytes.length;
}
if (entry.preview) { if (entry.preview) {
files.set(entry.preview.path, { target: inside(entry.preview.path), bytes: toBytes(entry.preview.bytes) }); files.set(entry.preview.path, { target: inside(entry.preview.path), bytes: toBytes(entry.preview.bytes) });
item.preview = `${base}${entry.preview.path}`; item.preview = `${base}${entry.preview.path}`;

View file

@ -57,6 +57,7 @@
"wb.store.category.tools": "Tools", "wb.store.category.tools": "Tools",
"wb.store.category.dark": "Dark", "wb.store.category.dark": "Dark",
"wb.store.category.light": "Light", "wb.store.category.light": "Light",
"wb.store.category.icons": "Icons",
"wb.store.builtIn": "Built in", "wb.store.builtIn": "Built in",
"wb.store.use": "Use", "wb.store.use": "Use",
"wb.store.install": "Install", "wb.store.install": "Install",
@ -1293,6 +1294,29 @@
"wb.install.openStrings": "Open Languages", "wb.install.openStrings": "Open Languages",
"wb.store.strings": "Languages", "wb.store.strings": "Languages",
"wb.store.stringsItem": "String pack", "wb.store.stringsItem": "String pack",
"wb.install.eyebrow.icons.install": "Install icon pack",
"wb.install.eyebrow.icons.update": "Update icon pack",
"wb.install.eyebrow.icons.reinstall": "Reinstall icon pack",
"wb.install.err.icons": "This icon pack cannot be installed",
"wb.install.err.iconsNone": "{site} cannot install icon packs here.",
"wb.install.err.iconsLarge": "Icon packs are limited to 120 KB.",
"wb.install.err.iconsNotInstalled": "The icon pack was not installed",
"wb.install.err.opened": "This file cannot be installed",
"wb.install.icons.dataOnly": "Data only: drawings as path data and small pictures. No code and no styles; nothing in it runs.",
"wb.install.icons.license": "License",
"wb.install.icons.source": "Drawings from",
"wb.install.icons.count": "Icons",
"wb.install.icons.countValue": "{count, plural, one {# icon} other {# icons}}",
"wb.install.icons.file": "The pack file",
"wb.install.done.iconsOn": "It is your icon pack now. Switch back any time in Appearance.",
"wb.install.done.iconsOff": "It is in your icon packs in Appearance.",
"wb.store.icons": "Icons",
"wb.store.iconsItem": "Icon pack",
"wb.store.builtinTab": "Built in",
"wb.store.builtinItem": "Built in",
"wb.store.areaSwitch": "Turn {name} on or off",
"wb.store.areaOn": "On",
"wb.store.areaOff": "Off",
"wb.strings.section": "Languages", "wb.strings.section": "Languages",
"wb.strings.title": "String packs", "wb.strings.title": "String packs",
"wb.strings.intro": "A string pack replaces {site}’s own words with text: a language {site} does not offer, a better translation, or your own wording. Packs apply in this order; a later one wins where two change the same word. Words no pack changes stay exactly as {site} shows them.", "wb.strings.intro": "A string pack replaces {site}’s own words with text: a language {site} does not offer, a better translation, or your own wording. Packs apply in this order; a later one wins where two change the same word. Words no pack changes stay exactly as {site} shows them.",

View file

@ -18,15 +18,26 @@
"color": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" }, "color": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" },
"item": { "item": {
"type": "object", "type": "object",
"required": ["apps", "kind", "id", "name", "version", "url", "sha256", "size"], "required": ["apps", "kind", "id", "name", "version"],
"additionalProperties": false, "additionalProperties": false,
"allOf": [
{
"if": { "properties": { "kind": { "const": "builtin" } } },
"then": { "not": { "anyOf": [{ "required": ["url"] }, { "required": ["sha256"] }, { "required": ["size"] }, { "required": ["file"] }, { "required": ["permissions"] }, { "required": ["colors"] }, { "required": ["language"] }] } },
"else": { "required": ["url", "sha256", "size"] }
},
{
"if": { "properties": { "kind": { "const": "icons" } } },
"then": { "not": { "anyOf": [{ "required": ["file"] }, { "required": ["permissions"] }, { "required": ["colors"] }, { "required": ["language"] }] }, "properties": { "size": { "maximum": 120000 } } }
}
],
"properties": { "properties": {
"apps": { "apps": {
"type": "array", "minItems": 1, "maxItems": 16, "uniqueItems": true, "type": "array", "minItems": 1, "maxItems": 16, "uniqueItems": true,
"description": "The wayBetter apps this item is for (app ids such as \"x\"). An app never shows, stages or installs another app's items.", "description": "The wayBetter apps this item is for (app ids such as \"x\"). An app never shows, stages or installs another app's items.",
"items": { "type": "string", "pattern": "^[a-z0-9-]{1,32}$" } "items": { "type": "string", "pattern": "^[a-z0-9-]{1,32}$" }
}, },
"kind": { "enum": ["theme", "plugin", "strings"], "description": "strings: a string pack (data that replaces the site's own UI strings; waybetter docs/STRING-PACKS.md)." }, "kind": { "enum": ["theme", "plugin", "strings", "icons", "builtin"], "description": "strings: a string pack (data that replaces the site's own UI strings; waybetter docs/STRING-PACKS.md). icons: an icon pack (`*.icons.json`, data only, at most 120 KB). builtin: a feature that ships inside the app (an area plugin), listed in the Store as built in with its switch; it has no url, sha256 or size because there is nothing to download." },
"id": { "type": "string", "pattern": "^[a-z0-9-]{1,40}$", "description": "Unique per app and kind." }, "id": { "type": "string", "pattern": "^[a-z0-9-]{1,40}$", "description": "Unique per app and kind." },
"name": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "minLength": 1, "maxLength": 60 }, "name": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "minLength": 1, "maxLength": 60 },
"author": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 60 }, "author": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 60 },
@ -34,7 +45,7 @@
"description": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 600 }, "description": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 600 },
"category": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 32, "description": "Shown as `wb.store.category.<id>` when the framework catalogs name it (reading, writing, filters, focus, tools, dark, light), else as is." }, "category": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 32, "description": "Shown as `wb.store.category.<id>` when the framework catalogs name it (reading, writing, filters, focus, tools, dark, light), else as is." },
"tags": { "type": "array", "maxItems": 12, "items": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 32 } }, "tags": { "type": "array", "maxItems": 12, "items": { "allOf": [{ "$ref": "#/$defs/text" }], "type": "string", "maxLength": 32 } },
"url": { "$ref": "#/$defs/https", "description": "The file. It must be on the reading app's download hosts (waybetter.fyi, cdn1.crt.fyi, git.crt.fyi raw files by default): https, default port, no credentials, no fragment." }, "url": { "$ref": "#/$defs/https", "description": "The file (not on a `builtin` item). It must be on the reading app's download hosts (waybetter.fyi, cdn1.crt.fyi, git.crt.fyi raw files by default): https, default port, no credentials, no fragment." },
"file": { "type": "string", "pattern": "^[A-Za-z0-9_\\-. ]+\\.plugin\\.js$", "maxLength": 128, "description": "Plugins only: the file name it is installed under (unique per app, ignoring case)." }, "file": { "type": "string", "pattern": "^[A-Za-z0-9_\\-. ]+\\.plugin\\.js$", "maxLength": 128, "description": "Plugins only: the file name it is installed under (unique per app, ignoring case)." },
"sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
"size": { "type": "integer", "minimum": 1, "maximum": 2097152 }, "size": { "type": "integer", "minimum": 1, "maximum": 2097152 },

View file

@ -104,3 +104,43 @@ test('sign and verify: a fresh key signs, the signature verifies, a changed byte
assert.match(fails('store', 'sign', catalog, '--key', join(dir, 'missing.key')), /no store key/); assert.match(fails('store', 'sign', catalog, '--key', join(dir, 'missing.key')), /no store key/);
assert.match(fails('store', 'frobnicate'), /Usage/); assert.match(fails('store', 'frobnicate'), /Usage/);
}); });
const ICONS = JSON.stringify({ id: 'line-2', name: 'Line 2', author: 'me', license: 'CC0-1.0', glyphs: { home: { d: 'M3 3h18v18H3z' } } });
test('icon packs are catalog items with a file; built-in items have none; the schema and the CLI agree', async () => {
const out = mkdtempSync(join(tmpdir(), 'wb-store-'));
const builtin = { kind: 'builtin', id: 'compose', name: 'Compose+', version: '1.0.0', category: 'writing', description: 'Writing tools.', preview: { path: 'previews/builtin-compose.svg', bytes: '<svg xmlns="http://www.w3.org/2000/svg"/>' } };
const icons = { kind: 'icons', id: 'line-2', name: 'Line 2', version: '1.0.0', category: 'icons', path: 'icons/line-2.icons.json', bytes: ICONS, license: 'CC0-1.0' };
await buildStore(config('x', [icons, builtin]), { out });
const catalog = JSON.parse(readFileSync(join(out, 'catalog.json'), 'utf8'));
const pack = catalog.items.find(item => item.kind === 'icons');
assert.deepEqual([pack.url, pack.sha256, pack.size, pack.license], ['https://waybetter.fyi/store/icons/line-2.icons.json', sha256(Buffer.from(ICONS)), Buffer.byteLength(ICONS), 'CC0-1.0']);
const area = catalog.items.find(item => item.kind === 'builtin');
for (const field of ['url', 'sha256', 'size', 'file']) assert.ok(!(field in area), `a built-in item has no ${field}`);
assert.ok(area.preview.endsWith('previews/builtin-compose.svg') && existsSync(join(out, 'previews/builtin-compose.svg')));
assert.deepEqual(validate(SCHEMA, catalog), [], 'the schema accepts what build writes');
assert.deepEqual(catalogProblems(catalog, { app: 'x' }), []);
// What apps refuse, the schema and the CLI both refuse.
const cases = [
['built-in with a url', area, { url: 'https://waybetter.fyi/store/a' }],
['built-in with a sha256', area, { sha256: 'a'.repeat(64) }],
['built-in with a size', area, { size: 4 }],
['built-in with a file', area, { file: 'a.plugin.js' }],
['icon pack without a url', pack, { url: undefined }],
['icon pack without a sha256', pack, { sha256: undefined }],
['icon pack over 120 KB', pack, { size: 120_001 }],
['icon pack with a plugin file', pack, { file: 'a.plugin.js' }],
['icon pack with permissions', pack, { permissions: ['ui'] }],
['icon pack with a language', pack, { language: 'eo' }],
['a theme without a url', catalog.items.find(item => item.kind === 'theme'), { url: undefined }],
];
for (const [what, item, patch] of cases) {
const doc = structuredClone(catalog);
const target = doc.items.find(entry => entry.kind === item.kind && entry.id === item.id);
for (const [key, value] of Object.entries(patch)) { if (value === undefined) delete target[key]; else target[key] = value; }
assert.notDeepEqual(validate(SCHEMA, doc), [], `schema accepted ${what}`);
assert.notDeepEqual(catalogProblems(doc, { app: 'x' }), [], `cli accepted ${what}`);
}
// Building refuses an icon pack with no file as well.
await assert.rejects(buildStore(config('x', [{ kind: 'icons', id: 'bare', name: 'Bare', version: '1' }]), { out }));
});

View file

@ -58,6 +58,26 @@ ManifestDPIAwareness PerMonitorV2
${StrCase} ${StrCase}
${StrLoc} ${StrLoc}
; wayBetter: file associations that never take a file type over. Tauri's APP_ASSOCIATE makes the
; app the default program for the extension, which for `.js` and `.json` (a wayBetter plugin is
; `name.plugin.js`, a theme `name.json`; Windows only knows the last part) would claim every
; script and JSON file on the machine. These two only list the app under "Open with" for the
; extension (OpenWithProgids) and register what that entry runs; the owner's default stays as it
; is. The app then shows its own install screen for the file (nothing installs without it).
!macro WaybetterOpenWith EXT FILECLASS DESCRIPTION ICON COMMANDTEXT COMMAND
WriteRegStr SHCTX "Software\Classes\.${EXT}\OpenWithProgids" "${FILECLASS}" ""
WriteRegStr SHCTX "Software\Classes\${FILECLASS}" "" `${DESCRIPTION}`
WriteRegStr SHCTX "Software\Classes\${FILECLASS}\DefaultIcon" "" `${ICON}`
WriteRegStr SHCTX "Software\Classes\${FILECLASS}\shell\open" "" `${COMMANDTEXT}`
WriteRegStr SHCTX "Software\Classes\${FILECLASS}\shell\open\command" "" `${COMMAND}`
System::Call 'Shell32::SHChangeNotify(i 0x08000000, i 0, i 0, i 0)'
!macroend
!macro WaybetterNoOpenWith EXT FILECLASS
DeleteRegValue SHCTX "Software\Classes\.${EXT}\OpenWithProgids" "${FILECLASS}"
DeleteRegKey SHCTX "Software\Classes\${FILECLASS}"
System::Call 'Shell32::SHChangeNotify(i 0x08000000, i 0, i 0, i 0)'
!macroend
{{#if installer_hooks}} {{#if installer_hooks}}
!include "{{installer_hooks}}" !include "{{installer_hooks}}"
{{/if}} {{/if}}
@ -556,7 +576,7 @@ Section Install
; Create file associations ; Create file associations
{{#each file_associations as |association| ~}} {{#each file_associations as |association| ~}}
{{#each association.ext as |ext| ~}} {{#each association.ext as |ext| ~}}
!insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\"" !insertmacro WaybetterOpenWith "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\""
{{/each}} {{/each}}
{{/each}} {{/each}}
@ -699,7 +719,7 @@ Section Uninstall
; Delete app associations ; Delete app associations
{{#each file_associations as |association| ~}} {{#each file_associations as |association| ~}}
{{#each association.ext as |ext| ~}} {{#each association.ext as |ext| ~}}
!insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}" !insertmacro WaybetterNoOpenWith "{{ext}}" "{{or association.name ext}}"
{{/each}} {{/each}}
{{/each}} {{/each}}