agentmux_srv_core/backend/widget/
catalog.rs1use 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
25pub const DEFAULT_CATALOG_URL: &str = "https://agentmuxai.github.io/widgets/index.json";
27
28pub const CATALOG_KEYS: &[&str] = &[
33 "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 pub hash: String,
59 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#[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 pub current: bool,
84}
85
86pub(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
100pub 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
128pub(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
143pub(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
164pub 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
171pub 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
188pub 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
222pub 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;