Skip to main content

toolblox_lib/
widgets.rs

1//! Permissioned widget manifests, signed catalogue data, and safe package installation.
2
3use std::collections::HashSet;
4use std::fs::{self, File};
5use std::io::{Cursor, Write};
6use std::path::{Component, Path};
7
8use base64::Engine;
9use ed25519_dalek::{Signature, Verifier, VerifyingKey};
10use semver::Version;
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use url::Url;
14use uuid::Uuid;
15use zip::ZipArchive;
16
17/// Largest widget package download, in bytes.
18const MAX_ARCHIVE_BYTES: usize = 20 * 1024 * 1024;
19/// Largest total size of a package's extracted files, in bytes.
20const MAX_EXPANDED_BYTES: u64 = 80 * 1024 * 1024;
21/// Most entries a package may contain.
22const MAX_FILES: usize = 2_000;
23
24/// A widget's `widget.json`.
25#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
26#[serde(rename_all = "camelCase")]
27pub struct WidgetManifest {
28    pub schema_version: u32,
29    pub id: String,
30    pub name: String,
31    pub version: String,
32    /// Sandboxed iframe page. Optional when the widget provides `module`.
33    #[serde(default)]
34    pub entry: Option<String>,
35    /// ES module loaded into the app window with full access to the host API.
36    #[serde(default)]
37    pub module: Option<String>,
38    /// Sandboxed settings page, which must be `settings.html`.
39    #[serde(default)]
40    pub settings_entry: Option<String>,
41    /// Sandboxed dashboard tile page, which must be `dashboard.html`.
42    #[serde(default)]
43    pub dashboard_entry: Option<String>,
44    #[serde(default)]
45    pub description: String,
46    #[serde(default)]
47    pub icon: Option<String>,
48    /// Image in the package shown across the top of the widget's card.
49    #[serde(default)]
50    pub banner: Option<String>,
51    #[serde(default)]
52    pub permissions: Vec<WidgetPermission>,
53    /// Bare HTTPS origins the widget may fetch. Requires `network.fetch`.
54    #[serde(default)]
55    pub network_origins: Vec<String>,
56    /// Executables under `optional-bin/` the widget may start. Requires `process.spawn`.
57    #[serde(default)]
58    pub processes: Vec<WidgetProcess>,
59    /// Shape of the widget's own window.
60    #[serde(default)]
61    pub popout: PopoutShape,
62    /// Keeps the widget's own window above other windows.
63    #[serde(default)]
64    pub popout_on_top: bool,
65    /// Oldest Toolblox version the widget runs on, as SemVer.
66    #[serde(default)]
67    pub min_app_version: Option<String>,
68}
69
70/// Shape of a module widget's own window.
71#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
72#[serde(rename_all = "lowercase")]
73pub enum PopoutShape {
74    #[default]
75    Portrait,
76    Landscape,
77}
78
79/// An action a widget may be granted, named as in manifests.
80#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
81pub enum WidgetPermission {
82    #[serde(rename = "accounts.read.basic")]
83    AccountsReadBasic,
84    #[serde(rename = "widgetData.read")]
85    WidgetDataRead,
86    #[serde(rename = "widgetData.write")]
87    WidgetDataWrite,
88    #[serde(rename = "roblox.status")]
89    RobloxStatus,
90    #[serde(rename = "roblox.join")]
91    RobloxJoin,
92    #[serde(rename = "network.fetch")]
93    NetworkFetch,
94    #[serde(rename = "process.spawn")]
95    ProcessSpawn,
96}
97
98impl WidgetPermission {
99    /// Every permission. Module widgets run in the app window and receive all of them.
100    pub const ALL: [WidgetPermission; 7] = [
101        WidgetPermission::AccountsReadBasic,
102        WidgetPermission::WidgetDataRead,
103        WidgetPermission::WidgetDataWrite,
104        WidgetPermission::RobloxStatus,
105        WidgetPermission::RobloxJoin,
106        WidgetPermission::NetworkFetch,
107        WidgetPermission::ProcessSpawn,
108    ];
109}
110
111/// A process a widget declares.
112#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
113#[serde(rename_all = "camelCase")]
114pub struct WidgetProcess {
115    pub id: String,
116    /// Path under `optional-bin/` in the package.
117    pub executable: String,
118    /// The only arguments the process may be started with.
119    #[serde(default)]
120    pub allowed_arguments: Vec<String>,
121}
122
123/// The signed list of reviewed widgets.
124#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
125#[serde(rename_all = "camelCase")]
126pub struct Catalogue {
127    pub schema_version: u32,
128    /// Unix time the catalogue was generated.
129    pub generated_at: i64,
130    pub entries: Vec<CatalogueEntry>,
131}
132
133/// A widget listed in the catalogue.
134#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
135#[serde(rename_all = "camelCase")]
136pub struct CatalogueEntry {
137    pub id: String,
138    pub name: String,
139    pub version: String,
140    pub description: String,
141    /// HTTPS URL of the package ZIP.
142    pub archive_url: String,
143    /// Hex SHA-256 the downloaded package must match.
144    pub sha256: String,
145    /// Permissions the package's manifest must declare exactly.
146    #[serde(default)]
147    pub permissions: Vec<WidgetPermission>,
148    #[serde(default)]
149    pub icon_url: Option<String>,
150    #[serde(default)]
151    pub banner_url: Option<String>,
152    /// Oldest Toolblox version the widget runs on, copied from its manifest.
153    #[serde(default)]
154    pub min_app_version: Option<String>,
155}
156
157/// This build's version.
158pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
159
160/// Whether `app` is at least `minimum`. Pre-release labels are ignored, so `0.5.0` accepts
161/// `0.5.0-beta`. A missing minimum accepts every version, and an invalid one accepts none.
162fn meets_minimum(minimum: Option<&str>, app: &str) -> bool {
163    let Some(minimum) = minimum else {
164        return true;
165    };
166    let release = |version: &str| {
167        Version::parse(version)
168            .ok()
169            .map(|v| (v.major, v.minor, v.patch))
170    };
171    matches!((release(minimum), release(app)), (Some(minimum), Some(app)) if app >= minimum)
172}
173
174/// Whether this build runs a widget that needs `minimum`. Debug builds run unreleased code, so
175/// they accept every minimum.
176pub fn app_supports(minimum: Option<&str>) -> bool {
177    cfg!(debug_assertions) || meets_minimum(minimum, APP_VERSION)
178}
179
180/// The error for a widget that needs a newer Toolblox.
181pub fn needs_newer_app(name: &str, minimum: &str) -> String {
182    format!("{name} needs Toolblox {minimum} or later. Can you update Toolblox first?")
183}
184
185/// A widget installed on this device.
186#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
187#[serde(rename_all = "camelCase")]
188pub struct InstalledWidget {
189    pub id: String,
190    pub version: String,
191    /// SHA-256 of the package it was installed from.
192    pub sha256: String,
193    pub manifest: WidgetManifest,
194}
195
196/// Install record written to `.installed.json` beside the manifest.
197#[derive(Debug, Deserialize, Serialize)]
198#[serde(rename_all = "camelCase")]
199struct InstalledMetadata {
200    schema_version: u32,
201    id: String,
202    version: String,
203    sha256: String,
204    /// SHA-256 of `widget.json` at install time, to detect later edits.
205    manifest_sha256: String,
206}
207
208impl WidgetManifest {
209    /// Checks the schema version, ID, name, SemVer version, fixed entry file names, permissions,
210    /// network origins, and processes.
211    pub fn validate(&self) -> Result<(), String> {
212        if self.schema_version != 1 {
213            return Err("This widget uses an unsupported manifest version.".into());
214        }
215        validate_widget_id(&self.id)?;
216        if self.name.trim().is_empty() || self.name.chars().count() > 80 {
217            return Err("The widget name must contain between 1 and 80 characters.".into());
218        }
219        Version::parse(&self.version).map_err(|_| "The widget version isn't valid SemVer.")?;
220        if let Some(minimum) = &self.min_app_version {
221            Version::parse(minimum)
222                .map_err(|_| "The widget's minimum Toolblox version isn't valid SemVer.")?;
223        }
224        if self.entry.is_none() && self.module.is_none() {
225            return Err("The widget must declare an entry page or a module.".into());
226        }
227        if self
228            .entry
229            .as_deref()
230            .is_some_and(|entry| entry != "index.html")
231        {
232            return Err("The widget entry must be index.html.".into());
233        }
234        if self
235            .module
236            .as_deref()
237            .is_some_and(|module| module != "main.js")
238        {
239            return Err("The widget module must be main.js.".into());
240        }
241        if self
242            .settings_entry
243            .as_deref()
244            .is_some_and(|entry| entry != "settings.html")
245        {
246            return Err("The widget settings entry must be settings.html.".into());
247        }
248        if self
249            .dashboard_entry
250            .as_deref()
251            .is_some_and(|entry| entry != "dashboard.html")
252        {
253            return Err("The widget dashboard entry must be dashboard.html.".into());
254        }
255        let permissions: HashSet<_> = self.permissions.iter().collect();
256        if permissions.len() != self.permissions.len() {
257            return Err("The widget manifest contains duplicate permissions.".into());
258        }
259        for origin in &self.network_origins {
260            validate_https_origin(origin)?;
261        }
262        if !self.network_origins.is_empty()
263            && !permissions.contains(&WidgetPermission::NetworkFetch)
264        {
265            return Err(
266                "The widget declares network origins without network.fetch permission.".into(),
267            );
268        }
269        let mut process_ids = HashSet::new();
270        for process in &self.processes {
271            validate_process_id(&process.id)?;
272            validate_relative_file(&process.executable, "process executable")?;
273            if !process.executable.starts_with("optional-bin/") {
274                return Err("Widget processes must be located in optional-bin/.".into());
275            }
276            if !process_ids.insert(&process.id) {
277                return Err("The widget manifest contains duplicate process IDs.".into());
278            }
279        }
280        if !self.processes.is_empty() && !permissions.contains(&WidgetPermission::ProcessSpawn) {
281            return Err("The widget declares processes without process.spawn permission.".into());
282        }
283        Ok(())
284    }
285}
286
287impl Catalogue {
288    /// Verifies the catalogue signature, then parses it and validates each entry's ID, version,
289    /// checksum, permissions, and HTTPS archive URL.
290    pub fn parse_verified(
291        bytes: &[u8],
292        signature_base64: &str,
293        public_key_base64: &str,
294    ) -> Result<Self, String> {
295        verify_signature(bytes, signature_base64, public_key_base64)?;
296        let catalogue: Self = serde_json::from_slice(bytes)
297            .map_err(|_| "The widget catalogue isn't valid JSON.".to_string())?;
298        if catalogue.schema_version != 1 {
299            return Err("The widget catalogue version isn't supported.".into());
300        }
301        let mut ids = HashSet::new();
302        for entry in &catalogue.entries {
303            validate_widget_id(&entry.id)?;
304            Version::parse(&entry.version)
305                .map_err(|_| format!("Widget {} has an invalid version.", entry.id))?;
306            if let Some(minimum) = &entry.min_app_version {
307                Version::parse(minimum).map_err(|_| {
308                    format!(
309                        "Widget {} has an invalid minimum Toolblox version.",
310                        entry.id
311                    )
312                })?;
313            }
314            validate_sha256(&entry.sha256)?;
315            let permissions: HashSet<_> = entry.permissions.iter().collect();
316            if permissions.len() != entry.permissions.len() {
317                return Err(format!(
318                    "Widget {} has duplicate catalogue permissions.",
319                    entry.id
320                ));
321            }
322            let url = Url::parse(&entry.archive_url)
323                .map_err(|_| format!("Widget {} has an invalid archive URL.", entry.id))?;
324            if url.scheme() != "https" || url.host_str().is_none() {
325                return Err(format!(
326                    "Widget {} must use an HTTPS archive URL.",
327                    entry.id
328                ));
329            }
330            if !ids.insert(&entry.id) {
331                return Err(format!(
332                    "The catalogue contains widget {} more than once.",
333                    entry.id
334                ));
335            }
336        }
337        Ok(catalogue)
338    }
339}
340
341/// Installs a widget package, replacing any installed version only after every check passes.
342///
343/// Checks the size and SHA-256, extracts into a staging folder with path, count, size, and
344/// symlink limits, requires the manifest's ID, version, and permissions to match the catalogue,
345/// and requires every declared file to exist. The previous version is restored if the swap fails.
346pub fn install_archive(
347    archive: &[u8],
348    expected_id: &str,
349    expected_version: &str,
350    expected_sha256: &str,
351    expected_permissions: &[WidgetPermission],
352    widgets_root: &Path,
353) -> Result<InstalledWidget, String> {
354    validate_widget_id(expected_id)?;
355    validate_sha256(expected_sha256)?;
356    if archive.len() > MAX_ARCHIVE_BYTES {
357        return Err("The widget package is larger than 20 MB.".into());
358    }
359    let actual_sha256 = hex::encode(Sha256::digest(archive));
360    if !actual_sha256.eq_ignore_ascii_case(expected_sha256) {
361        return Err("The widget package checksum doesn't match the catalogue.".into());
362    }
363
364    fs::create_dir_all(widgets_root)
365        .map_err(|_| "Couldn't create the widget directory. Is it writable?".to_string())?;
366    let nonce = Uuid::new_v4();
367    let staging = widgets_root.join(format!(".{expected_id}-install-{nonce}"));
368    let backup = widgets_root.join(format!(".{expected_id}-backup-{nonce}"));
369    let destination = widgets_root.join(expected_id);
370    fs::create_dir(&staging)
371        .map_err(|_| "Couldn't create the widget staging directory. Is it writable?".to_string())?;
372
373    let result = extract_archive(archive, &staging).and_then(|_| {
374        let manifest = read_manifest(&staging)?;
375        if manifest.id != expected_id {
376            return Err("The widget package ID doesn't match the catalogue.".into());
377        }
378        if manifest.version != expected_version {
379            return Err("The widget package version doesn't match the catalogue.".into());
380        }
381        if let Some(minimum) = manifest
382            .min_app_version
383            .as_deref()
384            .filter(|minimum| !app_supports(Some(minimum)))
385        {
386            return Err(needs_newer_app(&manifest.name, minimum));
387        }
388        if manifest.permissions.iter().collect::<HashSet<_>>()
389            != expected_permissions.iter().collect::<HashSet<_>>()
390        {
391            return Err("The widget permissions don't match the catalogue.".into());
392        }
393        for entry in [
394            manifest.entry.as_deref(),
395            manifest.module.as_deref(),
396            manifest.settings_entry.as_deref(),
397            manifest.dashboard_entry.as_deref(),
398        ]
399        .into_iter()
400        .flatten()
401        {
402            if !staging.join(entry).is_file() {
403                return Err(format!("The widget package doesn't contain {entry}."));
404            }
405        }
406        for process in &manifest.processes {
407            if !staging.join(&process.executable).is_file() {
408                return Err(format!("Widget process {} is missing.", process.id));
409            }
410        }
411        write_installed_metadata(&staging, &manifest, &actual_sha256)?;
412        replace_atomically(&staging, &destination, &backup)?;
413        Ok(InstalledWidget {
414            id: manifest.id.clone(),
415            version: manifest.version.clone(),
416            sha256: actual_sha256,
417            manifest,
418        })
419    });
420
421    if staging.exists() {
422        let _ = fs::remove_dir_all(&staging);
423    }
424    if result.is_ok() && backup.exists() {
425        let _ = fs::remove_dir_all(&backup);
426    }
427    result
428}
429
430/// Reads every installed widget, sorted by ID. Hidden folders, such as staging folders, are
431/// skipped, and each unreadable widget yields an error.
432pub fn discover_installed(widgets_root: &Path) -> Vec<Result<InstalledWidget, String>> {
433    let Ok(entries) = fs::read_dir(widgets_root) else {
434        return Vec::new();
435    };
436    let mut found = Vec::new();
437    for entry in entries.flatten() {
438        let name = entry.file_name().to_string_lossy().into_owned();
439        if name.starts_with('.') || !entry.path().is_dir() {
440            continue;
441        }
442        found.push(
443            read_installed(&entry.path())
444                .map_err(|error| format!("Widget {name} couldn't load: {error}")),
445        );
446    }
447    found.sort_by(|left, right| {
448        let left_id = left.as_ref().map(|widget| widget.id.as_str()).unwrap_or("");
449        let right_id = right
450            .as_ref()
451            .map(|widget| widget.id.as_str())
452            .unwrap_or("");
453        left_id.cmp(right_id)
454    });
455    found
456}
457
458/// The Hello, world! example widget, compiled into development builds only.
459#[cfg(debug_assertions)]
460const EXAMPLE_WIDGET: [(&str, &[u8]); 4] = [
461    (
462        "widget.json",
463        include_bytes!("../../examples/hello_world/widget.json"),
464    ),
465    (
466        "main.js",
467        include_bytes!("../../examples/hello_world/main.js"),
468    ),
469    (
470        "banner.gif",
471        include_bytes!("../../examples/hello_world/banner.gif"),
472    ),
473    (
474        "LICENSE",
475        include_bytes!("../../examples/hello_world/LICENSE"),
476    ),
477];
478
479/// Adds the example widget to the widgets folder once. A hidden marker file records that it was
480/// added, so an uninstalled example stays uninstalled and an edited copy is never replaced.
481/// Development builds only.
482#[cfg(debug_assertions)]
483pub fn add_example_widget(widgets_root: &Path) -> Result<(), String> {
484    let marker = widgets_root.join(".example-added");
485    let target = widgets_root.join("hello_world");
486    if marker.exists() {
487        return Ok(());
488    }
489    if !target.exists() {
490        fs::create_dir_all(&target)
491            .map_err(|_| "Couldn't create the example widget folder.".to_string())?;
492        for (name, contents) in EXAMPLE_WIDGET {
493            fs::write(target.join(name), contents)
494                .map_err(|_| format!("Couldn't write the example widget's {name}."))?;
495        }
496    }
497    fs::write(marker, "").map_err(|_| "Couldn't record the example widget.".to_string())
498}
499
500/// The working tree's `widgets/` and `examples/` folders, which development builds list as
501/// their catalogue.
502#[cfg(debug_assertions)]
503pub const LOCAL_CATALOGUE: [&str; 2] = [
504    concat!(env!("CARGO_MANIFEST_DIR"), "/../widgets"),
505    concat!(env!("CARGO_MANIFEST_DIR"), "/../examples"),
506];
507
508/// Builds an unsigned catalogue from the widget folders in `roots`, packaging each one in memory
509/// so installs run the same checks as catalogue packages. Missing folders list no widgets.
510/// Development builds only.
511#[cfg(debug_assertions)]
512pub fn local_catalogue(roots: &[&Path]) -> Result<Catalogue, String> {
513    let mut folders: Vec<_> = roots
514        .iter()
515        .filter_map(|root| fs::read_dir(root).ok())
516        .flat_map(|entries| entries.flatten())
517        .filter(|entry| {
518            entry.path().is_dir() && !entry.file_name().to_string_lossy().starts_with('.')
519        })
520        .map(|entry| entry.path())
521        .collect();
522    folders.sort();
523    let mut entries: Vec<CatalogueEntry> = Vec::new();
524    for folder in folders {
525        let name = folder
526            .file_name()
527            .unwrap_or_default()
528            .to_string_lossy()
529            .into_owned();
530        let manifest = read_manifest(&folder).map_err(|error| format!("Widget {name}: {error}"))?;
531        if manifest.id != name {
532            return Err(format!(
533                "Widget {name}: the manifest ID must match its folder name."
534            ));
535        }
536        if entries.iter().any(|entry| entry.id == name) {
537            return Err(format!(
538                "The catalogue contains widget {name} more than once."
539            ));
540        }
541        let archive = package_folder(&folder)?;
542        let icon_url = local_image_url(&folder, manifest.icon.as_deref());
543        let banner_url = local_image_url(&folder, manifest.banner.as_deref());
544        entries.push(CatalogueEntry {
545            id: manifest.id,
546            name: manifest.name,
547            version: manifest.version,
548            description: manifest.description,
549            archive_url: Url::from_directory_path(&folder)
550                .map_err(|_| format!("Widget {name}: the folder path isn't absolute."))?
551                .to_string(),
552            sha256: hex::encode(Sha256::digest(&archive)),
553            permissions: manifest.permissions,
554            icon_url,
555            banner_url,
556            min_app_version: manifest.min_app_version,
557        });
558    }
559    Ok(Catalogue {
560        schema_version: 1,
561        generated_at: 0,
562        entries,
563    })
564}
565
566/// A `data:` URL for an image inside a widget folder, or `None` when the path leaves the folder,
567/// isn't a supported image type, or can't be read. Development builds only.
568#[cfg(debug_assertions)]
569fn local_image_url(folder: &Path, path: Option<&str>) -> Option<String> {
570    let path = path?;
571    validate_relative_file(path, "image").ok()?;
572    let file = folder.join(path).canonicalize().ok()?;
573    if !file.starts_with(folder.canonicalize().ok()?) {
574        return None;
575    }
576    let content_type = match file.extension()?.to_str()? {
577        "svg" => "image/svg+xml",
578        "png" => "image/png",
579        "jpg" | "jpeg" => "image/jpeg",
580        "gif" => "image/gif",
581        "webp" => "image/webp",
582        _ => return None,
583    };
584    let bytes = fs::read(&file).ok()?;
585    let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
586    Some(format!("data:{content_type};base64,{encoded}"))
587}
588
589/// Packages a widget folder as a ZIP, skipping hidden files and rejecting symbolic links.
590/// Development builds only.
591#[cfg(debug_assertions)]
592pub fn package_folder(folder: &Path) -> Result<Vec<u8>, String> {
593    fn collect(folder: &Path, files: &mut Vec<std::path::PathBuf>) -> Result<(), String> {
594        let entries =
595            fs::read_dir(folder).map_err(|_| "Couldn't read a widget folder.".to_string())?;
596        for entry in entries.flatten() {
597            if entry.file_name().to_string_lossy().starts_with('.') {
598                continue;
599            }
600            let kind = entry
601                .file_type()
602                .map_err(|_| "Couldn't read a widget file.".to_string())?;
603            if kind.is_symlink() {
604                return Err("The widget folder contains a symbolic link.".into());
605            }
606            if kind.is_dir() {
607                collect(&entry.path(), files)?;
608            } else {
609                files.push(entry.path());
610            }
611        }
612        Ok(())
613    }
614    let mut files = Vec::new();
615    collect(folder, &mut files)?;
616    files.sort();
617    let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
618    for file in files {
619        let name = file
620            .strip_prefix(folder)
621            .map_err(|_| "Couldn't read a widget file.".to_string())?
622            .to_string_lossy()
623            .replace('\\', "/");
624        let options = zip::write::SimpleFileOptions::default()
625            .compression_method(zip::CompressionMethod::Deflated);
626        #[cfg(unix)]
627        let options = {
628            use std::os::unix::fs::PermissionsExt;
629            let mode = fs::metadata(&file)
630                .map_err(|_| "Couldn't read a widget file.".to_string())?
631                .permissions()
632                .mode();
633            options.unix_permissions(mode & 0o777)
634        };
635        zip.start_file(name, options)
636            .and_then(|()| {
637                fs::read(&file)
638                    .and_then(|bytes| zip.write_all(&bytes))
639                    .map_err(Into::into)
640            })
641            .map_err(|_| "Couldn't package a widget file.".to_string())?;
642    }
643    zip.finish()
644        .map(Cursor::into_inner)
645        .map_err(|_| "Couldn't package the widget.".to_string())
646}
647
648/// A cheap fingerprint of a folder's files: their paths, sizes, and modification times, skipping
649/// hidden ones. Development builds only.
650#[cfg(debug_assertions)]
651pub fn folder_fingerprint(folder: &Path) -> u64 {
652    use std::hash::{DefaultHasher, Hash, Hasher};
653    fn visit(folder: &Path, hasher: &mut DefaultHasher) {
654        let Ok(entries) = fs::read_dir(folder) else {
655            return;
656        };
657        let mut entries: Vec<_> = entries
658            .flatten()
659            .filter(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
660            .collect();
661        entries.sort_by_key(|entry| entry.file_name());
662        for entry in entries {
663            entry.file_name().hash(hasher);
664            let Ok(metadata) = entry.metadata() else {
665                continue;
666            };
667            if metadata.is_dir() {
668                visit(&entry.path(), hasher);
669            } else {
670                metadata.len().hash(hasher);
671                metadata.modified().ok().hash(hasher);
672            }
673        }
674    }
675    let mut hasher = DefaultHasher::new();
676    visit(folder, &mut hasher);
677    hasher.finish()
678}
679
680/// Packages a working-tree widget folder and installs it, with the same checks as a catalogue
681/// package, when the package differs from `installed_sha256`. Calls `before_install` first.
682/// Returns whether it installed. Development builds only.
683#[cfg(debug_assertions)]
684pub fn reinstall_from_folder(
685    folder: &Path,
686    installed_sha256: &str,
687    widgets_root: &Path,
688    before_install: impl FnOnce(),
689) -> Result<bool, String> {
690    let manifest = read_manifest(folder)?;
691    let archive = package_folder(folder)?;
692    let sha256 = hex::encode(Sha256::digest(&archive));
693    if sha256 == installed_sha256 {
694        return Ok(false);
695    }
696    before_install();
697    install_archive(
698        &archive,
699        &manifest.id,
700        &manifest.version,
701        &sha256,
702        &manifest.permissions,
703        widgets_root,
704    )?;
705    Ok(true)
706}
707
708/// Removes an installed widget's folder. A missing widget succeeds.
709pub fn uninstall_widget(widget_id: &str, widgets_root: &Path) -> Result<(), String> {
710    validate_widget_id(widget_id)?;
711    let target = widgets_root.join(widget_id);
712    if !target.exists() {
713        return Ok(());
714    }
715    fs::remove_dir_all(target)
716        .map_err(|_| "Couldn't remove the widget. Is a widget process still running?".to_string())
717}
718
719/// Extracts a ZIP into `staging`, rejecting unsafe or duplicate paths, symlinks, too many
720/// entries, and oversized content.
721fn extract_archive(archive: &[u8], staging: &Path) -> Result<(), String> {
722    let mut zip = ZipArchive::new(Cursor::new(archive))
723        .map_err(|_| "The widget package isn't a valid ZIP archive.".to_string())?;
724    if zip.len() > MAX_FILES {
725        return Err("The widget package contains too many files.".into());
726    }
727    let mut names = HashSet::new();
728    let mut expanded = 0_u64;
729    for index in 0..zip.len() {
730        let mut item = zip
731            .by_index(index)
732            .map_err(|_| "Couldn't read the widget package.".to_string())?;
733        let enclosed = item
734            .enclosed_name()
735            .ok_or_else(|| "The widget package contains an unsafe path.".to_string())?
736            .to_path_buf();
737        validate_archive_path(&enclosed)?;
738        let normalized = enclosed.to_string_lossy().replace('\\', "/");
739        if !names.insert(normalized) {
740            return Err("The widget package contains duplicate paths.".into());
741        }
742        if item
743            .unix_mode()
744            .is_some_and(|mode| mode & 0o170000 == 0o120000)
745        {
746            return Err("The widget package contains a symbolic link.".into());
747        }
748        expanded = expanded
749            .checked_add(item.size())
750            .ok_or_else(|| "The widget package is too large when extracted.".to_string())?;
751        if expanded > MAX_EXPANDED_BYTES {
752            return Err("The widget package is too large when extracted.".into());
753        }
754        let output = staging.join(&enclosed);
755        if item.is_dir() {
756            fs::create_dir_all(&output)
757                .map_err(|_| "Couldn't create a widget package directory.".to_string())?;
758            continue;
759        }
760        if let Some(parent) = output.parent() {
761            fs::create_dir_all(parent)
762                .map_err(|_| "Couldn't create a widget package directory.".to_string())?;
763        }
764        let mut file = File::create(&output)
765            .map_err(|_| "Couldn't create a widget package file.".to_string())?;
766        std::io::copy(&mut item, &mut file)
767            .map_err(|_| "Couldn't extract the widget package.".to_string())?;
768        file.sync_all()
769            .map_err(|_| "Couldn't save the widget package.".to_string())?;
770        #[cfg(unix)]
771        if let Some(mode) = item.unix_mode() {
772            use std::os::unix::fs::PermissionsExt;
773
774            fs::set_permissions(&output, fs::Permissions::from_mode(mode & 0o777))
775                .map_err(|_| "Couldn't set widget package permissions.".to_string())?;
776        }
777    }
778    Ok(())
779}
780
781/// Reads and validates `widget.json`, which may be at most 128 KB.
782fn read_manifest(root: &Path) -> Result<WidgetManifest, String> {
783    let bytes = fs::read(root.join("widget.json"))
784        .map_err(|_| "The widget package doesn't contain widget.json.".to_string())?;
785    if bytes.len() > 128 * 1024 {
786        return Err("The widget manifest is too large.".into());
787    }
788    let manifest: WidgetManifest = serde_json::from_slice(&bytes)
789        .map_err(|_| "The widget manifest isn't valid JSON.".to_string())?;
790    manifest.validate()?;
791    Ok(manifest)
792}
793
794/// Reads an installed widget and checks its install record, including that `widget.json`
795/// hasn't changed since install. Debug builds accept widgets without a record.
796fn read_installed(root: &Path) -> Result<InstalledWidget, String> {
797    let manifest = read_manifest(root)?;
798    let metadata_bytes = match fs::read(root.join(".installed.json")) {
799        Ok(bytes) => bytes,
800        Err(_) if cfg!(debug_assertions) => {
801            return Ok(InstalledWidget {
802                id: manifest.id.clone(),
803                version: manifest.version.clone(),
804                sha256: "0".repeat(64),
805                manifest,
806            });
807        }
808        Err(_) => {
809            return Err(format!(
810                "Widget {} is missing install metadata.",
811                manifest.id
812            ));
813        }
814    };
815    let metadata: InstalledMetadata = serde_json::from_slice(&metadata_bytes)
816        .map_err(|_| format!("Widget {} has invalid install metadata.", manifest.id))?;
817    if metadata.schema_version != 1
818        || metadata.id != manifest.id
819        || metadata.version != manifest.version
820    {
821        return Err(format!(
822            "Widget {} has inconsistent install metadata.",
823            manifest.id
824        ));
825    }
826    validate_sha256(&metadata.sha256)?;
827    validate_sha256(&metadata.manifest_sha256)?;
828    let manifest_bytes = fs::read(root.join("widget.json"))
829        .map_err(|_| format!("Widget {} is missing widget.json.", manifest.id))?;
830    if hex::encode(Sha256::digest(&manifest_bytes)) != metadata.manifest_sha256 {
831        return Err(format!(
832            "Widget {} has a modified manifest. Can you reinstall it from the catalogue?",
833            manifest.id
834        ));
835    }
836    Ok(InstalledWidget {
837        id: manifest.id.clone(),
838        version: manifest.version.clone(),
839        sha256: metadata.sha256,
840        manifest,
841    })
842}
843
844/// Writes `.installed.json` for a staged widget.
845fn write_installed_metadata(
846    root: &Path,
847    manifest: &WidgetManifest,
848    sha256: &str,
849) -> Result<(), String> {
850    let metadata = InstalledMetadata {
851        schema_version: 1,
852        id: manifest.id.clone(),
853        version: manifest.version.clone(),
854        sha256: sha256.to_owned(),
855        manifest_sha256: hex::encode(Sha256::digest(
856            fs::read(root.join("widget.json"))
857                .map_err(|_| "Couldn't read widget.json after installation.".to_string())?,
858        )),
859    };
860    let bytes = serde_json::to_vec_pretty(&metadata)
861        .map_err(|_| "Couldn't encode widget install metadata.".to_string())?;
862    let path = root.join(".installed.json");
863    let mut file =
864        File::create(path).map_err(|_| "Couldn't create widget install metadata.".to_string())?;
865    file.write_all(&bytes)
866        .and_then(|_| file.sync_all())
867        .map_err(|_| "Couldn't save widget install metadata.".to_string())
868}
869
870/// Moves `staging` to `destination`, keeping the old folder in `backup` and restoring it if
871/// the move fails.
872fn replace_atomically(staging: &Path, destination: &Path, backup: &Path) -> Result<(), String> {
873    if destination.exists() {
874        fs::rename(destination, backup)
875            .map_err(|_| "Couldn't prepare the installed widget for replacement.".to_string())?;
876    }
877    if let Err(error) = fs::rename(staging, destination) {
878        if backup.exists() {
879            let _ = fs::rename(backup, destination);
880        }
881        return Err(format!("Couldn't activate the widget package: {error}"));
882    }
883    Ok(())
884}
885
886/// Verifies a base64 Ed25519 signature with a base64 raw 32-byte public key.
887fn verify_signature(
888    bytes: &[u8],
889    signature_base64: &str,
890    public_key_base64: &str,
891) -> Result<(), String> {
892    let decoder = base64::engine::general_purpose::STANDARD;
893    let key_bytes = decoder
894        .decode(public_key_base64)
895        .map_err(|_| "The catalogue public key isn't valid.".to_string())?;
896    let signature_bytes = decoder
897        .decode(signature_base64)
898        .map_err(|_| "The catalogue signature isn't valid.".to_string())?;
899    let key_array: [u8; 32] = key_bytes
900        .try_into()
901        .map_err(|_| "The catalogue public key has the wrong length.".to_string())?;
902    let signature = Signature::from_slice(&signature_bytes)
903        .map_err(|_| "The catalogue signature has the wrong length.".to_string())?;
904    let key = VerifyingKey::from_bytes(&key_array)
905        .map_err(|_| "The catalogue public key isn't valid.".to_string())?;
906    key.verify(bytes, &signature)
907        .map_err(|_| "The widget catalogue signature couldn't be verified.".to_string())
908}
909
910/// Accepts IDs of 1 to 64 lowercase letters, digits, and underscores.
911pub(crate) fn validate_widget_id(value: &str) -> Result<(), String> {
912    if value.is_empty()
913        || value.len() > 64
914        || !value
915            .bytes()
916            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
917    {
918        return Err(
919            "Widget IDs may contain only lowercase letters, numbers, and underscores.".into(),
920        );
921    }
922    Ok(())
923}
924
925/// Accepts IDs of 1 to 64 ASCII letters, digits, `_`, and `-`.
926fn validate_process_id(value: &str) -> Result<(), String> {
927    if value.is_empty()
928        || value.len() > 64
929        || !value
930            .bytes()
931            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
932    {
933        return Err("Widget process IDs contain unsupported characters.".into());
934    }
935    Ok(())
936}
937
938/// Requires a non-empty relative path that doesn't leave the package.
939fn validate_relative_file(value: &str, label: &str) -> Result<(), String> {
940    let path = Path::new(value);
941    if value.is_empty()
942        || path.is_absolute()
943        || path.components().any(|part| {
944            matches!(
945                part,
946                Component::ParentDir | Component::RootDir | Component::Prefix(_)
947            )
948        })
949    {
950        return Err(format!("The widget {label} path isn't safe."));
951    }
952    Ok(())
953}
954
955/// Rejects archive paths with parent, root, or drive components.
956fn validate_archive_path(path: &Path) -> Result<(), String> {
957    if path.components().any(|part| {
958        matches!(
959            part,
960            Component::ParentDir | Component::RootDir | Component::Prefix(_)
961        )
962    }) {
963        return Err("The widget package contains an unsafe path.".into());
964    }
965    Ok(())
966}
967
968/// Accepts bare HTTPS origins, such as `https://example.com`, without a path, query, or
969/// credentials.
970fn validate_https_origin(value: &str) -> Result<(), String> {
971    let url = Url::parse(value).map_err(|_| "A widget network origin isn't valid.".to_string())?;
972    if url.scheme() != "https"
973        || url.host_str().is_none()
974        || url.path() != "/"
975        || url.query().is_some()
976        || url.fragment().is_some()
977        || !url.username().is_empty()
978        || url.password().is_some()
979    {
980        return Err("Widget network origins must be bare HTTPS origins.".into());
981    }
982    Ok(())
983}
984
985/// Requires 64 hex characters.
986fn validate_sha256(value: &str) -> Result<(), String> {
987    if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
988        return Err("A widget checksum isn't a valid SHA-256 value.".into());
989    }
990    Ok(())
991}
992
993#[cfg(test)]
994mod tests {
995    use super::*;
996    use ed25519_dalek::{Signer, SigningKey};
997    use std::io::Write;
998    use tempfile::tempdir;
999    use zip::write::SimpleFileOptions;
1000
1001    fn manifest() -> WidgetManifest {
1002        WidgetManifest {
1003            schema_version: 1,
1004            id: "example_widget".into(),
1005            name: "Example Widget".into(),
1006            version: "1.0.0".into(),
1007            entry: Some("index.html".into()),
1008            module: None,
1009            settings_entry: None,
1010            dashboard_entry: None,
1011            description: String::new(),
1012            icon: None,
1013            banner: None,
1014            permissions: vec![WidgetPermission::WidgetDataRead],
1015            network_origins: Vec::new(),
1016            processes: Vec::new(),
1017            popout: PopoutShape::Portrait,
1018            popout_on_top: false,
1019            min_app_version: None,
1020        }
1021    }
1022
1023    #[test]
1024    fn minimum_app_version_ignores_pre_release_labels() {
1025        assert!(meets_minimum(None, "0.4.5-beta"));
1026        assert!(meets_minimum(Some("0.4.5"), "0.4.5-beta"));
1027        assert!(meets_minimum(Some("0.4.5-beta"), "0.4.6-beta"));
1028        assert!(meets_minimum(Some("0.4.6"), "1.0.0"));
1029        assert!(!meets_minimum(Some("0.4.6"), "0.4.5-beta"));
1030        assert!(!meets_minimum(Some("0.5.0"), "0.4.9"));
1031        assert!(!meets_minimum(Some("not a version"), "0.4.5"));
1032    }
1033
1034    #[test]
1035    fn manifest_rejects_an_invalid_minimum_app_version() {
1036        let mut value = manifest();
1037        value.min_app_version = Some("0.4.6".into());
1038        assert!(value.validate().is_ok());
1039        value.min_app_version = Some("next".into());
1040        assert!(value.validate().is_err());
1041    }
1042
1043    #[test]
1044    fn manifest_popout_defaults_to_portrait_and_rejects_unknown_shapes() {
1045        let mut value = serde_json::to_value(manifest()).unwrap();
1046        value.as_object_mut().unwrap().remove("popout");
1047        let parsed: WidgetManifest = serde_json::from_value(value.clone()).unwrap();
1048        assert_eq!(parsed.popout, PopoutShape::Portrait);
1049        value["popout"] = "landscape".into();
1050        let parsed: WidgetManifest = serde_json::from_value(value.clone()).unwrap();
1051        assert_eq!(parsed.popout, PopoutShape::Landscape);
1052        value["popout"] = "square".into();
1053        assert!(serde_json::from_value::<WidgetManifest>(value).is_err());
1054    }
1055
1056    #[test]
1057    fn manifest_needs_a_page_or_a_module_with_fixed_names() {
1058        let mut module_only = manifest();
1059        module_only.entry = None;
1060        module_only.module = Some("main.js".into());
1061        assert!(module_only.validate().is_ok());
1062        let mut neither = module_only.clone();
1063        neither.module = None;
1064        assert!(neither.validate().is_err());
1065        let mut renamed = module_only.clone();
1066        renamed.module = Some("../main.js".into());
1067        assert!(renamed.validate().is_err());
1068    }
1069
1070    fn archive(files: &[(&str, &[u8])]) -> Vec<u8> {
1071        let cursor = Cursor::new(Vec::new());
1072        let mut writer = zip::ZipWriter::new(cursor);
1073        for (name, contents) in files {
1074            writer
1075                .start_file(*name, SimpleFileOptions::default())
1076                .unwrap();
1077            writer.write_all(contents).unwrap();
1078        }
1079        writer.finish().unwrap().into_inner()
1080    }
1081
1082    #[test]
1083    fn manifest_rejects_undeclared_network_access() {
1084        let mut value = manifest();
1085        value.network_origins = vec!["https://example.com".into()];
1086        assert!(value.validate().is_err());
1087    }
1088
1089    #[test]
1090    fn signed_catalogue_requires_exact_bytes() {
1091        let signing_key = SigningKey::from_bytes(&[7_u8; 32]);
1092        let bytes = br#"{"schemaVersion":1,"generatedAt":1,"entries":[]}"#;
1093        let signature = signing_key.sign(bytes);
1094        let encoder = base64::engine::general_purpose::STANDARD;
1095        let parsed = Catalogue::parse_verified(
1096            bytes,
1097            &encoder.encode(signature.to_bytes()),
1098            &encoder.encode(signing_key.verifying_key().to_bytes()),
1099        );
1100        assert!(parsed.is_ok());
1101        assert!(
1102            Catalogue::parse_verified(
1103                b"{}",
1104                &encoder.encode(signature.to_bytes()),
1105                &encoder.encode(signing_key.verifying_key().to_bytes()),
1106            )
1107            .is_err()
1108        );
1109    }
1110
1111    #[test]
1112    fn install_verifies_then_replaces() {
1113        let root = tempdir().unwrap();
1114        let manifest_bytes = serde_json::to_vec(&manifest()).unwrap();
1115        let bytes = archive(&[
1116            ("widget.json", &manifest_bytes),
1117            ("index.html", b"<main>Example</main>"),
1118        ]);
1119        let checksum = hex::encode(Sha256::digest(&bytes));
1120        let installed = install_archive(
1121            &bytes,
1122            "example_widget",
1123            "1.0.0",
1124            &checksum,
1125            &[WidgetPermission::WidgetDataRead],
1126            root.path(),
1127        )
1128        .unwrap();
1129        assert_eq!(installed.version, "1.0.0");
1130        assert!(root.path().join("example_widget/index.html").is_file());
1131    }
1132
1133    #[test]
1134    fn install_rejects_checksum_mismatch_before_extraction() {
1135        let root = tempdir().unwrap();
1136        let error = install_archive(
1137            &[],
1138            "example_widget",
1139            "1.0.0",
1140            &"0".repeat(64),
1141            &[],
1142            root.path(),
1143        )
1144        .unwrap_err();
1145        assert!(error.contains("checksum"));
1146        assert!(!root.path().join("example_widget").exists());
1147    }
1148
1149    #[test]
1150    fn install_rejects_manifest_version_mismatch() {
1151        let root = tempdir().unwrap();
1152        let manifest_bytes = serde_json::to_vec(&manifest()).unwrap();
1153        let bytes = archive(&[
1154            ("widget.json", &manifest_bytes),
1155            ("index.html", b"<main>Example</main>"),
1156        ]);
1157        let checksum = hex::encode(Sha256::digest(&bytes));
1158        let error = install_archive(
1159            &bytes,
1160            "example_widget",
1161            "2.0.0",
1162            &checksum,
1163            &[WidgetPermission::WidgetDataRead],
1164            root.path(),
1165        )
1166        .unwrap_err();
1167        assert!(error.contains("version"));
1168        assert!(!root.path().join("example_widget").exists());
1169    }
1170
1171    #[cfg(debug_assertions)]
1172    #[test]
1173    fn local_image_url_stays_inside_the_widget_folder() {
1174        let root = tempdir().unwrap();
1175        let folder = root.path().join("widget");
1176        fs::create_dir(&folder).unwrap();
1177        fs::write(folder.join("banner.png"), b"png").unwrap();
1178        fs::write(folder.join("notes.txt"), b"text").unwrap();
1179        fs::write(root.path().join("outside.png"), b"png").unwrap();
1180        assert_eq!(
1181            local_image_url(&folder, Some("banner.png")).as_deref(),
1182            Some("data:image/png;base64,cG5n")
1183        );
1184        assert_eq!(local_image_url(&folder, Some("../outside.png")), None);
1185        assert_eq!(local_image_url(&folder, Some("notes.txt")), None);
1186        assert_eq!(local_image_url(&folder, Some("missing.png")), None);
1187        assert_eq!(local_image_url(&folder, None), None);
1188    }
1189
1190    #[cfg(debug_assertions)]
1191    #[test]
1192    fn local_catalogue_packages_install_with_catalogue_checks() {
1193        let root = tempdir().unwrap();
1194        add_example_widget(root.path()).unwrap();
1195        let catalogue = local_catalogue(&[root.path()]).unwrap();
1196        let entry = &catalogue.entries[0];
1197        assert_eq!(entry.id, "hello_world");
1198        assert!(
1199            entry
1200                .banner_url
1201                .as_deref()
1202                .is_some_and(|url| url.starts_with("data:image/gif;base64,"))
1203        );
1204        let folder = Url::parse(&entry.archive_url)
1205            .unwrap()
1206            .to_file_path()
1207            .unwrap();
1208        let archive = package_folder(&folder).unwrap();
1209        let installed = tempdir().unwrap();
1210        install_archive(
1211            &archive,
1212            &entry.id,
1213            &entry.version,
1214            &entry.sha256,
1215            &entry.permissions,
1216            installed.path(),
1217        )
1218        .unwrap();
1219        assert!(discover_installed(installed.path())[0].is_ok());
1220
1221        fs::rename(root.path().join("hello_world"), root.path().join("renamed")).unwrap();
1222        assert!(
1223            local_catalogue(&[root.path()])
1224                .unwrap_err()
1225                .contains("folder name")
1226        );
1227        assert!(
1228            local_catalogue(&[&root.path().join("missing")])
1229                .unwrap()
1230                .entries
1231                .is_empty()
1232        );
1233    }
1234
1235    #[cfg(debug_assertions)]
1236    #[test]
1237    fn example_widget_is_added_once_and_never_replaces_an_edited_copy() {
1238        let root = tempdir().unwrap();
1239        add_example_widget(root.path()).unwrap();
1240        let installed = discover_installed(root.path());
1241        assert_eq!(
1242            installed.len(),
1243            1,
1244            "the marker file is hidden from discovery"
1245        );
1246        assert_eq!(installed[0].as_ref().unwrap().id, "hello_world");
1247
1248        let module = root.path().join("hello_world/main.js");
1249        fs::write(&module, "export function activate() {}").unwrap();
1250        fs::remove_file(root.path().join(".example-added")).unwrap();
1251        add_example_widget(root.path()).unwrap();
1252        assert_eq!(
1253            fs::read_to_string(module).unwrap(),
1254            "export function activate() {}"
1255        );
1256
1257        uninstall_widget("hello_world", root.path()).unwrap();
1258        add_example_widget(root.path()).unwrap();
1259        assert!(!root.path().join("hello_world").exists());
1260    }
1261
1262    #[test]
1263    fn discovery_rejects_a_modified_installed_manifest() {
1264        let root = tempdir().unwrap();
1265        let manifest_bytes = serde_json::to_vec(&manifest()).unwrap();
1266        let bytes = archive(&[
1267            ("widget.json", &manifest_bytes),
1268            ("index.html", b"<main>Example</main>"),
1269        ]);
1270        let checksum = hex::encode(Sha256::digest(&bytes));
1271        install_archive(
1272            &bytes,
1273            "example_widget",
1274            "1.0.0",
1275            &checksum,
1276            &[WidgetPermission::WidgetDataRead],
1277            root.path(),
1278        )
1279        .unwrap();
1280        let mut changed = manifest();
1281        changed.name = "Changed".into();
1282        fs::write(
1283            root.path().join("example_widget/widget.json"),
1284            serde_json::to_vec(&changed).unwrap(),
1285        )
1286        .unwrap();
1287        let error = discover_installed(root.path()).remove(0).unwrap_err();
1288        assert!(error.contains("modified manifest"));
1289    }
1290
1291    #[cfg(debug_assertions)]
1292    #[test]
1293    fn working_tree_changes_reinstall_only_when_the_package_differs() {
1294        let source = tempfile::tempdir().unwrap();
1295        let installed = tempfile::tempdir().unwrap();
1296        let folder = source.path().join("sample");
1297        fs::create_dir_all(&folder).unwrap();
1298        fs::write(
1299            folder.join("widget.json"),
1300            r#"{"schemaVersion":1,"id":"sample","name":"Sample","version":"1.0.0","module":"main.js"}"#,
1301        )
1302        .unwrap();
1303        fs::write(folder.join("main.js"), "export function activate() {}").unwrap();
1304        let before = folder_fingerprint(&folder);
1305        assert!(reinstall_from_folder(&folder, "", installed.path(), || {}).unwrap());
1306        let sha256 = discover_installed(installed.path())[0]
1307            .as_ref()
1308            .unwrap()
1309            .sha256
1310            .clone();
1311        assert!(!reinstall_from_folder(&folder, &sha256, installed.path(), || panic!()).unwrap());
1312
1313        fs::write(
1314            folder.join("main.js"),
1315            "export function activate() { return 1; }",
1316        )
1317        .unwrap();
1318        assert_ne!(folder_fingerprint(&folder), before);
1319        let mut stopped = false;
1320        assert!(
1321            reinstall_from_folder(&folder, &sha256, installed.path(), || stopped = true).unwrap()
1322        );
1323        assert!(stopped);
1324        assert!(
1325            fs::read_to_string(installed.path().join("sample/main.js"))
1326                .unwrap()
1327                .contains("return 1")
1328        );
1329    }
1330}