Skip to main content

crisol_core/extensions/
mod.rs

1//! The versioned extension manifest, capabilities, and contributions.
2//!
3//! The runtime and the UI stay in `crisol-extensions`; the manifest and its validation
4//! live here so remote hosts and the agent can read them without egui.
5//!
6//! ```
7//! use crisol_core::extensions;
8//! ```
9
10use std::collections::BTreeSet;
11use std::path::{Component, Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14
15/// The host API version this core implements.
16/// # Example
17///
18/// ```
19/// use crisol_core::extensions::HOST_API_VERSION;
20/// ```
21pub const HOST_API_VERSION: &str = "0.15";
22
23/// The API range this extension targets.
24#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
25#[non_exhaustive]
26/// # Example
27///
28/// ```
29/// use crisol_core::extensions::ApiRange;
30/// ```
31pub struct ApiRange {
32    /// Minimum host API version, such as `0.15`.
33    pub min: String,
34    /// Maximum host API version, exclusive.
35    pub max: String,
36}
37
38impl Default for ApiRange {
39    fn default() -> Self {
40        Self::line(HOST_API_VERSION)
41    }
42}
43
44impl ApiRange {
45    /// A range from its lower and exclusive upper bound.
46    pub fn new(min: impl Into<String>, max: impl Into<String>) -> Self {
47        Self {
48            min: min.into(),
49            max: max.into(),
50        }
51    }
52
53    /// A range for one minor line.
54    pub fn line(version: &str) -> Self {
55        let mut parts = version.split('.');
56        let major = parts.next().unwrap_or("0");
57        let minor = parts.next().unwrap_or("0").parse::<u64>().unwrap_or(0);
58        Self {
59            min: format!("{major}.{minor}"),
60            max: format!("{major}.{}", minor + 1),
61        }
62    }
63
64    /// Whether this host (`HOST_API_VERSION`) is inside the range. Comparison is major
65    /// and minor only; the host API is not patch-sensitive.
66    pub fn allows(&self, version: &str) -> bool {
67        // An unparsable bound used to read as `0.0`, which made `min: "abc"` accept any host.
68        [version, &self.min, &self.max].iter().all(|text| well_formed(text))
69            && compare(version, &self.min) >= 0
70            && compare(version, &self.max) < 0
71    }
72}
73
74/// `major.minor` with optional further numeric parts.
75fn well_formed(version: &str) -> bool {
76    let mut parts = version.split('.');
77    parts.clone().count() >= 2 && parts.all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
78}
79
80fn compare(left: &str, right: &str) -> i32 {
81    let mut left = left.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
82    let mut right = right.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
83    for _ in 0..2 {
84        let a = left.next().unwrap_or(0);
85        let b = right.next().unwrap_or(0);
86        if a != b {
87            return if a < b { -1 } else { 1 };
88        }
89    }
90    0
91}
92
93/// A module path that stays inside the extension directory on every platform.
94///
95/// `Path::components` does not treat a Windows drive or UNC prefix as a root on Unix, so
96/// the separators and drive colon are rejected explicitly before the component walk.
97fn entry_is_safe(entry: &str) -> bool {
98    if entry.is_empty() || entry.contains('\\') || entry.contains(':') {
99        return false;
100    }
101    Path::new(entry)
102        .components()
103        .all(|component| matches!(component, Component::Normal(_)))
104}
105
106/// A capability requested by an extension.
107#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
108#[serde(tag = "kind", rename_all = "snake_case")]
109#[non_exhaustive]
110/// # Example
111///
112/// ```
113/// use crisol_core::extensions::Capability;
114/// ```
115pub enum Capability {
116    /// Contribute commands.
117    Commands,
118    /// Contribute panels.
119    Panels,
120    /// Contribute viewers.
121    Viewers,
122    /// Contribute themes.
123    Themes,
124    /// Contribute keybindings.
125    Keybindings,
126    /// Store settings.
127    Settings,
128    /// Contribute plot layers.
129    ChartLayers,
130    /// Read files under a path prefix.
131    FilesystemRead {
132        /// The allowed prefix.
133        prefix: String,
134    },
135    /// Read dataset metadata.
136    Data,
137    /// Read and write the selection bus.
138    Selection,
139}
140
141impl Capability {
142    /// Parse the manifest spelling (`commands`, `filesystem:read:notes`).
143    ///
144    /// # Errors
145    /// When the spelling is not known.
146    pub fn parse(text: &str) -> Result<Self, ManifestError> {
147        let value = match text {
148            "commands" => Self::Commands,
149            "panels" => Self::Panels,
150            "viewers" => Self::Viewers,
151            "themes" => Self::Themes,
152            "keybindings" => Self::Keybindings,
153            "settings" => Self::Settings,
154            "chart-layers" => Self::ChartLayers,
155            "data" => Self::Data,
156            "selection" => Self::Selection,
157            other => {
158                if let Some(prefix) = other.strip_prefix("filesystem:read:") {
159                    // An empty prefix names nothing; reject it instead of granting a
160                    // capability that can never match (or, resolved later, the working dir).
161                    if prefix.is_empty() {
162                        return Err(ManifestError::Capability(other.to_owned()));
163                    }
164                    Self::FilesystemRead {
165                        prefix: prefix.to_owned(),
166                    }
167                } else {
168                    return Err(ManifestError::Capability(other.to_owned()));
169                }
170            }
171        };
172        Ok(value)
173    }
174}
175
176/// The manifest on disk.
177#[derive(Clone, Debug, Default, Serialize, Deserialize)]
178#[non_exhaustive]
179/// # Example
180///
181/// ```
182/// use crisol_core::extensions::ExtensionManifest;
183/// ```
184pub struct ExtensionManifest {
185    /// Stable, reverse-DNS id.
186    pub id: String,
187    /// Extension version.
188    pub version: String,
189    /// Display name.
190    pub name: String,
191    /// Host API range.
192    pub api: ApiRange,
193    /// Module path, relative to the manifest.
194    pub entry: String,
195    /// Optional `sha256:` checksum of the module.
196    pub checksum: Option<String>,
197    /// Optional signature over the module. A manager refuses a signed manifest unless the
198    /// application installed a verifier with `ExtensionManager::with_signature_verifier`.
199    pub signature: Option<String>,
200    /// Capabilities, in manifest spelling.
201    #[serde(default)]
202    pub capabilities: BTreeSet<String>,
203    /// Optional author.
204    pub author: Option<String>,
205    /// Optional description.
206    pub description: Option<String>,
207}
208
209impl ExtensionManifest {
210    /// Read and validate `extension.json` in `directory`.
211    ///
212    /// # Errors
213    /// When the file is missing, malformed, or the id/version/entry is invalid.
214    #[cfg(feature = "threads")]
215    pub fn load(directory: impl Into<PathBuf>) -> Result<(Self, PathBuf), ManifestError> {
216        let directory = directory.into();
217        let path = directory.join("extension.json");
218        let text = std::fs::read_to_string(&path).map_err(|error| ManifestError::Io(error.to_string()))?;
219        let manifest: Self = serde_json::from_str(&text).map_err(|error| ManifestError::Json(error.to_string()))?;
220        manifest.validate()?;
221        Ok((manifest, directory))
222    }
223
224    /// Validate the id, version, entry, API range, and capabilities.
225    ///
226    /// # Errors
227    /// When a field is invalid.
228    pub fn validate(&self) -> Result<(), ManifestError> {
229        // The id names directories and log lines: keep it to a plain reverse-DNS spelling.
230        if self.id.is_empty()
231            || self.id.len() > 128
232            || self.id.starts_with('.')
233            || !self
234                .id
235                .bytes()
236                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
237        {
238            return Err(ManifestError::Id(self.id.clone()));
239        }
240        if self.version.split('.').count() < 2 || self.version.split('.').any(|part| part.parse::<u64>().is_err()) {
241            return Err(ManifestError::Version(self.version.clone()));
242        }
243        if !entry_is_safe(&self.entry) {
244            return Err(ManifestError::Entry(self.entry.clone()));
245        }
246        if !self.api.allows(crate::extensions::HOST_API_VERSION) {
247            return Err(ManifestError::Api {
248                min: self.api.min.clone(),
249                max: self.api.max.clone(),
250            });
251        }
252        for capability in &self.capabilities {
253            Capability::parse(capability)?;
254        }
255        Ok(())
256    }
257
258    /// Capabilities as parsed values.
259    ///
260    /// # Errors
261    /// When a spelling is invalid.
262    pub fn parsed_capabilities(&self) -> Result<BTreeSet<Capability>, ManifestError> {
263        self.capabilities.iter().map(|text| Capability::parse(text)).collect()
264    }
265
266    /// The module path.
267    pub fn module_path(&self, directory: &std::path::Path) -> PathBuf {
268        directory.join(&self.entry)
269    }
270}
271
272/// Why a manifest is invalid.
273#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
274#[non_exhaustive]
275/// # Example
276///
277/// ```
278/// use crisol_core::extensions::ManifestError;
279/// ```
280pub enum ManifestError {
281    /// I/O failed.
282    #[error("{0}")]
283    Io(String),
284    /// JSON failed.
285    #[error("{0}")]
286    Json(String),
287    /// The id is invalid.
288    #[error("invalid extension id `{0}`")]
289    Id(String),
290    /// The version is invalid.
291    #[error("invalid extension version `{0}`")]
292    Version(String),
293    /// The entry path escapes the directory.
294    #[error("invalid entry `{0}`")]
295    Entry(String),
296    /// The host API range does not include this host.
297    #[error("host API {host} is outside {min}..{max}", host = crate::extensions::HOST_API_VERSION)]
298    Api {
299        /// The minimum accepted host version.
300        min: String,
301        /// The maximum accepted host version, exclusive.
302        max: String,
303    },
304    /// A capability spelling is unknown.
305    #[error("unknown capability `{0}`")]
306    Capability(String),
307}