Skip to main content

zoi_plugins/
lib.rs

1//! Plugin management system for Zoi.
2//!
3//! This crate provides the `PluginManager` which handles loading and executing
4//! Lua plugins that extend Zoi's functionality. It also includes support for
5//! extensions that can modify registry configurations.
6
7/// Registry extension management.
8pub mod extension;
9
10use std::collections::HashMap;
11use std::fs;
12use std::path::{Path, PathBuf};
13
14use anyhow::{Result, anyhow};
15use colored::Colorize;
16use comfy_table::Table as ComfyTable;
17use comfy_table::presets::UTF8_FULL;
18use dialoguer::theme::ColorfulTheme;
19use dialoguer::{Confirm, Select};
20use mlua::{Function, Lua, LuaSerdeExt, Table, Value};
21use zoi_core::{types, utils};
22use zoi_project as project;
23use zoi_resolver::{local, resolve};
24
25/// Key used in the Lua globals to store environment variable overrides.
26const PLUGIN_ENV_OVERRIDES_KEY: &str = "__ZOI_ENV_OVERRIDES";
27
28/// Orchestrates Zoi's extensibility via global Lua plugins.
29///
30/// Plugins allow users to customize Zoi's behavior by:
31/// - Registering new subcommands (`zoi.register_command`).
32/// - Intercepting lifecycle events (`zoi.on_post_install`, etc.).
33/// - Overriding tool versions at runtime (shim resolution).
34///
35/// Plugins are stored in Zoi's user data directory and are verified against
36/// a `trusted_hashes.json` database to prevent unauthorized execution.
37pub struct PluginManager {
38    /// The initialized mlua Lua Virtual Machine.
39    pub lua: Lua
40}
41
42impl PluginManager {
43    /// Initializes a new `PluginManager` and sets up the global Lua API.
44    ///
45    /// This injects the entire `zoi.*` API surface into the Lua environment,
46    /// enabling plugins to interact with the filesystem, HTTP, archives,
47    /// the UI, and the hook registry.
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if the Lua VM cannot be initialized or if the `zoi` API
52    /// fails to be injected.
53    pub fn new() -> Result<Self> {
54        let lua = Lua::new();
55        let manager = Self { lua };
56        manager.setup_api()?;
57        Ok(manager)
58    }
59
60    /// Sets up the global `zoi` API in the Lua environment.
61    fn setup_api(&self) -> Result<()> {
62        let zoi = self
63            .lua
64            .create_table()
65            .map_err(|e| anyhow!(e.to_string()))?;
66
67        self.lua
68            .globals()
69            .set(
70                "__ZOI_COMMANDS",
71                self.lua
72                    .create_table()
73                    .map_err(|e| anyhow!(e.to_string()))?
74            )
75            .map_err(|e| anyhow!(e.to_string()))?;
76        self.lua
77            .globals()
78            .set(
79                "__ZOI_COMMAND_HELP",
80                self.lua
81                    .create_table()
82                    .map_err(|e| anyhow!(e.to_string()))?
83            )
84            .map_err(|e| anyhow!(e.to_string()))?;
85
86        let register_command = self
87            .lua
88            .create_function(|lua, arg: Value| {
89                let registry: Table = lua.globals().get("__ZOI_COMMANDS")?;
90                let help_registry: Table =
91                    lua.globals().get("__ZOI_COMMAND_HELP")?;
92                match arg {
93                    Value::Table(t) => {
94                        let name: String = t.get("name")?;
95                        let desc: String = t
96                            .get("description")
97                            .unwrap_or_else(|_| String::new());
98                        let callback: Function = t.get("callback")?;
99                        registry.set(name.clone(), callback)?;
100                        help_registry.set(name, desc)?;
101                    }
102                    _ => {
103                        return Err(mlua::Error::RuntimeError(
104                            "Invalid argument to register_command. Expected a \
105                             table {name, description, callback}"
106                                .to_string()
107                        ));
108                    }
109                }
110                Ok(())
111            })
112            .map_err(|e| anyhow!(e.to_string()))?;
113        zoi.set("register_command", register_command)
114            .map_err(|e| anyhow!(e.to_string()))?;
115
116        let register_command_simple = self
117            .lua
118            .create_function(|lua, (name, callback): (String, Function)| {
119                let registry: Table = lua.globals().get("__ZOI_COMMANDS")?;
120                registry.set(name, callback)?;
121                Ok(())
122            })
123            .map_err(|e| anyhow!(e.to_string()))?;
124        zoi.set("register_command_simple", register_command_simple)
125            .map_err(|e| anyhow!(e.to_string()))?;
126
127        self.lua
128            .globals()
129            .set(
130                "__ZOI_HOOKS",
131                self.lua
132                    .create_table()
133                    .map_err(|e| anyhow!(e.to_string()))?
134            )
135            .map_err(|e| anyhow!(e.to_string()))?;
136        self.lua
137            .globals()
138            .set(
139                PLUGIN_ENV_OVERRIDES_KEY,
140                self.lua
141                    .create_table()
142                    .map_err(|e| anyhow!(e.to_string()))?
143            )
144            .map_err(|e| anyhow!(e.to_string()))?;
145        let hooks = [
146            "on_pre_install",
147            "on_post_install",
148            "on_pre_uninstall",
149            "on_post_uninstall",
150            "on_pre_sync",
151            "on_post_sync",
152            "on_rollback",
153            "on_pre_create",
154            "on_post_create",
155            "on_pre_extension_add",
156            "on_post_extension_add",
157            "on_pre_extension_remove",
158            "on_post_extension_remove",
159            "on_resolve_shim_version",
160            "on_project_install"
161        ];
162        for hook in hooks {
163            let hook_name = hook.to_string();
164            let register_hook = self
165                .lua
166                .create_function(move |lua, callback: Function| {
167                    let registry: Table = lua.globals().get("__ZOI_HOOKS")?;
168                    let hook_list: Table =
169                        if let Ok(t) = registry.get(hook_name.as_str()) {
170                            t
171                        } else {
172                            let t = lua.create_table()?;
173                            registry.set(hook_name.as_str(), t.clone())?;
174                            t
175                        };
176                    hook_list.push(callback)?;
177                    Ok(())
178                })
179                .map_err(|e| anyhow!(e.to_string()))?;
180            zoi.set(hook, register_hook)
181                .map_err(|e| anyhow!(e.to_string()))?;
182        }
183
184        let set_data = self
185            .lua
186            .create_function(|_, (key, value): (String, Value)| {
187                let mut state = read_plugin_state().unwrap_or_default();
188                let json_val: serde_json::Value = match value {
189                    Value::String(s) => {
190                        serde_json::Value::String(s.to_str()?.to_string())
191                    }
192                    Value::Integer(i) => serde_json::Value::Number(i.into()),
193                    Value::Number(n) => {
194                        let Some(num) = serde_json::Number::from_f64(n) else {
195                            return Err(mlua::Error::RuntimeError(
196                                "Non-finite numbers are not supported for \
197                                 set_data"
198                                    .to_string()
199                            ));
200                        };
201                        serde_json::Value::Number(num)
202                    }
203                    Value::Boolean(b) => serde_json::Value::Bool(b),
204                    _ => {
205                        return Err(mlua::Error::RuntimeError(
206                            "Unsupported value type for set_data".to_string()
207                        ));
208                    }
209                };
210                state.insert(key, json_val);
211                write_plugin_state(&state)
212                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
213                Ok(())
214            })
215            .map_err(|e| anyhow!(e.to_string()))?;
216        zoi.set("set_data", set_data)
217            .map_err(|e| anyhow!(e.to_string()))?;
218
219        let get_data = self
220            .lua
221            .create_function(|lua, key: String| {
222                let state = read_plugin_state().unwrap_or_default();
223                if let Some(val) = state.get(&key) {
224                    lua.to_value(val)
225                } else {
226                    Ok(Value::Nil)
227                }
228            })
229            .map_err(|e| anyhow!(e.to_string()))?;
230        zoi.set("get_data", get_data)
231            .map_err(|e| anyhow!(e.to_string()))?;
232
233        let list_installed = self
234            .lua
235            .create_function(|lua, ()| {
236                let installed = local::get_installed_packages()
237                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
238                lua.to_value(&installed)
239            })
240            .map_err(|e| anyhow!(e.to_string()))?;
241        zoi.set("list_installed", list_installed)
242            .map_err(|e| anyhow!(e.to_string()))?;
243
244        let get_package = self
245            .lua
246            .create_function(|lua, name: String| {
247                let (pkg, _, _, _, _, _, _) =
248                    resolve::resolve_package_and_version(
249                        &name, None, true, false
250                    )
251                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
252                lua.to_value(&pkg)
253            })
254            .map_err(|e| anyhow!(e.to_string()))?;
255        zoi.set("get_package", get_package)
256            .map_err(|e| anyhow!(e.to_string()))?;
257
258        if let Ok(config) = project::config::load() {
259            let project_table = self
260                .lua
261                .create_table()
262                .map_err(|e| anyhow!(e.to_string()))?;
263            project_table
264                .set("name", config.name)
265                .map_err(|e| anyhow!(e.to_string()))?;
266            project_table
267                .set("packages", config.pkgs)
268                .map_err(|e| anyhow!(e.to_string()))?;
269            zoi.set("project", project_table)
270                .map_err(|e| anyhow!(e.to_string()))?;
271        }
272
273        let ui = self
274            .lua
275            .create_table()
276            .map_err(|e| anyhow!(e.to_string()))?;
277        let ui_print = self
278            .lua
279            .create_function(|_, (text, color): (String, Option<String>)| {
280                let colored_text = match color.as_deref() {
281                    Some("red") => text.red(),
282                    Some("green") => text.green(),
283                    Some("yellow") => text.yellow(),
284                    Some("blue") => text.blue(),
285                    Some("cyan") => text.cyan(),
286                    Some("magenta") => text.magenta(),
287                    _ => text.normal()
288                };
289                println!("{colored_text}");
290                Ok(())
291            })
292            .map_err(|e| anyhow!(e.to_string()))?;
293        ui.set("print", ui_print)
294            .map_err(|e| anyhow!(e.to_string()))?;
295
296        let ui_confirm = self
297            .lua
298            .create_function(|_, prompt: String| {
299                Ok(Confirm::with_theme(&ColorfulTheme::default())
300                    .with_prompt(prompt)
301                    .interact()
302                    .unwrap_or(false))
303            })
304            .map_err(|e| anyhow!(e.to_string()))?;
305        ui.set("confirm", ui_confirm)
306            .map_err(|e| anyhow!(e.to_string()))?;
307
308        let ui_select = self
309            .lua
310            .create_function(|_, (prompt, options): (String, Vec<String>)| {
311                let selection = Select::with_theme(&ColorfulTheme::default())
312                    .with_prompt(prompt)
313                    .items(&options)
314                    .default(0)
315                    .interact_opt()
316                    .unwrap_or(None);
317                Ok(selection.map(|s| s + 1))
318            })
319            .map_err(|e| anyhow!(e.to_string()))?;
320        ui.set("select", ui_select)
321            .map_err(|e| anyhow!(e.to_string()))?;
322
323        let ui_table = self
324            .lua
325            .create_function(
326                |_, (headers, rows): (Vec<String>, Vec<Vec<String>>)| {
327                    let mut table = ComfyTable::new();
328                    table.load_style(UTF8_FULL).set_header(headers);
329                    for row in rows {
330                        table.add_row(row);
331                    }
332                    println!("{table}");
333                    Ok(())
334                }
335            )
336            .map_err(|e| anyhow!(e.to_string()))?;
337        ui.set("table", ui_table)
338            .map_err(|e| anyhow!(e.to_string()))?;
339        zoi.set("ui", ui).map_err(|e| anyhow!(e.to_string()))?;
340
341        let system = self
342            .lua
343            .create_table()
344            .map_err(|e| anyhow!(e.to_string()))?;
345        let platform = utils::get_platform()
346            .unwrap_or_else(|_| "unknown-unknown".to_string());
347        let parts: Vec<&str> = platform.split('-').collect();
348        system
349            .set("os", parts.first().unwrap_or(&"unknown").to_string())
350            .map_err(|e| anyhow!(e.to_string()))?;
351        system
352            .set("arch", parts.get(1).unwrap_or(&"unknown").to_string())
353            .map_err(|e| anyhow!(e.to_string()))?;
354        if let Some(distro) = utils::get_linux_distribution() {
355            system
356                .set("distro", distro)
357                .map_err(|e| anyhow!(e.to_string()))?;
358        }
359        if let Some(dv) = utils::get_distro_version() {
360            system
361                .set("distro_ver", dv)
362                .map_err(|e| anyhow!(e.to_string()))?;
363        }
364
365        zoi.set("system", system)
366            .map_err(|e| anyhow!(e.to_string()))?;
367        zoi.set("version", env!("CARGO_PKG_VERSION"))
368            .map_err(|e| anyhow!(e.to_string()))?;
369        zoi.set("scope", "user") // Default
370            .map_err(|e| anyhow!(e.to_string()))?;
371
372        let shell = self
373            .lua
374            .create_function(|lua, cmd: String| {
375                let env_overrides: Table = lua
376                    .globals()
377                    .get(PLUGIN_ENV_OVERRIDES_KEY)
378                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
379
380                let mut command = if cfg!(target_os = "windows") {
381                    let mut c = std::process::Command::new("pwsh");
382                    c.arg("-Command").arg(&cmd);
383                    c
384                } else {
385                    let mut c = std::process::Command::new("bash");
386                    c.arg("-c").arg(&cmd);
387                    c
388                };
389
390                for pair in env_overrides.pairs::<String, String>() {
391                    let (key, value) = pair.map_err(|e| {
392                        mlua::Error::RuntimeError(e.to_string())
393                    })?;
394                    command.env(key, value);
395                }
396
397                if let Ok(zoi_table) = lua.globals().get::<Table>("zoi")
398                    && let Ok(scope_str) = zoi_table.get::<String>("scope")
399                {
400                    command.env("ZOI_SCOPE", scope_str);
401                }
402
403                let status = command.status();
404                match status {
405                    Ok(s) => Ok(s.code().unwrap_or(i32::from(!s.success()))),
406                    Err(e) => Err(mlua::Error::RuntimeError(e.to_string()))
407                }
408            })
409            .map_err(|e| anyhow!(e.to_string()))?;
410        zoi.set("sh", shell).map_err(|e| anyhow!(e.to_string()))?;
411
412        let fs_table = self
413            .lua
414            .create_table()
415            .map_err(|e| anyhow!(e.to_string()))?;
416        let fs_read = self
417            .lua
418            .create_function(
419                |_, path: String| Ok(fs::read_to_string(path).ok())
420            )
421            .map_err(|e| anyhow!(e.to_string()))?;
422        fs_table
423            .set("read", fs_read)
424            .map_err(|e| anyhow!(e.to_string()))?;
425
426        let fs_write = self
427            .lua
428            .create_function(|_, (path, content): (String, String)| {
429                Ok(fs::write(path, content).is_ok())
430            })
431            .map_err(|e| anyhow!(e.to_string()))?;
432        fs_table
433            .set("write", fs_write)
434            .map_err(|e| anyhow!(e.to_string()))?;
435
436        let fs_exists = self
437            .lua
438            .create_function(|_, path: String| Ok(PathBuf::from(path).exists()))
439            .map_err(|e| anyhow!(e.to_string()))?;
440        fs_table
441            .set("exists", fs_exists)
442            .map_err(|e| anyhow!(e.to_string()))?;
443
444        let fs_list = self
445            .lua
446            .create_function(|lua, path: String| {
447                let mut entries = Vec::new();
448                if let Ok(read_dir) = fs::read_dir(path) {
449                    for entry in read_dir.flatten() {
450                        entries.push(
451                            entry.file_name().to_string_lossy().to_string()
452                        );
453                    }
454                }
455                lua.to_value(&entries)
456            })
457            .map_err(|e| anyhow!(e.to_string()))?;
458        fs_table
459            .set("list", fs_list)
460            .map_err(|e| anyhow!(e.to_string()))?;
461
462        let fs_delete = self
463            .lua
464            .create_function(|_, path: String| {
465                let p = PathBuf::from(path);
466                if p.is_dir() {
467                    Ok(fs::remove_dir_all(p).is_ok())
468                } else {
469                    Ok(fs::remove_file(p).is_ok())
470                }
471            })
472            .map_err(|e| anyhow!(e.to_string()))?;
473        fs_table
474            .set("delete", fs_delete)
475            .map_err(|e| anyhow!(e.to_string()))?;
476
477        let fs_symlink = self
478            .lua
479            .create_function(
480                |_, (target, link, is_dir): (String, String, bool)| {
481                    let target_path = PathBuf::from(target);
482                    let link_path = PathBuf::from(link);
483                    if is_dir {
484                        Ok(utils::symlink_dir(&target_path, &link_path).is_ok())
485                    } else {
486                        Ok(utils::symlink_file(&target_path, &link_path)
487                            .is_ok())
488                    }
489                }
490            )
491            .map_err(|e| anyhow!(e.to_string()))?;
492        fs_table
493            .set("symlink", fs_symlink)
494            .map_err(|e| anyhow!(e.to_string()))?;
495
496        let fs_copy = self
497            .lua
498            .create_function(|_, (src, dest): (String, String)| {
499                let src_path = Path::new(&src);
500                let dest_path = Path::new(&dest);
501                if src_path.is_dir() {
502                    Ok(utils::copy_dir_all(src_path, dest_path).is_ok())
503                } else {
504                    Ok(fs::copy(src_path, dest_path).is_ok())
505                }
506            })
507            .map_err(|e| anyhow!(e.to_string()))?;
508        fs_table
509            .set("copy", fs_copy)
510            .map_err(|e| anyhow!(e.to_string()))?;
511
512        zoi.set("fs", fs_table)
513            .map_err(|e| anyhow!(e.to_string()))?;
514
515        let archive_table = self
516            .lua
517            .create_table()
518            .map_err(|e| anyhow!(e.to_string()))?;
519        let archive_extract = self
520            .lua
521            .create_function(
522                |_, (source, dest, strip): (String, String, Option<usize>)| {
523                    fn safe_stripped_relative_path(
524                        path: &Path,
525                        strip: usize
526                    ) -> Result<Option<PathBuf>, std::io::Error>
527                    {
528                        let mut sanitized = PathBuf::new();
529                        let mut has_component = false;
530                        for component in path.components().skip(strip) {
531                            match component {
532                                std::path::Component::Normal(part) => {
533                                    sanitized.push(part);
534                                    has_component = true;
535                                }
536                                std::path::Component::CurDir => {}
537                                _ => {
538                                    return Err(std::io::Error::new(
539                                        std::io::ErrorKind::InvalidInput,
540                                        format!(
541                                            "Archive entry escapes \
542                                             destination: {}",
543                                            path.display()
544                                        )
545                                    ));
546                                }
547                            }
548                        }
549                        if has_component {
550                            Ok(Some(sanitized))
551                        } else {
552                            Ok(None)
553                        }
554                    }
555
556                    fn unpack_with_strip<R: std::io::Read>(
557                        mut archive: tar::Archive<R>,
558                        dest: &Path,
559                        strip: usize
560                    ) -> Result<(), std::io::Error> {
561                        for entry in archive.entries()? {
562                            let mut entry = entry?;
563                            let path = entry.path()?.to_path_buf();
564                            let Some(stripped_path) =
565                                safe_stripped_relative_path(&path, strip)?
566                            else {
567                                continue;
568                            };
569                            entry.unpack(dest.join(stripped_path))?;
570                        }
571                        Ok(())
572                    }
573
574                    let src_path = Path::new(&source);
575                    let dest_path = Path::new(&dest);
576
577                    if !dest_path.exists() {
578                        let _ = fs::create_dir_all(dest_path);
579                    }
580
581                    let file = fs::File::open(src_path).map_err(|e| {
582                        mlua::Error::RuntimeError(e.to_string())
583                    })?;
584                    let archive_path_str = source.to_lowercase();
585
586                    let strip_val = strip.unwrap_or(0);
587
588                    if std::path::Path::new(&archive_path_str)
589                        .extension()
590                        .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
591                    {
592                        let mut archive =
593                            zip::ZipArchive::new(file).map_err(|e| {
594                                mlua::Error::RuntimeError(e.to_string())
595                            })?;
596                        if strip_val > 0 {
597                            for i in 0..archive.len() {
598                                let mut file =
599                                    archive.by_index(i).map_err(|e| {
600                                        mlua::Error::RuntimeError(e.to_string())
601                                    })?;
602                                let path = PathBuf::from(
603                                    // Since zip 9.0 reading an entry name is
604                                    // fallible, because it is decoded
605                                    // according to the entry's encoding flags.
606                                    file.name()
607                                        .map_err(|e| {
608                                            mlua::Error::RuntimeError(
609                                                e.to_string()
610                                            )
611                                        })?
612                                        .into_owned()
613                                );
614                                let Some(stripped_path) =
615                                    safe_stripped_relative_path(
616                                        &path, strip_val
617                                    )
618                                    .map_err(|e| {
619                                        mlua::Error::RuntimeError(e.to_string())
620                                    })?
621                                else {
622                                    continue;
623                                };
624                                let out_path = dest_path.join(stripped_path);
625                                if file.is_dir() {
626                                    fs::create_dir_all(&out_path).map_err(
627                                        |e| {
628                                            mlua::Error::RuntimeError(
629                                                e.to_string()
630                                            )
631                                        }
632                                    )?;
633                                } else {
634                                    if let Some(p) = out_path.parent() {
635                                        fs::create_dir_all(p).map_err(|e| {
636                                            mlua::Error::RuntimeError(
637                                                e.to_string()
638                                            )
639                                        })?;
640                                    }
641                                    let mut outfile = fs::File::create(
642                                        &out_path
643                                    )
644                                    .map_err(|e| {
645                                        mlua::Error::RuntimeError(e.to_string())
646                                    })?;
647                                    std::io::copy(&mut file, &mut outfile)
648                                        .map_err(|e| {
649                                            mlua::Error::RuntimeError(
650                                                e.to_string()
651                                            )
652                                        })?;
653                                }
654                            }
655                        } else {
656                            archive.extract(dest_path).map_err(|e| {
657                                mlua::Error::RuntimeError(e.to_string())
658                            })?;
659                        }
660                    } else if archive_path_str.ends_with(".tar.gz")
661                        || std::path::Path::new(&archive_path_str)
662                            .extension()
663                            .is_some_and(|ext| ext.eq_ignore_ascii_case("tgz"))
664                    {
665                        let tar_gz = flate2::read::GzDecoder::new(file);
666                        let archive = tar::Archive::new(tar_gz);
667                        if strip_val > 0 {
668                            unpack_with_strip(archive, dest_path, strip_val)
669                                .map_err(|e| {
670                                    mlua::Error::RuntimeError(e.to_string())
671                                })?;
672                        } else {
673                            let mut archive = archive;
674                            archive.unpack(dest_path).map_err(|e| {
675                                mlua::Error::RuntimeError(e.to_string())
676                            })?;
677                        }
678                    } else if archive_path_str.ends_with(".tar.zst") {
679                        let tar_zst = zstd::stream::read::Decoder::new(file)
680                            .map_err(|e| {
681                                mlua::Error::RuntimeError(e.to_string())
682                            })?;
683                        let archive = tar::Archive::new(tar_zst);
684                        if strip_val > 0 {
685                            unpack_with_strip(archive, dest_path, strip_val)
686                                .map_err(|e| {
687                                    mlua::Error::RuntimeError(e.to_string())
688                                })?;
689                        } else {
690                            let mut archive = archive;
691                            archive.unpack(dest_path).map_err(|e| {
692                                mlua::Error::RuntimeError(e.to_string())
693                            })?;
694                        }
695                    } else if archive_path_str.ends_with(".tar.xz") {
696                        let tar_xz = xz2::read::XzDecoder::new(file);
697                        let archive = tar::Archive::new(tar_xz);
698                        if strip_val > 0 {
699                            unpack_with_strip(archive, dest_path, strip_val)
700                                .map_err(|e| {
701                                    mlua::Error::RuntimeError(e.to_string())
702                                })?;
703                        } else {
704                            let mut archive = archive;
705                            archive.unpack(dest_path).map_err(|e| {
706                                mlua::Error::RuntimeError(e.to_string())
707                            })?;
708                        }
709                    } else {
710                        return Err(mlua::Error::RuntimeError(format!(
711                            "Unsupported archive format: {source}"
712                        )));
713                    }
714                    Ok(true)
715                }
716            )
717            .map_err(|e| anyhow!(e.to_string()))?;
718        archive_table
719            .set("extract", archive_extract)
720            .map_err(|e| anyhow!(e.to_string()))?;
721        zoi.set("archive", archive_table)
722            .map_err(|e| anyhow!(e.to_string()))?;
723
724        let http_table = self
725            .lua
726            .create_table()
727            .map_err(|e| anyhow!(e.to_string()))?;
728        let http_get = self
729            .lua
730            .create_function(|_, url: String| {
731                let client = reqwest::blocking::Client::builder()
732                    .user_agent("zoi-plugin")
733                    .build()
734                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
735                match client.get(&url).send() {
736                    Ok(resp) => Ok(resp.text().ok()),
737                    Err(_) => Ok(None)
738                }
739            })
740            .map_err(|e| anyhow!(e.to_string()))?;
741        http_table
742            .set("get", http_get)
743            .map_err(|e| anyhow!(e.to_string()))?;
744
745        let http_download = self
746            .lua
747            .create_function(|_, (url, dest): (String, String)| {
748                let mut response = reqwest::blocking::get(&url)
749                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
750                if !response.status().is_success() {
751                    return Ok(false);
752                }
753                let mut dest_file = fs::File::create(dest)
754                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
755                std::io::copy(&mut response, &mut dest_file)
756                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
757                Ok(true)
758            })
759            .map_err(|e| anyhow!(e.to_string()))?;
760        http_table
761            .set("download", http_download)
762            .map_err(|e| anyhow!(e.to_string()))?;
763
764        let http_post = self
765            .lua
766            .create_function(|_, (url, body): (String, String)| {
767                let client = reqwest::blocking::Client::builder()
768                    .user_agent("zoi-plugin")
769                    .build()
770                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
771                match client.post(&url).body(body).send() {
772                    Ok(resp) => Ok(resp.text().ok()),
773                    Err(_) => Ok(None)
774                }
775            })
776            .map_err(|e| anyhow!(e.to_string()))?;
777        http_table
778            .set("post", http_post)
779            .map_err(|e| anyhow!(e.to_string()))?;
780        zoi.set("http", http_table)
781            .map_err(|e| anyhow!(e.to_string()))?;
782
783        let json_table = self
784            .lua
785            .create_table()
786            .map_err(|e| anyhow!(e.to_string()))?;
787        let json_parse = self
788            .lua
789            .create_function(|lua, json_str: String| {
790                let parsed: serde_json::Value = serde_json::from_str(&json_str)
791                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
792                lua.to_value(&parsed)
793            })
794            .map_err(|e| anyhow!(e.to_string()))?;
795        json_table
796            .set("parse", json_parse)
797            .map_err(|e| anyhow!(e.to_string()))?;
798
799        let json_stringify = self
800            .lua
801            .create_function(|lua, value: Value| {
802                let json_val: serde_json::Value = lua
803                    .from_value(value)
804                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
805                Ok(serde_json::to_string(&json_val).unwrap_or_default())
806            })
807            .map_err(|e| anyhow!(e.to_string()))?;
808        json_table
809            .set("stringify", json_stringify)
810            .map_err(|e| anyhow!(e.to_string()))?;
811        zoi.set("json", json_table)
812            .map_err(|e| anyhow!(e.to_string()))?;
813
814        let env_table = self
815            .lua
816            .create_table()
817            .map_err(|e| anyhow!(e.to_string()))?;
818        let env_get = self
819            .lua
820            .create_function(|lua, name: String| {
821                let env_overrides: Table = lua
822                    .globals()
823                    .get(PLUGIN_ENV_OVERRIDES_KEY)
824                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
825
826                if let Some(value) = env_overrides
827                    .get::<Option<String>>(name.as_str())
828                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?
829                {
830                    return Ok(Some(value));
831                }
832
833                Ok(std::env::var(name).ok())
834            })
835            .map_err(|e| anyhow!(e.to_string()))?;
836        env_table
837            .set("get", env_get)
838            .map_err(|e| anyhow!(e.to_string()))?;
839
840        let env_set = self
841            .lua
842            .create_function(|lua, (name, value): (String, String)| {
843                let env_overrides: Table = lua
844                    .globals()
845                    .get(PLUGIN_ENV_OVERRIDES_KEY)
846                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
847                env_overrides
848                    .set(name, value)
849                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
850                Ok(())
851            })
852            .map_err(|e| anyhow!(e.to_string()))?;
853        env_table
854            .set("set", env_set)
855            .map_err(|e| anyhow!(e.to_string()))?;
856        zoi.set("env", env_table)
857            .map_err(|e| anyhow!(e.to_string()))?;
858
859        self.lua
860            .globals()
861            .set("zoi", zoi)
862            .map_err(|e| anyhow!(e.to_string()))?;
863
864        let plugin_dir = get_plugin_dir()?;
865        let import_fn = self
866            .lua
867            .create_function(move |lua, file_name: String| {
868                // `IMPORT` is documented as "load a file that sits next to
869                // the plugin", but a plain `join` also accepts an absolute
870                // path or `../` segments, which would let a plugin read any
871                // file on the host. `safe_join` enforces the boundary.
872                let path = zoi_core::utils::safe_join(
873                    &plugin_dir,
874                    Path::new(&file_name)
875                )
876                .map_err(|e| {
877                    mlua::Error::RuntimeError(format!(
878                        "Invalid import path '{file_name}': {e}"
879                    ))
880                })?;
881                if !path.exists() {
882                    return Err(mlua::Error::RuntimeError(format!(
883                        "File not found: {}",
884                        path.display()
885                    )));
886                }
887                let content = fs::read_to_string(&path)
888                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
889                if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
890                    match ext {
891                        "json" => {
892                            let val: serde_json::Value = serde_json::from_str(
893                                &content
894                            )
895                            .map_err(|e| {
896                                mlua::Error::RuntimeError(e.to_string())
897                            })?;
898                            return lua.to_value(&val);
899                        }
900                        _ => return lua.to_value(&content)
901                    }
902                }
903                lua.to_value(&content)
904            })
905            .map_err(|e| anyhow!(e.to_string()))?;
906        self.lua
907            .globals()
908            .set("IMPORT", import_fn)
909            .map_err(|e| anyhow!(e.to_string()))?;
910
911        Ok(())
912    }
913
914    /// Sets the operational scope for plugins.
915    ///
916    /// # Errors
917    ///
918    /// Returns an error if the `zoi` global table cannot be accessed or if the
919    /// scope cannot be set.
920    pub fn set_context(&self, scope: types::Scope) -> Result<()> {
921        let zoi: Table = self
922            .lua
923            .globals()
924            .get("zoi")
925            .map_err(|e| anyhow!(e.to_string()))?;
926        let scope_str = format!("{scope:?}").to_lowercase();
927        zoi.set("scope", scope_str)
928            .map_err(|e| anyhow!(e.to_string()))?;
929        Ok(())
930    }
931
932    /// Loads and executes all trusted Lua plugins from the plugin directory.
933    ///
934    /// # Errors
935    ///
936    /// Returns an error if the plugin directory cannot be read, if a plugin
937    /// script cannot be loaded, or if a plugin execution fails.
938    pub fn load_all(&self, yes: bool) -> Result<()> {
939        let plugin_dir = get_plugin_dir()?;
940        if !plugin_dir.exists() {
941            return Ok(());
942        }
943        let mut plugin_paths = Vec::new();
944        for entry in fs::read_dir(plugin_dir)? {
945            let entry = entry?;
946            let path = entry.path();
947            if path.extension().and_then(|s| s.to_str()) == Some("lua") {
948                plugin_paths.push(path);
949            }
950        }
951        plugin_paths.sort();
952
953        let trusted_path = get_plugin_dir()?.join("trusted_hashes.json");
954        let mut trusted: HashMap<String, String> = if trusted_path.exists() {
955            let content = fs::read_to_string(&trusted_path)?;
956            serde_json::from_str(&content).unwrap_or_default()
957        } else {
958            HashMap::new()
959        };
960        let mut trusted_changed = false;
961
962        for path in plugin_paths {
963            let script = fs::read_to_string(&path)?;
964
965            let hash = zoi_core::hash::calculate_string_hash(
966                &script,
967                zoi_core::hash::DEFAULT_ALGORITHM
968            );
969
970            let plugin_name = path
971                .file_name()
972                .unwrap_or_default()
973                .to_string_lossy()
974                .to_string();
975
976            let known_hash = trusted.get(&plugin_name);
977            let is_trusted = known_hash.is_some_and(|known| {
978                zoi_core::hash::bytes_match_hex(script.as_bytes(), known)
979            });
980            // Trust recorded as SHA-256 by an earlier version: keep it and
981            // record the SHA-512 from now on.
982            if is_trusted && known_hash != Some(&hash) {
983                trusted.insert(plugin_name.clone(), hash.clone());
984                trusted_changed = true;
985            }
986
987            if !is_trusted {
988                if yes {
989                    println!(
990                        "\n{}: Skipping untrusted plugin: {}. Run Zoi \
991                         interactively to trust it.",
992                        "Warning".yellow().bold(),
993                        plugin_name.cyan()
994                    );
995
996                    continue;
997                }
998
999                println!(
1000                    "\n{}: Untrusted plugin detected: {}",
1001                    "SECURITY WARNING".yellow().bold(),
1002                    plugin_name.cyan()
1003                );
1004                println!(
1005                    "Plugins can execute arbitrary commands and modify your \
1006                     system."
1007                );
1008                if utils::ask_for_confirmation(
1009                    "Do you trust this plugin and want to execute it?",
1010                    false
1011                ) {
1012                    trusted.insert(plugin_name.clone(), hash);
1013                    trusted_changed = true;
1014                } else {
1015                    println!("Skipping untrusted plugin: {plugin_name}");
1016                    continue;
1017                }
1018            }
1019
1020            let script_wrapper = format!(
1021                "local old_reg = zoi.register_command; zoi.register_command = \
1022                 function(a, b) if type(a) == 'string' then \
1023                 zoi.register_command_simple(a, b) else old_reg(a) end end; \
1024                 {script}"
1025            );
1026            self.lua.load(&script_wrapper).exec().map_err(|e| {
1027                anyhow!("Plugin error in {}: {}", path.display(), e)
1028            })?;
1029        }
1030
1031        if trusted_changed {
1032            let content = serde_json::to_string_pretty(&trusted)?;
1033            fs::write(trusted_path, content)?;
1034        }
1035
1036        Ok(())
1037    }
1038
1039    /// Triggers a lifecycle hook, executing all registered callbacks.
1040    ///
1041    /// # Errors
1042    ///
1043    /// Returns an error if the hook registry cannot be accessed or if any
1044    /// callback execution fails.
1045    pub fn trigger_hook(
1046        &self,
1047        hook_name: &str,
1048        arg: Option<&Value>
1049    ) -> Result<()> {
1050        let registry: Table = self
1051            .lua
1052            .globals()
1053            .get("__ZOI_HOOKS")
1054            .map_err(|e| anyhow!(e.to_string()))?;
1055        if let Ok(hook_list) = registry.get::<Table>(hook_name) {
1056            for callback in hook_list.sequence_values::<Function>() {
1057                let callback = callback.map_err(|e| anyhow!(e.to_string()))?;
1058                if let Some(a) = arg {
1059                    callback
1060                        .call::<()>(a.clone())
1061                        .map_err(|e| anyhow!(e.to_string()))?;
1062                } else {
1063                    callback
1064                        .call::<()>(())
1065                        .map_err(|e| anyhow!(e.to_string()))?;
1066                }
1067            }
1068        }
1069        Ok(())
1070    }
1071
1072    /// Triggers a lifecycle hook but ignores errors, printing a warning
1073    /// instead.
1074    pub fn trigger_hook_nonfatal(&self, hook_name: &str, arg: Option<&Value>) {
1075        if let Err(error) = self.trigger_hook(hook_name, arg) {
1076            eprintln!(
1077                "Warning: hook '{hook_name}' failed after the operation \
1078                 completed: {error}"
1079            );
1080        }
1081    }
1082
1083    /// Triggers the shim version resolution hook.
1084    ///
1085    /// # Errors
1086    ///
1087    /// Returns an error if the hook registry cannot be accessed or if any
1088    /// callback execution fails.
1089    pub fn trigger_resolve_shim_version(
1090        &self,
1091        bin_name: &str
1092    ) -> Result<Option<String>> {
1093        let registry: Table = self
1094            .lua
1095            .globals()
1096            .get("__ZOI_HOOKS")
1097            .map_err(|e| anyhow!(e.to_string()))?;
1098
1099        if let Ok(hook_list) = registry.get::<Table>("on_resolve_shim_version")
1100        {
1101            for callback in hook_list.sequence_values::<Function>() {
1102                let callback = callback.map_err(|e| anyhow!(e.to_string()))?;
1103                let result: Option<String> = callback
1104                    .call(bin_name)
1105                    .map_err(|e| anyhow!(e.to_string()))?;
1106                if result.is_some() {
1107                    return Ok(result);
1108                }
1109            }
1110        }
1111        Ok(None)
1112    }
1113
1114    /// Triggers the project installation hook.
1115    ///
1116    /// # Errors
1117    ///
1118    /// Returns an error if the hook registry cannot be accessed or if any
1119    /// callback execution fails.
1120    pub fn trigger_project_install_hook(&self) -> Result<bool> {
1121        let registry: Table = self
1122            .lua
1123            .globals()
1124            .get("__ZOI_HOOKS")
1125            .map_err(|e| anyhow!(e.to_string()))?;
1126
1127        if let Ok(hook_list) = registry.get::<Table>("on_project_install") {
1128            for callback in hook_list.sequence_values::<Function>() {
1129                let callback = callback.map_err(|e| anyhow!(e.to_string()))?;
1130                let handled: bool =
1131                    callback.call(()).map_err(|e| anyhow!(e.to_string()))?;
1132                if handled {
1133                    return Ok(true);
1134                }
1135            }
1136        }
1137        Ok(false)
1138    }
1139
1140    /// Executes a custom command registered by a plugin.
1141    ///
1142    /// # Errors
1143    ///
1144    /// Returns an error if the command registry cannot be accessed or if the
1145    /// command execution fails.
1146    pub fn run_command(&self, name: &str, args: Vec<String>) -> Result<bool> {
1147        let registry: Table = self
1148            .lua
1149            .globals()
1150            .get("__ZOI_COMMANDS")
1151            .map_err(|e| anyhow!(e.to_string()))?;
1152        let callback: Value =
1153            registry.get(name).map_err(|e| anyhow!(e.to_string()))?;
1154        if let Value::Function(func) = callback {
1155            func.call::<()>(args).map_err(|e| anyhow!(e.to_string()))?;
1156            Ok(true)
1157        } else {
1158            Ok(false)
1159        }
1160    }
1161
1162    /// Lists all custom commands registered by plugins.
1163    ///
1164    /// # Errors
1165    ///
1166    /// Returns an error if the command registry cannot be accessed.
1167    pub fn list_commands(&self) -> Result<Vec<(String, String)>> {
1168        let registry: Table = self
1169            .lua
1170            .globals()
1171            .get("__ZOI_COMMANDS")
1172            .map_err(|e| anyhow!(e.to_string()))?;
1173        let help_registry: Table = self
1174            .lua
1175            .globals()
1176            .get("__ZOI_COMMAND_HELP")
1177            .map_err(|e| anyhow!(e.to_string()))?;
1178        let mut commands = Vec::new();
1179        for pair in registry.pairs::<String, Value>() {
1180            let (name, _) = pair.map_err(|e| anyhow!(e.to_string()))?;
1181            let desc: String = help_registry
1182                .get(name.clone())
1183                .unwrap_or_else(|_| String::new());
1184            commands.push((name, desc));
1185        }
1186        Ok(commands)
1187    }
1188}
1189
1190/// Returns the path to the Zoi plugin directory.
1191///
1192/// # Errors
1193///
1194/// Returns an error if the user home directory cannot be found or if the
1195/// plugin directory cannot be created.
1196pub fn get_plugin_dir() -> Result<PathBuf> {
1197    let plugin_dir = utils::get_user_data_dir()?.join("plugins");
1198    if !plugin_dir.exists() {
1199        fs::create_dir_all(&plugin_dir)?;
1200    }
1201    Ok(plugin_dir)
1202}
1203
1204/// Reads the persistent state for plugins from state.json.
1205fn read_plugin_state() -> Result<HashMap<String, serde_json::Value>> {
1206    let path = get_plugin_dir()?.join("state.json");
1207    if !path.exists() {
1208        return Ok(HashMap::new());
1209    }
1210    let content = fs::read_to_string(path)?;
1211    Ok(serde_json::from_str(&content).unwrap_or_default())
1212}
1213
1214/// Writes the persistent state for plugins to state.json.
1215fn write_plugin_state(
1216    state: &HashMap<String, serde_json::Value>
1217) -> Result<()> {
1218    let path = get_plugin_dir()?.join("state.json");
1219    let content = serde_json::to_string_pretty(state)?;
1220    fs::write(path, content)?;
1221    Ok(())
1222}