Skip to main content

agentmux_srv_core/backend/widget/
catalog.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The widget catalog (docs/specs/SPEC_WIDGET_SHARING_2026_10_10.md §4): a
5//! public list of sandboxed widgets, built and signed by the
6//! `agentmuxai/widgets` repository's CI, that Settings → Widgets browses.
7//!
8//! The catalog is a convenience and a second check, never an approval. srv
9//! checks the index's signature against a key pinned here, downloads a
10//! widget only from the catalog's own origin, checks the zip's SHA-256, the
11//! package's content hash and its author's signature against the index, and
12//! installs it as `needs_approval`, like any widget: the user's prompt
13//! decides.
14
15use std::path::{Path, PathBuf};
16
17use base64::Engine;
18use ed25519_dalek::{Signature, Verifier, VerifyingKey};
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21
22use super::packages::{self as wp, WidgetState};
23use super::signature as sig;
24
25/// Where the official catalog is served.
26pub const DEFAULT_CATALOG_URL: &str = "https://agentmuxai.github.io/widgets/index.json";
27
28/// The catalog keys AgentMux trusts (base64 Ed25519 public keys). The
29/// private half lives only in the catalog repository's CI
30/// (`agentmuxai/widgets`, secret `CATALOG_SIGNING_SEED`). More than one, for
31/// a rotation.
32pub const CATALOG_KEYS: &[&str] = &[
33    // 2026-10-11, the first catalog key.
34    "iFz5TLnwIg/oApX6WVrjmdVT6HDl133MeaWlQpA+MjE=",
35];
36
37const MAX_INDEX_BYTES: usize = 5 * 1024 * 1024;
38const CATALOG_VERSION: u32 = 1;
39
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
41#[serde(rename_all = "camelCase")]
42#[ts(export, export_to = "../../../frontend/types/rpc/", rename = "WidgetCatalogEntry")]
43pub struct CatalogEntry {
44    pub id: String,
45    pub name: String,
46    pub version: String,
47    #[serde(default)]
48    pub description: Option<String>,
49    #[serde(default)]
50    pub author: Option<String>,
51    #[serde(default)]
52    pub homepage: Option<String>,
53    #[serde(default)]
54    pub icon: Option<String>,
55    #[serde(default)]
56    pub permissions: Vec<String>,
57    /// The package's content hash.
58    pub hash: String,
59    /// Its publisher's key (base64), which signed it.
60    pub publisher_key: String,
61    pub zip: String,
62    pub zip_sha256: String,
63}
64
65#[derive(Debug, Clone, Deserialize)]
66#[serde(rename_all = "camelCase")]
67struct CatalogIndex {
68    catalog_version: u32,
69    #[serde(default)]
70    widgets: Vec<CatalogEntry>,
71}
72
73/// An entry as Settings shows it: the entry, its publisher's fingerprint,
74/// and what is installed here.
75#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
76#[ts(export, export_to = "../../../frontend/types/rpc/")]
77pub struct WidgetCatalogItem {
78    pub entry: CatalogEntry,
79    pub fingerprint: String,
80    pub installed_version: Option<String>,
81    pub installed_state: Option<WidgetState>,
82    /// Installed here at exactly the catalog's files.
83    pub current: bool,
84}
85
86/// Whether `signature` over `raw` verifies with one of `keys` (base64
87/// Ed25519 public keys). Job template catalogs use it too.
88pub(crate) fn signed_by_any(raw: &[u8], signature: &[u8; 64], keys: &[&str]) -> bool {
89    let b64 = base64::engine::general_purpose::STANDARD;
90    let signature = Signature::from_bytes(signature);
91    keys.iter().any(|k| {
92        b64.decode(k)
93            .ok()
94            .and_then(|k| <[u8; 32]>::try_from(k).ok())
95            .and_then(|k| VerifyingKey::from_bytes(&k).ok())
96            .is_some_and(|k| k.verify(raw, &signature).is_ok())
97    })
98}
99
100/// Checks the index `raw` against its signature `sig_b64` with `keys`, and
101/// each entry against the catalog's rules.
102pub fn verify_index(raw: &[u8], sig_b64: &str, keys: &[&str], index_url: &str) -> Result<Vec<CatalogEntry>, String> {
103    let b64 = base64::engine::general_purpose::STANDARD;
104    let signature: [u8; 64] = b64
105        .decode(sig_b64.trim())
106        .ok()
107        .and_then(|s| s.try_into().ok())
108        .ok_or("the catalog's signature isn't 64 bytes of base64")?;
109    if !signed_by_any(raw, &signature, keys) {
110        return Err("the catalog's signature doesn't verify: it isn't the AgentMux catalog, or it was changed".to_string());
111    }
112    let index: CatalogIndex = serde_json::from_slice(raw).map_err(|e| format!("the catalog index: {e}"))?;
113    if index.catalog_version != CATALOG_VERSION {
114        return Err(format!("the catalog is version {}, this AgentMux reads {CATALOG_VERSION}", index.catalog_version));
115    }
116    let origin = origin_of(index_url).ok_or("the catalog URL isn't an https:// URL")?;
117    for e in &index.widgets {
118        if !wp::valid_id(&e.id) {
119            return Err(format!("the catalog lists {:?}, which isn't a widget id", e.id));
120        }
121        if origin_of(&e.zip).as_deref() != Some(origin.as_str()) {
122            return Err(format!("the catalog's {} isn't served from the catalog itself", e.id));
123        }
124    }
125    Ok(index.widgets)
126}
127
128/// `https://host[:port]` of an https URL.
129pub(crate) fn origin_of(url: &str) -> Option<String> {
130    let rest = url.strip_prefix("https://")?;
131    let host = rest.split(['/', '?', '#']).next()?;
132    (!host.is_empty() && !host.contains('@')).then(|| format!("https://{host}"))
133}
134
135fn client() -> Result<reqwest::Client, String> {
136    crate::http_client::builder()
137        .timeout(std::time::Duration::from_secs(60))
138        .redirect(reqwest::redirect::Policy::none())
139        .build()
140        .map_err(|e| e.to_string())
141}
142
143/// `url`'s body, at most `max` bytes: refused as soon as it declares or
144/// reaches more, never held in memory whole first.
145pub(crate) async fn get(url: &str, max: usize) -> Result<Vec<u8>, String> {
146    let too_big = || format!("{url} is over the {} KB it may be", max / 1024);
147    let mut resp = client()?.get(url).send().await.map_err(|e| format!("can't reach the catalog: {e}"))?;
148    if !resp.status().is_success() {
149        return Err(format!("the catalog answered {} for {url}", resp.status()));
150    }
151    if resp.content_length().is_some_and(|n| n > max as u64) {
152        return Err(too_big());
153    }
154    let mut body = Vec::new();
155    while let Some(chunk) = resp.chunk().await.map_err(|e| format!("the catalog: {e}"))? {
156        if body.len() + chunk.len() > max {
157            return Err(too_big());
158        }
159        body.extend_from_slice(&chunk);
160    }
161    Ok(body)
162}
163
164/// The catalog at `url`, checked.
165pub async fn fetch(url: &str) -> Result<Vec<CatalogEntry>, String> {
166    let raw = get(url, MAX_INDEX_BYTES).await?;
167    let sig_text = String::from_utf8(get(&format!("{url}.sig"), 1024).await?).map_err(|_| "the catalog's signature isn't text")?;
168    verify_index(&raw, &sig_text, CATALOG_KEYS, url)
169}
170
171/// What Settings lists: each entry with what is installed here.
172pub fn items(entries: Vec<CatalogEntry>, installed: &[wp::WidgetPackageInfo]) -> Vec<WidgetCatalogItem> {
173    entries
174        .into_iter()
175        .map(|entry| {
176            let i = installed.iter().find(|p| p.id == entry.id);
177            WidgetCatalogItem {
178                fingerprint: sig::fingerprint(&entry.publisher_key),
179                installed_version: i.map(|p| p.version.clone()),
180                installed_state: i.map(|p| p.state.clone()),
181                current: i.is_some_and(|p| p.hash == entry.hash),
182                entry,
183            }
184        })
185        .collect()
186}
187
188/// Checks a downloaded zip against its entry: the zip's SHA-256, then,
189/// unpacked, the package's content hash and its author's signature.
190/// Returns the unpacked package's folder (in the returned temp dir).
191pub fn check_download(zip: &[u8], entry: &CatalogEntry) -> Result<(tempfile::TempDir, PathBuf), String> {
192    if hex::encode(Sha256::digest(zip)) != entry.zip_sha256 {
193        return Err(format!("{}'s download doesn't match the catalog", entry.id));
194    }
195    let tmp = tempfile::tempdir().map_err(|e| e.to_string())?;
196    let zip_path = tmp.path().join("pkg.zip");
197    std::fs::write(&zip_path, zip).map_err(|e| e.to_string())?;
198    let stage = tmp.path().join("pkg");
199    wp::unzip(&zip_path, &stage)?;
200    let root = wp::package_root(&stage, wp::MANIFEST_FILE)?;
201    let hash = wp::package_hash(&wp::hash_files(&root)?);
202    if hash != entry.hash {
203        return Err(format!("{}'s files don't match the catalog", entry.id));
204    }
205    let manifest: wp::Manifest = serde_json::from_slice(&std::fs::read(root.join(wp::MANIFEST_FILE)).map_err(|e| e.to_string())?)
206        .map_err(|e| format!("widget.json: {e}"))?;
207    if manifest.id != entry.id || manifest.version != entry.version {
208        return Err(format!("{}'s widget.json doesn't match the catalog", entry.id));
209    }
210    if manifest.kind() != wp::WidgetKind::Sandboxed {
211        return Err("the catalog lists sandboxed widgets only".to_string());
212    }
213    match sig::check(&sig::WIDGET, &root, &entry.id, &entry.version, &hash) {
214        Some(Ok(key)) if key == entry.publisher_key => {}
215        Some(Ok(_)) | None => return Err(format!("{} isn't signed by the publisher the catalog lists", entry.id)),
216        Some(Err(e)) => return Err(e),
217    }
218    std::fs::remove_file(&zip_path).ok();
219    Ok((tmp, root))
220}
221
222/// Downloads `entry` from the catalog, checks it, and copies it into
223/// `widgets_dir` (replacing an installed version), waiting for approval.
224pub async fn install(widgets_dir: &Path, entry: &CatalogEntry) -> Result<String, String> {
225    let zip = get(&entry.zip, (wp::MAX_PACKAGE_BYTES + 1024 * 1024) as usize).await?;
226    let (entry, dir) = (entry.clone(), widgets_dir.to_path_buf());
227    tokio::task::spawn_blocking(move || {
228        let (_tmp, root) = check_download(&zip, &entry)?;
229        wp::install(&dir, &root, true)
230    })
231    .await
232    .map_err(|e| e.to_string())?
233}
234
235#[cfg(test)]
236#[path = "catalog_tests.rs"]
237mod tests;