Skip to main content

mars_schema/
plugin_metadata.rs

1//! Pure validation for Mars-generated plugin tree markers.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize};
6
7use crate::retired::RETIRED_TARGETS;
8
9pub const SENTINEL_FILE: &str = ".mars-plugin.json";
10pub const SENTINEL_SCHEMA_VERSION: u32 = 1;
11
12/// A package-root file Mars generates and owns.
13///
14/// `GENERATED_ROOT_FILES` is the only list of them: publishing excludes these
15/// paths from authored-source walks, and sentinel validation accepts only them.
16/// A tree row names one of these constants directly; `build::plugin::spec`'s test
17/// keeps the tree rows and this list in agreement, so a tree cannot generate a
18/// root file the list does not cover.
19#[derive(Clone, Copy)]
20pub struct GeneratedRootFile {
21    path: &'static str,
22    /// The catalog directory holding a marketplace file; `None` for a package
23    /// manifest at the package root.
24    catalog_directory: Option<&'static str>,
25}
26
27pub const CLAUDE_ROOT_FILE: GeneratedRootFile = GeneratedRootFile {
28    path: ".claude-plugin/marketplace.json",
29    catalog_directory: Some(".claude-plugin"),
30};
31pub const OPENCODE_ROOT_FILE: GeneratedRootFile = GeneratedRootFile {
32    path: "package.json",
33    catalog_directory: None,
34};
35
36pub const GENERATED_ROOT_FILES: &[GeneratedRootFile] = &[CLAUDE_ROOT_FILE, OPENCODE_ROOT_FILE];
37
38impl GeneratedRootFile {
39    pub fn path(self) -> &'static str {
40        self.path
41    }
42
43    pub fn catalog_directory(self) -> Option<&'static str> {
44        self.catalog_directory
45    }
46}
47
48/// Every package-root path Mars generates: the root files and their catalog directories.
49pub fn generated_root_paths() -> impl Iterator<Item = &'static str> {
50    GENERATED_ROOT_FILES
51        .iter()
52        .flat_map(|file| std::iter::once(file.path()).chain(file.catalog_directory()))
53}
54
55/// A root file this build generates, or one a retired target's plugin tree generated: a sentinel
56/// an older Mars wrote still records it, and the rebuild deletes it.
57pub fn is_generated_root_file(path: &str) -> bool {
58    GENERATED_ROOT_FILES.iter().any(|file| file.path() == path)
59        || RETIRED_TARGETS
60            .iter()
61            .any(|target| target.plugin_root_file == path)
62}
63
64/// The directory holding the generated root file at `path`, if it sits in one.
65pub fn catalog_directory_of(path: &str) -> Option<&'static str> {
66    GENERATED_ROOT_FILES
67        .iter()
68        .find(|file| file.path() == path)
69        .and_then(|file| file.catalog_directory())
70        .or_else(|| {
71            RETIRED_TARGETS
72                .iter()
73                .find(|target| target.plugin_root_file == path)
74                .map(|target| target.plugin_catalog_directory)
75        })
76}
77
78pub fn is_generated_root_directory(path: &str) -> bool {
79    GENERATED_ROOT_FILES
80        .iter()
81        .any(|file| file.catalog_directory() == Some(path))
82        || RETIRED_TARGETS
83            .iter()
84            .any(|target| target.plugin_catalog_directory == path)
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct PluginSentinel {
89    pub schema_version: u32,
90    pub mars_version: String,
91    pub plugin_name: String,
92    pub version: String,
93    pub inputs_hash: String,
94    pub dependencies: BTreeMap<String, ResolvedDependency>,
95    pub files: BTreeMap<String, String>,
96    #[serde(default)]
97    pub root_files: BTreeMap<String, String>,
98    /// Root-file hashes this build replaces or deletes: the Mars-owned bytes
99    /// still on disk if publication died before rewriting them. Publishing the
100    /// tree and the root files takes two steps; without this record the next
101    /// build could not tell its own earlier write from a hand edit. A path
102    /// counts only while its bytes still match, so a user's own file at a
103    /// retired path is never claimed.
104    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
105    pub root_files_previous: BTreeMap<String, String>,
106    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
107    pub root_directories: BTreeSet<String>,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct ResolvedDependency {
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub version: Option<String>,
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub commit: Option<String>,
116}
117
118/// Why a sentinel is not a marker for a generated plugin output directory.
119///
120/// Each variant names the value that failed, so a caller reports which entry is wrong
121/// without repeating the rule to find it.
122#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
123pub enum SentinelError {
124    #[error(
125        "plugin sentinel schema version {recorded} is not supported (this build reads {})",
126        SENTINEL_SCHEMA_VERSION
127    )]
128    UnsupportedSchemaVersion { recorded: u32 },
129    #[error("plugin sentinel records an empty `{field}`")]
130    EmptyField { field: &'static str },
131    #[error("plugin sentinel dependency `{name}` records neither a version nor a commit")]
132    DependencyWithoutVersionOrCommit { name: String },
133    #[error("plugin sentinel records no generated files")]
134    NoFiles,
135    #[error("plugin sentinel entry `{path}` is not a relative path with a sha256 hash")]
136    InvalidEntry { path: String },
137    #[error("plugin sentinel records unsupported generated root file `{path}`")]
138    UnsupportedRootFile { path: String },
139    #[error("plugin sentinel records unsupported generated root directory `{path}`")]
140    UnsupportedRootDirectory { path: String },
141}
142
143impl PluginSentinel {
144    /// Why this sentinel does not describe a tree this build may treat as generated output.
145    pub fn validate(&self) -> Result<(), SentinelError> {
146        if self.schema_version != SENTINEL_SCHEMA_VERSION {
147            return Err(SentinelError::UnsupportedSchemaVersion {
148                recorded: self.schema_version,
149            });
150        }
151        let required = [
152            ("mars_version", &self.mars_version),
153            ("plugin_name", &self.plugin_name),
154            ("version", &self.version),
155            ("inputs_hash", &self.inputs_hash),
156        ];
157        if let Some((field, _)) = required
158            .into_iter()
159            .find(|(_, value)| value.trim().is_empty())
160        {
161            return Err(SentinelError::EmptyField { field });
162        }
163        for (name, dependency) in &self.dependencies {
164            if !records_revision(&dependency.version) && !records_revision(&dependency.commit) {
165                return Err(SentinelError::DependencyWithoutVersionOrCommit { name: name.clone() });
166            }
167        }
168        if self.files.is_empty() {
169            return Err(SentinelError::NoFiles);
170        }
171        for (path, hash) in &self.files {
172            validate_entry(path, hash)?;
173        }
174        for (path, hash) in self.root_files.iter().chain(&self.root_files_previous) {
175            if !is_generated_root_file(path) {
176                return Err(SentinelError::UnsupportedRootFile { path: path.clone() });
177            }
178            validate_entry(path, hash)?;
179        }
180        if let Some(path) = self
181            .root_directories
182            .iter()
183            .find(|path| !is_generated_root_directory(path))
184        {
185            return Err(SentinelError::UnsupportedRootDirectory { path: path.clone() });
186        }
187        Ok(())
188    }
189
190    pub fn is_valid(&self) -> bool {
191        self.validate().is_ok()
192    }
193}
194
195/// Whether bytes are a valid marker for a generated plugin output directory.
196pub fn is_valid_sentinel(bytes: &[u8]) -> bool {
197    serde_json::from_slice::<PluginSentinel>(bytes).is_ok_and(|sentinel| sentinel.is_valid())
198}
199
200fn validate_entry(path: &str, hash: &str) -> Result<(), SentinelError> {
201    if valid_entry(path, hash) {
202        return Ok(());
203    }
204    Err(SentinelError::InvalidEntry {
205        path: path.to_string(),
206    })
207}
208
209/// Whether a dependency pins the build to something: a version, a commit, or both.
210fn records_revision(value: &Option<String>) -> bool {
211    value
212        .as_deref()
213        .is_some_and(|value| !value.trim().is_empty())
214}
215
216/// Whether a sentinel entry names a package-relative path and a sha256 hash.
217pub fn valid_entry(path: &str, hash: &str) -> bool {
218    !path.is_empty()
219        && !is_absolute_on_any_platform(path)
220        && !path.split(['/', '\\']).any(|component| component == "..")
221        && is_sha256(hash)
222}
223
224/// Reject roots of every target platform, not only the host's: a sentinel written
225/// on Windows must not read as relative when checked on Unix, or the reverse.
226fn is_absolute_on_any_platform(path: &str) -> bool {
227    path.starts_with(['/', '\\'])
228        || path.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
229            && path.as_bytes().get(1) == Some(&b':')
230}
231
232pub fn is_sha256(value: &str) -> bool {
233    value.strip_prefix("sha256:").is_some_and(|hex| {
234        hex.len() == 64
235            && hex
236                .bytes()
237                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
238    })
239}