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 e85a00eca3
commit 5aa66e7191
21 changed files with 1015 additions and 90 deletions

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`).
pub const CATALOG_FORMAT: u32 = 2;
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_SIGNATURE_BYTES: usize = 512;
pub const MAX_LINK_CHARS: usize = 2048;
@ -61,6 +63,11 @@ pub enum Kind {
Plugin,
/// A string pack: data that replaces the site's own UI strings (`store::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 {
@ -69,7 +76,9 @@ impl Kind {
"theme" => Ok(Kind::Theme),
"plugin" => Ok(Kind::Plugin),
"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::Plugin => "plugin",
Kind::Strings => "strings",
Kind::Icons => "icons",
Kind::Builtin => "builtin",
}
}
@ -86,6 +97,8 @@ impl Kind {
Kind::Theme => MAX_THEME_BYTES,
Kind::Plugin => MAX_PLUGIN_BYTES as usize,
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());
}
}
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")?;
if !allowed_download_url(config.allowed_hosts, &target) {
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`).
pub fn validate_plugin(file: &str, bytes: &[u8]) -> Result<ValidatedPlugin, String> {
plugins::validate_plugin(file, bytes)
@ -279,11 +351,15 @@ pub struct CatalogItem {
pub category: String,
#[serde(default)]
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,
/// Plugins: the file name it is installed under.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub sha256: String,
#[serde(default, skip_serializing_if = "is_zero")]
pub size: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview: Option<String>,
@ -321,6 +397,10 @@ impl Catalog {
}
}
fn is_zero(value: &u64) -> bool {
*value == 0
}
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'-')
}
@ -358,9 +438,22 @@ impl CatalogItem {
if self.tags.len() > 12 || self.tags.iter().any(|tag| !valid_text(tag, 32)) {
return bad("tags");
}
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.kind == Kind::Builtin {
// Part of the app: nothing to download, so nothing to hash or point at.
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 {
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");
}
}
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.
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");
@ -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 => {
if self.file.is_some() || self.permissions.is_some() || self.colors.is_some() {
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.
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 {
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"));
}
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]
fn versions_compare_numerically() {
assert!(newer_version("1.10.0", "1.9.3"));