Skip to main content

agentmux_srv_core/backend/widget/
packages.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Widget packages: user widgets as folders with a `widget.json` manifest,
5//! which run only once the user approves them
6//! (docs/specs/SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md §5, §8).
7//!
8//! srv scans `~/.agentmux/widgets/` (shared by every channel), validates each
9//! package's manifest, hashes every file, and keeps this instance's approval
10//! record. A package's files are served (`/agentmux/widget-files/…`) only while
11//! they still hash to what the user approved, checked per file on every read,
12//! so an edit after approval can't run until it is approved again — whether
13//! or not the folder watcher saw it.
14
15use std::collections::{BTreeMap, HashMap};
16use std::path::{Component, Path, PathBuf};
17use std::sync::{Arc, Mutex, OnceLock};
18
19use hmac::{Hmac, Mac};
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22
23use crate::backend::wconfig::WidgetConfigType;
24use super::signature::{self as sig, Pins, WidgetPublisherPin, WidgetSignatureInfo};
25
26pub const MANIFEST_FILE: &str = "widget.json";
27pub const MANIFEST_VERSION: u32 = 1;
28pub const MAX_PACKAGE_BYTES: u64 = 50 * 1024 * 1024;
29pub const MAX_PACKAGE_FILES: usize = 2000;
30/// Palette commands and status bar items a package may add (spec §6.8).
31pub const MAX_COMMANDS: usize = 20;
32pub const MAX_STATUS_ITEMS: usize = 4;
33const APPROVALS_FILE: &str = "widget-approvals.json";
34/// Publisher → the key its first approved signed package was signed with.
35const PUBLISHERS_FILE: &str = "widget-publishers.json";
36
37/// Every permission a manifest may ask for (spec §6.4). `net:<origin>` is
38/// checked separately.
39pub const PERMISSIONS: &[&str] = &["storage", "files", "clipboard:write", "links:open", "panes", "agents:read", "agents:send", "tasks:read"];
40
41// ── The manifest (spec §5.3) ────────────────────────────────────────────────
42
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
44#[serde(rename_all = "lowercase")]
45#[ts(export, export_to = "../../../frontend/types/rpc/")]
46pub enum WidgetKind {
47    Sandboxed,
48    Trusted,
49}
50
51#[derive(Debug, Clone, Default, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct ManifestPane {
54    pub name: String,
55    #[serde(default)]
56    pub label: Option<String>,
57    #[serde(default)]
58    pub icon: Option<String>,
59    #[serde(default)]
60    pub entry: Option<String>,
61    #[serde(default)]
62    pub default_meta: Option<serde_json::Map<String, serde_json::Value>>,
63    #[serde(default)]
64    pub singleton: bool,
65}
66
67/// A command palette entry (spec §6.8).
68#[derive(Debug, Clone, Default, Serialize, Deserialize)]
69pub struct ManifestCommand {
70    pub id: String,
71    pub title: String,
72    #[serde(default)]
73    pub icon: Option<String>,
74    /// The pane it runs in; the first pane when left out.
75    #[serde(default)]
76    pub pane: Option<String>,
77    #[serde(default)]
78    pub keywords: Option<String>,
79}
80
81/// A status bar item (spec §6.8).
82#[derive(Debug, Clone, Default, Serialize, Deserialize)]
83pub struct ManifestStatusItem {
84    pub id: String,
85    pub text: String,
86    #[serde(default)]
87    pub icon: Option<String>,
88    #[serde(default)]
89    pub tooltip: Option<String>,
90    /// One of the package's commands, run on a click; the first pane opens
91    /// when left out.
92    #[serde(default)]
93    pub command: Option<String>,
94    #[serde(default)]
95    pub alignment: Option<StatusAlignment>,
96}
97
98#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
99#[serde(rename_all = "lowercase")]
100#[ts(export, export_to = "../../../frontend/types/rpc/")]
101pub enum StatusAlignment {
102    Left,
103    #[default]
104    Right,
105}
106
107#[derive(Debug, Clone, Default, Serialize, Deserialize)]
108pub struct ManifestContributes {
109    #[serde(default)]
110    pub panes: Vec<ManifestPane>,
111    #[serde(default)]
112    pub commands: Vec<ManifestCommand>,
113    #[serde(default, rename = "statusItems")]
114    pub status_items: Vec<ManifestStatusItem>,
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
118#[serde(rename_all = "camelCase")]
119pub struct Manifest {
120    pub manifest_version: u32,
121    pub id: String,
122    pub name: String,
123    pub version: String,
124    #[serde(default)]
125    pub description: Option<String>,
126    #[serde(default)]
127    pub author: Option<String>,
128    #[serde(default)]
129    pub homepage: Option<String>,
130    #[serde(default)]
131    pub icon: Option<String>,
132    #[serde(default)]
133    pub default_hue: Option<i64>,
134    #[serde(default)]
135    pub kind: Option<WidgetKind>,
136    #[serde(default)]
137    pub entry: Option<String>,
138    #[serde(default)]
139    pub permissions: Vec<String>,
140    #[serde(default)]
141    pub min_agent_mux: Option<String>,
142    pub contributes: ManifestContributes,
143}
144
145impl Manifest {
146    pub fn kind(&self) -> WidgetKind {
147        self.kind.clone().unwrap_or(WidgetKind::Sandboxed)
148    }
149
150    fn default_entry(&self) -> String {
151        self.entry.clone().unwrap_or_else(|| match self.kind() {
152            WidgetKind::Sandboxed => "index.html".to_string(),
153            WidgetKind::Trusted => "index.js".to_string(),
154        })
155    }
156}
157
158fn is_slug(s: &str) -> bool {
159    !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
160}
161
162pub fn valid_id(id: &str) -> bool {
163    id.len() <= 64 && matches!(id.split_once('.'), Some((a, b)) if is_slug(a) && is_slug(b))
164}
165
166/// A Font Awesome name: lowercase letters, digits and `-`.
167fn valid_icon(icon: &Option<String>) -> bool {
168    icon.as_deref().is_none_or(|i| i.len() <= 60 && is_slug(i))
169}
170
171pub(crate) fn valid_semver(v: &str) -> bool {
172    let core = v.split(['-', '+']).next().unwrap_or("");
173    let parts: Vec<&str> = core.split('.').collect();
174    parts.len() == 3 && parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
175}
176
177/// A permission is a known name, or `net:<origin>`: `http(s)://host[:port]`,
178/// where host may start with `*.` (subdomains), never a bare `*`.
179pub fn valid_permission(p: &str) -> bool {
180    if PERMISSIONS.contains(&p) {
181        return true;
182    }
183    let Some(origin) = p.strip_prefix("net:") else {
184        return false;
185    };
186    let Some(rest) = origin.strip_prefix("https://").or_else(|| origin.strip_prefix("http://")) else {
187        return false;
188    };
189    if rest.is_empty() || rest.contains('/') || rest.contains('?') || rest.contains('#') || rest.contains('@') {
190        return false;
191    }
192    let host = rest.rsplit_once(':').map(|(h, port)| (h, port)).map_or(rest, |(h, port)| {
193        if port.bytes().all(|b| b.is_ascii_digit()) && !port.is_empty() {
194            h
195        } else {
196            "\u{0}"
197        }
198    });
199    let bare = host.strip_prefix("*.").unwrap_or(host);
200    !bare.is_empty() && !bare.contains('*') && bare.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-' || b == b'[' || b == b']' || b == b':')
201}
202
203/// A path inside a package: relative, `/`-separated, no `..`.
204fn valid_rel_path(p: &str) -> bool {
205    !p.is_empty()
206        && !p.starts_with('/')
207        && !p.contains('\\')
208        && Path::new(p).components().all(|c| matches!(c, Component::Normal(_)))
209}
210
211/// Check a manifest; the first problem, in words the user can act on.
212pub fn validate(m: &Manifest, folder: &str) -> Result<(), String> {
213    if m.manifest_version != MANIFEST_VERSION {
214        return Err(format!(
215            "manifestVersion {} isn't one this AgentMux reads (it reads {MANIFEST_VERSION})",
216            m.manifest_version
217        ));
218    }
219    if !valid_id(&m.id) {
220        return Err(format!("id {:?} must look like publisher.name (lowercase letters, digits, -)", m.id));
221    }
222    if m.id != folder {
223        return Err(format!("id {:?} must match its folder name {:?}", m.id, folder));
224    }
225    if m.name.trim().is_empty() || m.name.chars().count() > 60 {
226        return Err("name must be 1–60 characters".to_string());
227    }
228    if !valid_semver(&m.version) {
229        return Err(format!("version {:?} isn't semver (like 1.2.0)", m.version));
230    }
231    if m.description.as_deref().is_some_and(|d| d.chars().count() > 300) {
232        return Err("description is longer than 300 characters".to_string());
233    }
234    if let Some(h) = &m.homepage {
235        if !h.starts_with("https://") {
236            return Err("homepage must be an https:// link".to_string());
237        }
238    }
239    if let Some(h) = m.default_hue {
240        if !(0..=359).contains(&h) {
241            return Err("defaultHue must be 0–359".to_string());
242        }
243    }
244    for p in &m.permissions {
245        if !valid_permission(p) {
246            return Err(format!("unknown permission {p:?}"));
247        }
248    }
249    if m.contributes.panes.is_empty() {
250        return Err("contributes.panes must list at least one pane".to_string());
251    }
252    let mut seen = std::collections::HashSet::new();
253    for pane in &m.contributes.panes {
254        if !is_slug(&pane.name) {
255            return Err(format!("pane name {:?} must be lowercase letters, digits and -", pane.name));
256        }
257        if !seen.insert(pane.name.as_str()) {
258            return Err(format!("two panes are named {:?}", pane.name));
259        }
260        let entry = pane.entry.clone().unwrap_or_else(|| m.default_entry());
261        if !valid_rel_path(&entry) {
262            return Err(format!("entry {entry:?} must be a path inside the package"));
263        }
264        if let Some(meta) = &pane.default_meta {
265            if let Some(k) = meta.keys().find(|k| !k.starts_with("widget:")) {
266                return Err(format!("defaultMeta key {k:?} must start with \"widget:\""));
267            }
268        }
269    }
270    validate_contributions(m)
271}
272
273/// `contributes.commands` and `contributes.statusItems` (spec §6.8).
274fn validate_contributions(m: &Manifest) -> Result<(), String> {
275    let c = &m.contributes;
276    if c.commands.len() > MAX_COMMANDS {
277        return Err(format!("contributes.commands lists more than {MAX_COMMANDS} commands"));
278    }
279    let mut seen = std::collections::HashSet::new();
280    for cmd in &c.commands {
281        if !is_slug(&cmd.id) || cmd.id.len() > 60 {
282            return Err(format!("command id {:?} must be lowercase letters, digits and -", cmd.id));
283        }
284        if !seen.insert(cmd.id.as_str()) {
285            return Err(format!("two commands have the id {:?}", cmd.id));
286        }
287        if cmd.title.trim().is_empty() || cmd.title.chars().count() > 60 {
288            return Err(format!("command {:?} needs a title of 1–60 characters", cmd.id));
289        }
290        if !valid_icon(&cmd.icon) {
291            return Err(format!("command {:?}: icon must be a Font Awesome name", cmd.id));
292        }
293        if cmd.keywords.as_deref().is_some_and(|k| k.chars().count() > 200) {
294            return Err(format!("command {:?}: keywords are longer than 200 characters", cmd.id));
295        }
296        if let Some(p) = &cmd.pane {
297            if !c.panes.iter().any(|pane| &pane.name == p) {
298                return Err(format!("command {:?} runs in pane {p:?}, which the package doesn't contribute", cmd.id));
299            }
300        }
301    }
302    if c.status_items.len() > MAX_STATUS_ITEMS {
303        return Err(format!("contributes.statusItems lists more than {MAX_STATUS_ITEMS} items"));
304    }
305    let mut seen = std::collections::HashSet::new();
306    for item in &c.status_items {
307        if !is_slug(&item.id) || item.id.len() > 60 {
308            return Err(format!("status item id {:?} must be lowercase letters, digits and -", item.id));
309        }
310        if !seen.insert(item.id.as_str()) {
311            return Err(format!("two status items have the id {:?}", item.id));
312        }
313        if item.text.trim().is_empty() || item.text.chars().count() > 40 {
314            return Err(format!("status item {:?} needs a text of 1–40 characters", item.id));
315        }
316        if item.tooltip.as_deref().is_some_and(|t| t.chars().count() > 120) {
317            return Err(format!("status item {:?}: tooltip is longer than 120 characters", item.id));
318        }
319        if !valid_icon(&item.icon) {
320            return Err(format!("status item {:?}: icon must be a Font Awesome name", item.id));
321        }
322        if let Some(cmd) = &item.command {
323            if !c.commands.iter().any(|x| &x.id == cmd) {
324                return Err(format!("status item {:?} runs command {cmd:?}, which the package doesn't contribute", item.id));
325            }
326        }
327    }
328    Ok(())
329}
330
331// ── Files and the content hash (spec §5.1, §8.2) ────────────────────────────
332
333/// Every file in `dir` (relative path → SHA-256 hex), within the limits, with
334/// no symlinks. `widget.sig` at the root is left out: it signs the hash of
335/// the rest (SPEC_WIDGET_SHARING_2026_10_10.md §2.1).
336pub fn hash_files(dir: &Path) -> Result<BTreeMap<String, String>, String> {
337    hash_files_except(dir, sig::WIDGET.sig_file)
338}
339
340/// [`hash_files`], leaving out `sig_file` at the root instead: another
341/// signing domain's signature file.
342pub fn hash_files_except(dir: &Path, sig_file: &str) -> Result<BTreeMap<String, String>, String> {
343    let mut out = BTreeMap::new();
344    let mut total: u64 = 0;
345    let mut stack = vec![dir.to_path_buf()];
346    while let Some(d) = stack.pop() {
347        let entries = std::fs::read_dir(&d).map_err(|e| format!("can't read {}: {e}", d.display()))?;
348        for entry in entries {
349            let entry = entry.map_err(|e| e.to_string())?;
350            let ft = entry.file_type().map_err(|e| e.to_string())?;
351            let path = entry.path();
352            if ft.is_symlink() {
353                return Err(format!("{} is a link; a package can't contain links", path.display()));
354            }
355            if ft.is_dir() {
356                stack.push(path);
357                continue;
358            }
359            let rel = path
360                .strip_prefix(dir)
361                .map_err(|e| e.to_string())?
362                .components()
363                .map(|c| c.as_os_str().to_string_lossy().into_owned())
364                .collect::<Vec<_>>()
365                .join("/");
366            if rel == sig_file {
367                continue;
368            }
369            let bytes = std::fs::read(&path).map_err(|e| format!("can't read {rel}: {e}"))?;
370            total += bytes.len() as u64;
371            if total > MAX_PACKAGE_BYTES {
372                return Err(format!("the package is over {} MB", MAX_PACKAGE_BYTES / (1024 * 1024)));
373            }
374            out.insert(rel, hex::encode(Sha256::digest(&bytes)));
375            if out.len() > MAX_PACKAGE_FILES {
376                return Err(format!("the package has over {MAX_PACKAGE_FILES} files"));
377            }
378        }
379    }
380    Ok(out)
381}
382
383/// The package's content hash: SHA-256 over each file's path and hash, in
384/// path order. Any change to any file changes it.
385pub fn package_hash(files: &BTreeMap<String, String>) -> String {
386    let mut h = Sha256::new();
387    for (path, file_hash) in files {
388        h.update(path.as_bytes());
389        h.update([0]);
390        h.update(file_hash.as_bytes());
391        h.update([b'\n']);
392    }
393    hex::encode(h.finalize())
394}
395
396// ── Approvals (spec §8.3) ───────────────────────────────────────────────────
397
398#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
399pub struct Approval {
400    pub hash: String,
401    pub kind: WidgetKind,
402    pub permissions: Vec<String>,
403    /// Per-file hashes at approval: what the files route checks every read
404    /// against.
405    pub files: BTreeMap<String, String>,
406    pub approved_at: i64,
407    #[serde(default = "yes")]
408    pub enabled: bool,
409    /// The publisher key that signed it (base64), if it was signed.
410    #[serde(default)]
411    pub signer: Option<String>,
412}
413
414fn yes() -> bool {
415    true
416}
417
418pub type Approvals = BTreeMap<String, Approval>;
419
420/// The approvals that read, each on its own: one this build cannot read (a kind a newer AgentMux wrote) is left out of the answer,
421/// not the whole file, and [`write_approvals`] keeps it on disk as it was.
422pub fn read_approvals(path: &Path) -> Approvals {
423    crate::backend::json_keep::read_entries(path)
424}
425
426/// Writes `approvals`, and keeps every approval already on disk that this build cannot read, exactly as it was.
427pub fn write_approvals(path: &Path, approvals: &Approvals) -> Result<(), String> {
428    crate::backend::json_keep::write_entries(path, approvals)
429}
430
431/// [`write_approvals`] for an uninstall: the approval of `removed` is dropped from the file even when this build cannot read it.
432pub fn write_approvals_removing(path: &Path, approvals: &Approvals, removed: &str) -> Result<(), String> {
433    crate::backend::json_keep::write_entries_removing(path, approvals, &[removed])
434}
435
436// ── What the frontend sees (spec §8.1) ──────────────────────────────────────
437
438#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
439#[serde(rename_all = "snake_case")]
440#[ts(export, export_to = "../../../frontend/types/rpc/")]
441pub enum WidgetState {
442    Approved,
443    NeedsApproval,
444    Changed,
445    Invalid,
446    Disabled,
447}
448
449#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
450#[ts(export, export_to = "../../../frontend/types/rpc/")]
451pub struct WidgetPaneInfo {
452    /// `ext:<id>/<name>` (or a v1 widget's own `ext:<name>`).
453    pub view: String,
454    pub name: String,
455    pub label: String,
456    pub icon: String,
457    pub entry: String,
458    pub singleton: bool,
459    #[ts(type = "Record<string, unknown>")]
460    pub default_meta: serde_json::Map<String, serde_json::Value>,
461}
462
463/// A palette command, as the UI registers it (spec §6.8).
464#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
465#[ts(export, export_to = "../../../frontend/types/rpc/")]
466pub struct WidgetCommandInfo {
467    pub id: String,
468    pub title: String,
469    pub icon: String,
470    /// The view of the pane it runs in.
471    pub view: String,
472    pub keywords: String,
473}
474
475/// A status bar item, before any pane of the widget updates it.
476#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
477#[ts(export, export_to = "../../../frontend/types/rpc/")]
478pub struct WidgetStatusItemInfo {
479    pub id: String,
480    pub text: String,
481    pub icon: String,
482    pub tooltip: Option<String>,
483    pub command: Option<String>,
484    pub alignment: StatusAlignment,
485}
486
487#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
488#[ts(export, export_to = "../../../frontend/types/rpc/")]
489pub struct WidgetPackageInfo {
490    pub id: String,
491    pub name: String,
492    pub version: String,
493    pub description: Option<String>,
494    pub author: Option<String>,
495    pub homepage: Option<String>,
496    pub icon: String,
497    #[ts(type = "number | null")]
498    pub default_hue: Option<i64>,
499    pub kind: WidgetKind,
500    pub permissions: Vec<String>,
501    /// Permissions the user granted, when approved (an update that asks for
502    /// more is `changed` until approved again).
503    pub granted: Vec<String>,
504    pub state: WidgetState,
505    pub error: Option<String>,
506    /// The current content hash (empty when the files couldn't be read).
507    pub hash: String,
508    pub panes: Vec<WidgetPaneInfo>,
509    pub commands: Vec<WidgetCommandInfo>,
510    pub status_items: Vec<WidgetStatusItemInfo>,
511    /// Who signed it, against this instance's pinned publishers.
512    pub signature: WidgetSignatureInfo,
513    /// Where its files are served, ending in `/`, while it is approved and
514    /// enabled; relative to srv's web endpoint.
515    pub files_url: Option<String>,
516    /// A v1 `widgets.json` module entry, shown as an implied package.
517    pub implied: bool,
518    pub folder: String,
519}
520
521// ── The scan ────────────────────────────────────────────────────────────────
522
523/// A package found on disk, before approval is applied.
524#[derive(Debug, Clone)]
525pub struct Found {
526    pub id: String,
527    pub dir: PathBuf,
528    pub manifest: Result<Manifest, String>,
529    pub files: Result<BTreeMap<String, String>, String>,
530    pub implied: bool,
531}
532
533/// Every folder in `widgets_dir` (a missing folder is none).
534pub fn scan(widgets_dir: &Path) -> Vec<Found> {
535    let mut out = Vec::new();
536    let Ok(entries) = std::fs::read_dir(widgets_dir) else {
537        return out;
538    };
539    for entry in entries.flatten() {
540        let Ok(ft) = entry.file_type() else { continue };
541        if !ft.is_dir() {
542            continue;
543        }
544        let dir = entry.path();
545        let folder = entry.file_name().to_string_lossy().into_owned();
546        let manifest_path = dir.join(MANIFEST_FILE);
547        if !manifest_path.exists() {
548            // A v1 widget's module folder (e.g. hello/ with only index.js) is
549            // not a package; the v1 entry in widgets.json names it instead.
550            continue;
551        }
552        let manifest = std::fs::read_to_string(&manifest_path)
553            .map_err(|e| format!("can't read widget.json: {e}"))
554            .and_then(|s| serde_json::from_str::<Manifest>(&s).map_err(|e| format!("widget.json: {e}")))
555            .and_then(|m| validate(&m, &folder).map(|()| m));
556        out.push(Found { id: folder, files: hash_files(&dir), dir, manifest, implied: false });
557    }
558    out.sort_by(|a, b| a.id.cmp(&b.id));
559    out
560}
561
562/// A v1 `widgets.json` entry with a `module` as an implied trusted package
563/// (spec §5.5): its one module file is the package.
564pub fn implied_from_v1(key: &str, entry: &WidgetConfigType, widgets_dir: &Path) -> Option<Found> {
565    let module = entry.module.as_str();
566    if module.is_empty() {
567        return None;
568    }
569    let view = entry.block_def.meta.get("view").and_then(|v| v.as_str())?.to_string();
570    let name = view.strip_prefix("ext:")?;
571    if name.contains('/') {
572        return None;
573    }
574    let raw = Path::new(module);
575    let path = if raw.is_absolute() { raw.to_path_buf() } else { widgets_dir.join(raw) };
576    let dir = path.parent()?.to_path_buf();
577    let file = path.file_name()?.to_string_lossy().into_owned();
578    let slug: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
579    let id = format!("local.{slug}");
580    let files = std::fs::read(&path)
581        .map_err(|e| format!("can't read {}: {e}", path.display()))
582        .map(|bytes| BTreeMap::from([(file.clone(), hex::encode(Sha256::digest(&bytes)))]));
583    let manifest = Manifest {
584        manifest_version: MANIFEST_VERSION,
585        id: id.clone(),
586        name: if entry.label.is_empty() { name.to_string() } else { entry.label.clone() },
587        version: "0.0.0".to_string(),
588        description: Some(format!("From widgets.json ({key})")),
589        author: None,
590        homepage: None,
591        icon: Some(entry.icon.clone()).filter(|i| !i.is_empty()),
592        default_hue: None,
593        kind: Some(WidgetKind::Trusted),
594        entry: Some(file),
595        permissions: vec![],
596        min_agent_mux: None,
597        contributes: ManifestContributes {
598            panes: vec![ManifestPane { name: slug, label: None, icon: None, entry: None, default_meta: None, singleton: false }],
599            commands: vec![],
600            status_items: vec![],
601        },
602    };
603    Some(Found { id, dir, manifest: Ok(manifest), files, implied: true })
604}
605
606/// The view a pane opens as: `ext:<id>/<name>`, or a v1 widget's own name.
607fn pane_view(found: &Found, m: &Manifest, pane: &ManifestPane, v1_view: Option<&str>) -> String {
608    match (found.implied, v1_view) {
609        (true, Some(v)) => v.to_string(),
610        _ => format!("ext:{}/{}", m.id, pane.name),
611    }
612}
613
614/// The files URL's unguessable part: HMAC(instance secret, id, hash), so a web
615/// page outside AgentMux can't name a package's files (they aren't secret,
616/// but nothing else needs them).
617pub fn files_key(secret: &str, id: &str, hash: &str) -> String {
618    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("any key length");
619    mac.update(b"agentmux-widget-files\0");
620    mac.update(id.as_bytes());
621    mac.update(b"\0");
622    mac.update(hash.as_bytes());
623    hex::encode(&mac.finalize().into_bytes()[..16])
624}
625
626/// Combine what's on disk with this instance's approvals and pins.
627pub fn describe(found: &Found, approvals: &Approvals, pins: &Pins, secret: &str, v1_view: Option<&str>) -> WidgetPackageInfo {
628    let folder = found.dir.display().to_string();
629    let invalid = |error: String| WidgetPackageInfo {
630        id: found.id.clone(),
631        name: found.id.clone(),
632        version: String::new(),
633        description: None,
634        author: None,
635        homepage: None,
636        icon: "puzzle-piece".to_string(),
637        default_hue: None,
638        kind: WidgetKind::Sandboxed,
639        permissions: vec![],
640        granted: vec![],
641        state: WidgetState::Invalid,
642        error: Some(error),
643        hash: String::new(),
644        panes: vec![],
645        commands: vec![],
646        status_items: vec![],
647        signature: sig::describe(&found.id, None, pins),
648        files_url: None,
649        implied: found.implied,
650        folder: folder.clone(),
651    };
652    let m = match &found.manifest {
653        Ok(m) => m,
654        Err(e) => return invalid(e.clone()),
655    };
656    let files = match &found.files {
657        Ok(f) => f,
658        Err(e) => return invalid(e.clone()),
659    };
660    let entry_missing = m.contributes.panes.iter().find_map(|p| {
661        let entry = p.entry.clone().unwrap_or_else(|| m.default_entry());
662        (!files.contains_key(&entry)).then_some(entry)
663    });
664    if let Some(entry) = entry_missing {
665        return invalid(format!("its entry {entry:?} isn't in the package"));
666    }
667    let hash = package_hash(files);
668    let signer = match sig::check(&sig::WIDGET, &found.dir, &m.id, &m.version, &hash) {
669        None => None,
670        Some(Ok(key)) => Some(key),
671        Some(Err(e)) => return invalid(e),
672    };
673    let kind = m.kind();
674    let approval = approvals.get(&m.id);
675    let state = match approval {
676        None => WidgetState::NeedsApproval,
677        Some(a) if a.hash != hash || a.kind != kind || a.signer != signer => WidgetState::Changed,
678        Some(a) if !a.enabled => WidgetState::Disabled,
679        Some(_) => WidgetState::Approved,
680    };
681    let icon = m.icon.clone().unwrap_or_else(|| "puzzle-piece".to_string());
682    let panes = m
683        .contributes
684        .panes
685        .iter()
686        .map(|p| WidgetPaneInfo {
687            view: pane_view(found, m, p, v1_view),
688            name: p.name.clone(),
689            label: p.label.clone().unwrap_or_else(|| m.name.clone()),
690            icon: p.icon.clone().unwrap_or_else(|| icon.clone()),
691            entry: p.entry.clone().unwrap_or_else(|| m.default_entry()),
692            singleton: p.singleton,
693            default_meta: p.default_meta.clone().unwrap_or_default(),
694        })
695        .collect::<Vec<WidgetPaneInfo>>();
696    let commands = m
697        .contributes
698        .commands
699        .iter()
700        .map(|c| {
701            let pane = c.pane.as_deref().unwrap_or(&m.contributes.panes[0].name);
702            WidgetCommandInfo {
703                id: c.id.clone(),
704                title: c.title.clone(),
705                icon: c.icon.clone().unwrap_or_else(|| icon.clone()),
706                view: panes.iter().find(|p| p.name == pane).map(|p| p.view.clone()).unwrap_or_default(),
707                keywords: c.keywords.clone().unwrap_or_default(),
708            }
709        })
710        .collect();
711    let status_items = m
712        .contributes
713        .status_items
714        .iter()
715        .map(|s| WidgetStatusItemInfo {
716            id: s.id.clone(),
717            text: s.text.clone(),
718            icon: s.icon.clone().unwrap_or_else(|| icon.clone()),
719            tooltip: s.tooltip.clone(),
720            command: s.command.clone(),
721            alignment: s.alignment.unwrap_or_default(),
722        })
723        .collect();
724    let files_url = (state == WidgetState::Approved)
725        .then(|| format!("/agentmux/widget-files/{}/{}/{}/", m.id, hash, files_key(secret, &m.id, &hash)));
726    WidgetPackageInfo {
727        id: m.id.clone(),
728        name: m.name.clone(),
729        version: m.version.clone(),
730        description: m.description.clone(),
731        author: m.author.clone(),
732        homepage: m.homepage.clone(),
733        icon,
734        default_hue: m.default_hue,
735        kind: kind.clone(),
736        permissions: if kind == WidgetKind::Trusted { vec![] } else { m.permissions.clone() },
737        granted: approval.filter(|a| a.hash == hash).map(|a| a.permissions.clone()).unwrap_or_default(),
738        state,
739        error: None,
740        hash,
741        panes,
742        commands,
743        status_items,
744        signature: sig::describe(&m.id, signer.as_deref(), pins),
745        files_url,
746        implied: found.implied,
747        folder,
748    }
749}
750
751/// The widget-bar entries an approved, enabled package adds, keyed
752/// `ext@<id>/<name>` (spec §5.4). v1 widgets already have theirs.
753pub fn widget_entries(packages: &[WidgetPackageInfo]) -> HashMap<String, WidgetConfigType> {
754    let mut out = HashMap::new();
755    for p in packages.iter().filter(|p| p.state == WidgetState::Approved && !p.implied) {
756        for pane in &p.panes {
757            let mut entry = WidgetConfigType {
758                label: pane.label.clone(),
759                icon: pane.icon.clone(),
760                description: p.description.clone().unwrap_or_default(),
761                ..Default::default()
762            };
763            entry.block_def.meta.insert("view".to_string(), serde_json::Value::String(pane.view.clone()));
764            for (k, v) in &pane.default_meta {
765                entry.block_def.meta.insert(k.clone(), v.clone());
766            }
767            out.insert(format!("ext@{}/{}", p.id, pane.name), entry);
768        }
769    }
770    out
771}
772
773// ── The service ─────────────────────────────────────────────────────────────
774
775/// srv's view of the widgets folder and this instance's approvals.
776pub struct WidgetPackages {
777    pub widgets_dir: PathBuf,
778    approvals_path: PathBuf,
779    pins_path: PathBuf,
780    secret: String,
781    inner: Mutex<Inner>,
782}
783
784#[derive(Default)]
785struct Inner {
786    found: Vec<Found>,
787    v1_views: HashMap<String, String>,
788    packages: Vec<WidgetPackageInfo>,
789    approvals: Approvals,
790    pins: Pins,
791}
792
793static SERVICE: OnceLock<Arc<WidgetPackages>> = OnceLock::new();
794
795pub fn service() -> Option<&'static Arc<WidgetPackages>> {
796    SERVICE.get()
797}
798
799/// `~/.agentmux/widgets`, shared by every channel (spec §3, decision 5).
800pub fn widgets_dir() -> PathBuf {
801    crate::srv_info::agentmux_home()
802        .unwrap_or_else(crate::backend::base::get_mux_data_dir)
803        .join("widgets")
804}
805
806impl WidgetPackages {
807    pub fn new(widgets_dir: PathBuf, data_dir: &Path, secret: String) -> Self {
808        let approvals_path = data_dir.join(APPROVALS_FILE);
809        let approvals = read_approvals(&approvals_path);
810        let pins_path = data_dir.join(PUBLISHERS_FILE);
811        let pins = sig::read_pins(&pins_path);
812        Self { widgets_dir, approvals_path, pins_path, secret, inner: Mutex::new(Inner { approvals, pins, ..Default::default() }) }
813    }
814
815    pub fn install_global(self) -> &'static Arc<WidgetPackages> {
816        SERVICE.get_or_init(|| Arc::new(self))
817    }
818
819    /// The process-wide service for tests, in one temp folder that lives as
820    /// long as the process: every test that needs the global service shares
821    /// it, so each finds its own package by id.
822    #[cfg(any(test, feature = "test-support"))]
823    pub fn for_tests() -> &'static Arc<WidgetPackages> {
824        static DIR: OnceLock<tempfile::TempDir> = OnceLock::new();
825        let dir = DIR.get_or_init(|| tempfile::tempdir().unwrap());
826        WidgetPackages::new(dir.path().join("widgets"), &dir.path().join("data"), "test-secret-key".into()).install_global()
827    }
828
829    /// Scan again, with the v1 entries currently in the user's widgets.json.
830    pub fn rescan(&self, v1_entries: &HashMap<String, WidgetConfigType>) -> Vec<WidgetPackageInfo> {
831        let mut found = scan(&self.widgets_dir);
832        let mut v1_views = HashMap::new();
833        let mut keys: Vec<&String> = v1_entries.keys().collect();
834        keys.sort();
835        for key in keys {
836            if let Some(f) = implied_from_v1(key, &v1_entries[key], &self.widgets_dir) {
837                if found.iter().any(|x| x.id == f.id) {
838                    continue;
839                }
840                if let Some(v) = v1_entries[key].block_def.meta.get("view").and_then(|v| v.as_str()) {
841                    v1_views.insert(f.id.clone(), v.to_string());
842                }
843                found.push(f);
844            }
845        }
846        let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
847        let packages = found
848            .iter()
849            .map(|f| describe(f, &inner.approvals, &inner.pins, &self.secret, v1_views.get(&f.id).map(String::as_str)))
850            .collect::<Vec<_>>();
851        inner.found = found;
852        inner.v1_views = v1_views;
853        inner.packages = packages.clone();
854        packages
855    }
856
857    pub fn list(&self) -> Vec<WidgetPackageInfo> {
858        self.inner.lock().unwrap_or_else(|p| p.into_inner()).packages.clone()
859    }
860
861    /// Record the user's approval of exactly `hash`, signed by the key whose
862    /// fingerprint the prompt showed (`shown_signer`, "" for unsigned); the
863    /// host-only route calls this. Fails if the package or its signature
864    /// changed since the prompt was shown: `widget.sig` isn't in the hash, so
865    /// it is checked here (SPEC_WIDGET_SHARING_2026_10_10.md §2.3).
866    pub fn approve(&self, id: &str, hash: &str, shown_signer: &str) -> Result<(), String> {
867        let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
868        let found = inner.found.iter().find(|f| f.id == id).ok_or("no such widget")?;
869        let m = found.manifest.as_ref().map_err(|e| e.clone())?;
870        let files = found.files.as_ref().map_err(|e| e.clone())?;
871        if package_hash(files) != hash {
872            return Err("the widget changed since you were asked; review it again".to_string());
873        }
874        let signer = match sig::check(&sig::WIDGET, &found.dir, &m.id, &m.version, hash) {
875            None => None,
876            Some(Ok(key)) => Some(key),
877            Some(Err(e)) => return Err(e),
878        };
879        if signer.as_deref().map(sig::fingerprint).unwrap_or_default() != shown_signer {
880            return Err("the widget's signature changed since you were asked; review it again".to_string());
881        }
882        // The first signed package of a publisher pins it to its key; a
883        // later one signed otherwise doesn't move the pin
884        // (SPEC_WIDGET_SHARING_2026_10_10.md §2.2).
885        let publisher = sig::publisher_of(id).to_string();
886        let pin = signer.clone().filter(|_| !inner.pins.contains_key(&publisher));
887        let approval = Approval {
888            hash: hash.to_string(),
889            kind: m.kind(),
890            permissions: if m.kind() == WidgetKind::Trusted { vec![] } else { m.permissions.clone() },
891            files: files.clone(),
892            approved_at: chrono::Utc::now().timestamp(),
893            enabled: true,
894            signer,
895        };
896        if let Some(key) = pin {
897            inner.pins.insert(publisher, key);
898            sig::write_pins(&self.pins_path, &inner.pins)?;
899        }
900        inner.approvals.insert(id.to_string(), approval);
901        write_approvals(&self.approvals_path, &inner.approvals)
902    }
903
904    /// Who signed a package, against this instance's pins.
905    pub fn describe_signature(&self, id: &str, signer: Option<&str>) -> WidgetSignatureInfo {
906        sig::describe(id, signer, &self.inner.lock().unwrap_or_else(|p| p.into_inner()).pins)
907    }
908
909    /// An approved sandboxed package's approved bytes, for a bundle export
910    /// (SPEC_WIDGET_SHARING_2026_10_10.md §3.4): every file hashed again
911    /// against the approval, never a newer copy on disk, and its
912    /// `widget.sig` when it still names the approved signer.
913    pub fn approved_package(&self, id: &str) -> Result<(String, BTreeMap<String, Vec<u8>>), String> {
914        let (dir, approval) = {
915            let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
916            let a = inner.approvals.get(id).filter(|a| a.enabled).cloned().ok_or(format!("{id} isn't installed and turned on"))?;
917            let dir = inner.found.iter().find(|f| f.id == id && !f.implied).map(|f| f.dir.clone()).ok_or(format!("{id} isn't a widget package"))?;
918            (dir, a)
919        };
920        if approval.kind != WidgetKind::Sandboxed {
921            return Err(format!("{id} is a trusted widget; bundles carry sandboxed widgets only"));
922        }
923        let mut files = BTreeMap::new();
924        for (path, file_hash) in &approval.files {
925            let bytes = std::fs::read(dir.join(path)).map_err(|e| format!("{id}: can't read {path}: {e}"))?;
926            if hex::encode(Sha256::digest(&bytes)) != *file_hash {
927                return Err(format!("{id} changed since you approved it; approve it again first"));
928            }
929            files.insert(path.clone(), bytes);
930        }
931        if let Some(signer) = &approval.signer {
932            let text = std::fs::read(dir.join(sig::SIG_FILE)).map_err(|_| format!("{id} lost its signature since you approved it"))?;
933            let manifest: Manifest = serde_json::from_slice(files.get(MANIFEST_FILE).ok_or("no widget.json")?).map_err(|e| e.to_string())?;
934            if sig::check(&sig::WIDGET, &dir, id, &manifest.version, &approval.hash) != Some(Ok(signer.clone())) {
935                return Err(format!("{id}'s signature changed since you approved it"));
936            }
937            files.insert(sig::SIG_FILE.to_string(), text);
938        }
939        Ok((approval.hash, files))
940    }
941
942    /// The publishers this instance has pinned to a key, for Settings.
943    pub fn publishers(&self) -> Vec<WidgetPublisherPin> {
944        let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
945        inner.pins.iter().map(|(publisher, key)| WidgetPublisherPin { publisher: publisher.clone(), fingerprint: sig::fingerprint(key) }).collect()
946    }
947
948    /// Forget a publisher's key (the user's **Forget key**, through the host
949    /// route): its next signed package pins it again.
950    pub fn forget_publisher(&self, publisher: &str) -> Result<(), String> {
951        let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
952        // A key this build cannot read is not in the map but is on disk, and is forgotten too.
953        if inner.pins.remove(publisher).is_none() && !crate::backend::json_keep::has_record(&self.pins_path, publisher) {
954            return Err(format!("no key is kept for {publisher:?}"));
955        }
956        sig::write_pins_removing(&self.pins_path, &inner.pins, publisher)
957    }
958
959    pub fn set_enabled(&self, id: &str, enabled: bool) -> Result<(), String> {
960        let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
961        let a = inner.approvals.get_mut(id).ok_or("that widget isn't approved")?;
962        a.enabled = enabled;
963        write_approvals(&self.approvals_path, &inner.approvals)
964    }
965
966    /// Forget a package's approval (uninstall does this; so does a v1 entry
967    /// leaving widgets.json, at the next rescan's caller's choice).
968    pub fn forget(&self, id: &str) -> Result<(), String> {
969        let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
970        inner.approvals.remove(id);
971        write_approvals_removing(&self.approvals_path, &inner.approvals, id)
972    }
973
974    pub fn package_dir(&self, id: &str) -> Option<(PathBuf, bool)> {
975        let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
976        inner.found.iter().find(|f| f.id == id).map(|f| (f.dir.clone(), f.implied))
977    }
978
979    /// The bytes of `path` in package `id`, if `hash` and `key` name its
980    /// approved version and the file on disk still matches that approval
981    /// (hashed now, not trusted from the last scan).
982    pub fn read_file(&self, id: &str, hash: &str, key: &str, path: &str) -> Result<Vec<u8>, FileError> {
983        if !valid_rel_path(path) {
984            return Err(FileError::NotFound);
985        }
986        if !agentmux_common::secret_eq::secret_eq(key.as_bytes(), files_key(&self.secret, id, hash).as_bytes()) {
987            return Err(FileError::NotFound);
988        }
989        let (dir, file_hash) = {
990            let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
991            let approval = inner.approvals.get(id).filter(|a| a.hash == hash && a.enabled).ok_or(FileError::NotFound)?;
992            let file_hash = approval.files.get(path).cloned().ok_or(FileError::NotFound)?;
993            let dir = inner.found.iter().find(|f| f.id == id).map(|f| f.dir.clone()).ok_or(FileError::NotFound)?;
994            (dir, file_hash)
995        };
996        let full = dir.join(path);
997        // No links anywhere on the way: the approved bytes are the package's
998        // own, not wherever a link points now.
999        let mut p = dir.clone();
1000        for c in Path::new(path).components() {
1001            p.push(c);
1002            if std::fs::symlink_metadata(&p).map(|m| m.file_type().is_symlink()).unwrap_or(true) {
1003                return Err(FileError::NotFound);
1004            }
1005        }
1006        let bytes = std::fs::read(&full).map_err(|_| FileError::NotFound)?;
1007        if hex::encode(Sha256::digest(&bytes)) != file_hash {
1008            return Err(FileError::Changed);
1009        }
1010        Ok(bytes)
1011    }
1012}
1013
1014// ── Keeping everyone current ────────────────────────────────────────────────
1015
1016/// Scan again, merge the widget bar again, and tell every UI.
1017pub fn refresh(
1018    config_watcher: &Arc<crate::backend::wconfig::ConfigState>,
1019    event_bus: &Arc<crate::backend::eventbus::EventBus>,
1020    broker: &crate::backend::mps::Broker,
1021) -> Vec<WidgetPackageInfo> {
1022    let Some(svc) = service() else {
1023        return vec![];
1024    };
1025    let packages = svc.rescan(&crate::backend::user_widgets::last_v1_entries());
1026    crate::backend::user_widgets::recompute(config_watcher);
1027    crate::backend::config_watcher_fs::broadcast_full_config(config_watcher, event_bus);
1028    publish(broker, &packages);
1029    packages
1030}
1031
1032/// `refresh` on a blocking thread: a rescan reads and hashes every file of
1033/// every package, which mustn't stall an async worker.
1034pub async fn refresh_off_thread(
1035    config_watcher: &Arc<crate::backend::wconfig::ConfigState>,
1036    event_bus: &Arc<crate::backend::eventbus::EventBus>,
1037    broker: &Arc<crate::backend::mps::Broker>,
1038) -> Vec<WidgetPackageInfo> {
1039    let (c, e, b) = (config_watcher.clone(), event_bus.clone(), broker.clone());
1040    tokio::task::spawn_blocking(move || refresh(&c, &e, &b)).await.unwrap_or_default()
1041}
1042
1043/// Tell every UI the package list (Settings → Widgets and the loader follow it).
1044pub fn publish(broker: &crate::backend::mps::Broker, packages: &[WidgetPackageInfo]) {
1045    broker.publish_event::<crate::backend::mps_events::WidgetPackages>(&crate::backend::mps_events::WidgetPackagesEvent { packages: packages.to_vec() }, vec![], 0);
1046}
1047
1048/// Start the service: scan, merge, and watch the widgets folder.
1049pub fn start(
1050    data_dir: &Path,
1051    secret: String,
1052    pool: Arc<crate::backend::fs_watch::FsWatchPool>,
1053    config_watcher: Arc<crate::backend::wconfig::ConfigState>,
1054    event_bus: Arc<crate::backend::eventbus::EventBus>,
1055    broker: Arc<crate::backend::mps::Broker>,
1056) {
1057    let data_dir = if data_dir.as_os_str().is_empty() { crate::backend::base::get_mux_data_dir() } else { data_dir.to_path_buf() };
1058    let data_dir = data_dir.as_path();
1059    let dir = widgets_dir();
1060    if let Err(e) = std::fs::create_dir_all(&dir) {
1061        tracing::warn!(dir = %dir.display(), error = %e, "can't create the widgets folder; widget packages off");
1062        return;
1063    }
1064    WidgetPackages::new(dir.clone(), data_dir, secret).install_global();
1065    let packages = refresh(&config_watcher, &event_bus, &broker);
1066    tracing::info!(dir = %dir.display(), count = packages.len(), "widget packages scanned");
1067
1068    let mut events = pool.events();
1069    let _sub = pool.subscribe_dir_recursive(&dir);
1070    let watched = dir.canonicalize().unwrap_or(dir);
1071    tokio::spawn(async move {
1072        let _sub = _sub;
1073        loop {
1074            match events.recv().await {
1075                Ok(ev) if ev.path.starts_with(&watched) => {}
1076                Ok(_) => continue,
1077                Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
1078                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
1079            }
1080            // Coalesce a burst (an editor's save, a copy of a whole folder).
1081            tokio::time::sleep(std::time::Duration::from_millis(400)).await;
1082            while events.try_recv().is_ok() {}
1083            refresh_off_thread(&config_watcher, &event_bus, &broker).await;
1084        }
1085    });
1086}
1087
1088#[derive(Debug, PartialEq)]
1089pub enum FileError {
1090    NotFound,
1091    /// The file no longer matches what the user approved.
1092    Changed,
1093}
1094
1095/// The content type a widget file is served with.
1096pub fn content_type(path: &str) -> &'static str {
1097    let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
1098    match ext.as_str() {
1099        "html" | "htm" => "text/html; charset=utf-8",
1100        "js" | "mjs" => "text/javascript; charset=utf-8",
1101        "css" => "text/css; charset=utf-8",
1102        "json" | "map" => "application/json",
1103        "svg" => "image/svg+xml",
1104        "png" => "image/png",
1105        "jpg" | "jpeg" => "image/jpeg",
1106        "gif" => "image/gif",
1107        "webp" => "image/webp",
1108        "ico" => "image/x-icon",
1109        "woff" => "font/woff",
1110        "woff2" => "font/woff2",
1111        "ttf" => "font/ttf",
1112        "wasm" => "application/wasm",
1113        "txt" | "md" => "text/plain; charset=utf-8",
1114        "mp3" => "audio/mpeg",
1115        "wav" => "audio/wav",
1116        "mp4" => "video/mp4",
1117        "webm" => "video/webm",
1118        _ => "application/octet-stream",
1119    }
1120}
1121
1122/// The policy every widget file is served with (spec §6.1).
1123pub const WIDGET_CSP: &str = "default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; \
1124style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' blob:; \
1125connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'";
1126
1127// ── Install and uninstall (spec §8.4) ───────────────────────────────────────
1128
1129/// Copy the package at `source` (a folder, a `widget.json` in one, or a
1130/// `.zip`) into the widgets folder; returns its id. Validates first; refuses
1131/// to replace an existing package unless `replace`.
1132pub fn install(widgets_dir: &Path, source: &Path, replace: bool) -> Result<String, String> {
1133    install_package(widgets_dir, source, replace, MANIFEST_FILE, validate_manifest)
1134}
1135
1136/// [`install`] for a package a container agent built in its workspace, whose host folder is `root`:
1137/// every file is read only if it is inside `root`. On Unix the copy walks open folders and follows no link
1138/// (`widget::beneath`); elsewhere each file is checked as it is opened (see [`open_within`]).
1139pub fn install_within(widgets_dir: &Path, source: &Path, replace: bool, root: &Path) -> Result<String, String> {
1140    let canonical = root.canonicalize().map_err(|e| format!("the workspace can't be read: {e}"))?;
1141    // `source` was built under the workspace as given. If that path goes through a link (macOS keeps /var and /tmp under
1142    // /private), the walk below, which refuses links, would reject it: name the same place under the canonical folder.
1143    let source = match source.strip_prefix(root) {
1144        Ok(rel) => canonical.join(rel),
1145        Err(_) => source.to_path_buf(),
1146    };
1147    install_checked(widgets_dir, &source, replace, MANIFEST_FILE, Some(&canonical), validate_manifest)
1148}
1149
1150fn validate_manifest(root: &Path) -> Result<String, String> {
1151    let manifest: Manifest =
1152        serde_json::from_str(&std::fs::read_to_string(root.join(MANIFEST_FILE)).map_err(|e| format!("can't read widget.json: {e}"))?)
1153            .map_err(|e| format!("widget.json: {e}"))?;
1154    validate(&manifest, &manifest.id)?;
1155    hash_files(root)?;
1156    Ok(manifest.id)
1157}
1158
1159/// The package folder in an unpacked zip or a copied folder: `stage`
1160/// itself, or its one top folder, whichever holds `manifest_file`.
1161pub(crate) fn package_root(stage: &Path, manifest_file: &str) -> Result<PathBuf, String> {
1162    if stage.join(manifest_file).exists() {
1163        return Ok(stage.to_path_buf());
1164    }
1165    let mut dirs = std::fs::read_dir(stage).map_err(|e| e.to_string())?.flatten().filter(|e| e.path().is_dir());
1166    match (dirs.next(), dirs.next()) {
1167        (Some(d), None) if d.path().join(manifest_file).exists() => Ok(d.path()),
1168        _ => Err(format!("no {manifest_file} at the package's top level")),
1169    }
1170}
1171
1172/// Copy the package at `source` (a folder, its `manifest_file`, or a
1173/// `.zip`) into `packages_dir`, in a folder named by the id `check` returns
1174/// once it has validated the staged copy. Shared by widgets and job
1175/// templates (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.4).
1176pub(crate) fn install_package(
1177    packages_dir: &Path,
1178    source: &Path,
1179    replace: bool,
1180    manifest_file: &str,
1181    check: impl FnOnce(&Path) -> Result<String, String>,
1182) -> Result<String, String> {
1183    install_checked(packages_dir, source, replace, manifest_file, None, check)
1184}
1185
1186fn install_checked(
1187    packages_dir: &Path,
1188    source: &Path,
1189    replace: bool,
1190    manifest_file: &str,
1191    within: Option<&Path>,
1192    check: impl FnOnce(&Path) -> Result<String, String>,
1193) -> Result<String, String> {
1194    let is_zip = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip"));
1195    let staging = tempfile::tempdir_in(packages_dir.parent().unwrap_or(packages_dir))
1196        .or_else(|_| tempfile::tempdir())
1197        .map_err(|e| format!("can't make a staging folder: {e}"))?;
1198    let stage = staging.path().join("pkg");
1199    let folder = if source.file_name().is_some_and(|n| n == manifest_file) { source.parent().unwrap_or(source) } else { source };
1200    match within {
1201        // A container agent's workspace is read through open folders, so no swap on the way is followed.
1202        #[cfg(unix)]
1203        Some(root) if is_zip => unzip_from(super::beneath::file_beneath(root, source).map_err(|e| beneath_error(source, e))?, &stage)?,
1204        #[cfg(unix)]
1205        Some(root) => {
1206            let dir = super::beneath::dir_beneath(root, folder).map_err(|e| beneath_error(folder, e))?;
1207            copy_tree_beneath(&dir, &stage, &mut Budget::default())?;
1208        }
1209        _ if is_zip => unzip_from(open_within(source, within)?, &stage)?,
1210        _ => copy_tree(folder, &stage, &mut Budget::default(), within)?,
1211    }
1212    // A zip may hold the package at its root or in one top-level folder.
1213    let root = package_root(&stage, manifest_file)?;
1214    let id = check(&root)?;
1215    std::fs::create_dir_all(packages_dir).map_err(|e| e.to_string())?;
1216    let dest = packages_dir.join(&id);
1217    // A replaced version moves aside first and comes back if the new one
1218    // can't be put in place, so a failed install never leaves nothing.
1219    let old = staging.path().join("old");
1220    let replacing = dest.exists();
1221    if replacing {
1222        if !replace {
1223            return Err(format!("{id} is already installed"));
1224        }
1225        std::fs::rename(&dest, &old).map_err(|e| format!("can't replace the installed version: {e}"))?;
1226    }
1227    if let Err(e) = put_in_place(&root, &dest) {
1228        let _ = std::fs::remove_dir_all(&dest);
1229        if replacing {
1230            let _ = std::fs::rename(&old, &dest);
1231        }
1232        return Err(e);
1233    }
1234    Ok(id)
1235}
1236
1237/// Moves the staged package to `dest`, or copies it when they're on
1238/// different drives.
1239fn put_in_place(root: &Path, dest: &Path) -> Result<(), String> {
1240    if std::fs::rename(root, dest).is_ok() {
1241        return Ok(());
1242    }
1243    copy_tree(root, dest, &mut Budget::default(), None)
1244}
1245
1246/// What a package may still take while it is copied or unpacked: the limits
1247/// apply to the bytes actually written, so neither a large folder nor a zip
1248/// whose header understates its sizes can fill the disk before hash_files.
1249#[derive(Default)]
1250struct Budget {
1251    bytes: u64,
1252    files: usize,
1253}
1254
1255impl Budget {
1256    /// Copies `from` into `to`, counting what was written against the limits.
1257    fn copy(&mut self, from: &mut impl std::io::Read, to: &Path) -> Result<(), String> {
1258        self.files += 1;
1259        if self.files > MAX_PACKAGE_FILES {
1260            return Err(format!("the package has over {MAX_PACKAGE_FILES} files"));
1261        }
1262        let left = MAX_PACKAGE_BYTES - self.bytes;
1263        let mut w = std::fs::File::create(to).map_err(|e| e.to_string())?;
1264        let written = std::io::copy(&mut from.take(left + 1), &mut w).map_err(|e| e.to_string())?;
1265        if written > left {
1266            return Err(format!("the package is over {} MB", MAX_PACKAGE_BYTES / (1024 * 1024)));
1267        }
1268        self.bytes += written;
1269        Ok(())
1270    }
1271}
1272
1273/// `p` without Windows' `\\?\` verbatim prefix, so a canonical path compares with a folder given without it.
1274fn plain(p: &Path) -> &Path {
1275    let s = p.to_str().unwrap_or_default();
1276    match s.strip_prefix(r"\\?\") {
1277        Some(rest) if !rest.starts_with("UNC\\") => Path::new(rest),
1278        _ => p,
1279    }
1280}
1281
1282/// Opens `path` to read. With `within` (a canonical folder), the file must be one inside it: opened without
1283/// following a link, and the file at that path inside `within` right after is the one opened, so a path
1284/// whose folder was swapped for a link to somewhere else reads nothing from there.
1285pub(crate) fn open_within(path: &Path, within: Option<&Path>) -> Result<std::fs::File, String> {
1286    let mut options = std::fs::OpenOptions::new();
1287    options.read(true);
1288    #[cfg(unix)]
1289    if within.is_some() {
1290        std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NOFOLLOW);
1291    }
1292    let file = options.open(path).map_err(|e| format!("can't open {}: {e}", path.display()))?;
1293    if let Some(root) = within {
1294        let outside = || format!("{} is outside the workspace", path.display());
1295        let real = path.canonicalize().map_err(|_| outside())?;
1296        if !plain(&real).starts_with(plain(root)) {
1297            return Err(outside());
1298        }
1299        // The same file, on every platform (a Windows link is followed by the open, so the identity check is what catches it).
1300        let named = same_file::Handle::from_path(&real).map_err(|_| outside())?;
1301        let opened = same_file::Handle::from_file(file.try_clone().map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
1302        if named != opened {
1303            return Err(outside());
1304        }
1305    }
1306    Ok(file)
1307}
1308
1309#[cfg(unix)]
1310fn beneath_error(path: &Path, e: std::io::Error) -> String {
1311    format!("{} is outside the workspace or a link ({e})", path.display())
1312}
1313
1314/// [`copy_tree`] for a folder that is open: every entry is opened relative to it, and a link is an error.
1315#[cfg(unix)]
1316fn copy_tree_beneath(dir: &std::os::fd::OwnedFd, to: &Path, budget: &mut Budget) -> Result<(), String> {
1317    use super::beneath::Kind;
1318    std::fs::create_dir_all(to).map_err(|e| e.to_string())?;
1319    for (name, kind) in super::beneath::entries(dir).map_err(|e| format!("can't read the folder: {e}"))? {
1320        let target = to.join(&name);
1321        let shown = || name.to_string_lossy().into_owned();
1322        match kind {
1323            Kind::Link => return Err(format!("{} is a link; a package can't contain links", shown())),
1324            Kind::Dir => {
1325                let sub = super::beneath::subdir(dir, &name).map_err(|e| beneath_error(Path::new(&name), e))?;
1326                copy_tree_beneath(&sub, &target, budget)?;
1327            }
1328            Kind::File => {
1329                let mut f = super::beneath::file_in(dir, &name).map_err(|e| beneath_error(Path::new(&name), e))?;
1330                budget.copy(&mut f, &target)?;
1331            }
1332            Kind::Other => return Err(format!("{} isn't a regular file", shown())),
1333        }
1334    }
1335    Ok(())
1336}
1337
1338fn copy_tree(from: &Path, to: &Path, budget: &mut Budget, within: Option<&Path>) -> Result<(), String> {
1339    if let Some(root) = within {
1340        if !from.canonicalize().is_ok_and(|real| plain(&real).starts_with(plain(root))) {
1341            return Err(format!("{} is outside the workspace", from.display()));
1342        }
1343    }
1344    std::fs::create_dir_all(to).map_err(|e| e.to_string())?;
1345    for entry in std::fs::read_dir(from).map_err(|e| format!("can't read {}: {e}", from.display()))? {
1346        let entry = entry.map_err(|e| e.to_string())?;
1347        let ft = entry.file_type().map_err(|e| e.to_string())?;
1348        let target = to.join(entry.file_name());
1349        if ft.is_symlink() {
1350            return Err(format!("{} is a link; a package can't contain links", entry.path().display()));
1351        } else if ft.is_dir() {
1352            copy_tree(&entry.path(), &target, budget, within)?;
1353        } else {
1354            let mut f = open_within(&entry.path(), within)?;
1355            budget.copy(&mut f, &target)?;
1356        }
1357    }
1358    Ok(())
1359}
1360
1361pub(crate) fn unzip(zip_path: &Path, to: &Path) -> Result<(), String> {
1362    unzip_from(open_within(zip_path, None)?, to)
1363}
1364
1365fn unzip_from(file: std::fs::File, to: &Path) -> Result<(), String> {
1366    let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("not a zip file: {e}"))?;
1367    if archive.len() > MAX_PACKAGE_FILES {
1368        return Err(format!("the package has over {MAX_PACKAGE_FILES} files"));
1369    }
1370    let mut budget = Budget::default();
1371    for i in 0..archive.len() {
1372        let mut f = archive.by_index(i).map_err(|e| e.to_string())?;
1373        // enclosed_name refuses `..` and absolute names.
1374        let rel = f.enclosed_name().ok_or_else(|| format!("unsafe path in the zip: {}", f.name()))?;
1375        if f.is_symlink() {
1376            return Err(format!("{} is a link; a package can't contain links", f.name()));
1377        }
1378        let out = to.join(rel);
1379        if f.is_dir() {
1380            std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
1381            continue;
1382        }
1383        if let Some(parent) = out.parent() {
1384            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
1385        }
1386        budget.copy(&mut f, &out)?;
1387    }
1388    Ok(())
1389}
1390
1391use std::io::Read as _;
1392
1393#[cfg(test)]
1394#[path = "packages_tests.rs"]
1395mod tests;