mars_schema/
plugin_metadata.rs1use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize};
6
7pub const SENTINEL_FILE: &str = ".mars-plugin.json";
8pub const SENTINEL_SCHEMA_VERSION: u32 = 1;
9
10#[derive(Clone, Copy)]
18pub struct GeneratedRootFile {
19 path: &'static str,
20 catalog_directory: Option<&'static str>,
23}
24
25pub const CLAUDE_ROOT_FILE: GeneratedRootFile = GeneratedRootFile {
26 path: ".claude-plugin/marketplace.json",
27 catalog_directory: Some(".claude-plugin"),
28};
29pub const OPENCODE_ROOT_FILE: GeneratedRootFile = GeneratedRootFile {
30 path: "package.json",
31 catalog_directory: None,
32};
33
34pub const GENERATED_ROOT_FILES: &[GeneratedRootFile] = &[CLAUDE_ROOT_FILE, OPENCODE_ROOT_FILE];
35
36impl GeneratedRootFile {
37 pub fn path(self) -> &'static str {
38 self.path
39 }
40
41 pub fn catalog_directory(self) -> Option<&'static str> {
42 self.catalog_directory
43 }
44}
45
46pub fn generated_root_paths() -> impl Iterator<Item = &'static str> {
48 GENERATED_ROOT_FILES
49 .iter()
50 .flat_map(|file| std::iter::once(file.path()).chain(file.catalog_directory()))
51}
52
53pub fn is_generated_root_file(path: &str) -> bool {
54 GENERATED_ROOT_FILES.iter().any(|file| file.path() == path)
55}
56
57pub fn is_generated_root_directory(path: &str) -> bool {
58 GENERATED_ROOT_FILES
59 .iter()
60 .any(|file| file.catalog_directory() == Some(path))
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct PluginSentinel {
65 pub schema_version: u32,
66 pub mars_version: String,
67 pub plugin_name: String,
68 pub version: String,
69 pub inputs_hash: String,
70 pub dependencies: BTreeMap<String, ResolvedDependency>,
71 pub files: BTreeMap<String, String>,
72 #[serde(default)]
73 pub root_files: BTreeMap<String, String>,
74 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
81 pub root_files_previous: BTreeMap<String, String>,
82 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
83 pub root_directories: BTreeSet<String>,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct ResolvedDependency {
88 #[serde(skip_serializing_if = "Option::is_none")]
89 pub version: Option<String>,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub commit: Option<String>,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
99pub enum SentinelError {
100 #[error(
101 "plugin sentinel schema version {recorded} is not supported (this build reads {})",
102 SENTINEL_SCHEMA_VERSION
103 )]
104 UnsupportedSchemaVersion { recorded: u32 },
105 #[error("plugin sentinel records an empty `{field}`")]
106 EmptyField { field: &'static str },
107 #[error("plugin sentinel dependency `{name}` records neither a version nor a commit")]
108 DependencyWithoutVersionOrCommit { name: String },
109 #[error("plugin sentinel records no generated files")]
110 NoFiles,
111 #[error("plugin sentinel entry `{path}` is not a relative path with a sha256 hash")]
112 InvalidEntry { path: String },
113 #[error("plugin sentinel records unsupported generated root file `{path}`")]
114 UnsupportedRootFile { path: String },
115 #[error("plugin sentinel records unsupported generated root directory `{path}`")]
116 UnsupportedRootDirectory { path: String },
117}
118
119impl PluginSentinel {
120 pub fn validate(&self) -> Result<(), SentinelError> {
122 if self.schema_version != SENTINEL_SCHEMA_VERSION {
123 return Err(SentinelError::UnsupportedSchemaVersion {
124 recorded: self.schema_version,
125 });
126 }
127 let required = [
128 ("mars_version", &self.mars_version),
129 ("plugin_name", &self.plugin_name),
130 ("version", &self.version),
131 ("inputs_hash", &self.inputs_hash),
132 ];
133 if let Some((field, _)) = required
134 .into_iter()
135 .find(|(_, value)| value.trim().is_empty())
136 {
137 return Err(SentinelError::EmptyField { field });
138 }
139 for (name, dependency) in &self.dependencies {
140 if !records_revision(&dependency.version) && !records_revision(&dependency.commit) {
141 return Err(SentinelError::DependencyWithoutVersionOrCommit { name: name.clone() });
142 }
143 }
144 if self.files.is_empty() {
145 return Err(SentinelError::NoFiles);
146 }
147 for (path, hash) in &self.files {
148 validate_entry(path, hash)?;
149 }
150 for (path, hash) in self.root_files.iter().chain(&self.root_files_previous) {
151 if !is_generated_root_file(path) {
152 return Err(SentinelError::UnsupportedRootFile { path: path.clone() });
153 }
154 validate_entry(path, hash)?;
155 }
156 if let Some(path) = self
157 .root_directories
158 .iter()
159 .find(|path| !is_generated_root_directory(path))
160 {
161 return Err(SentinelError::UnsupportedRootDirectory { path: path.clone() });
162 }
163 Ok(())
164 }
165
166 pub fn is_valid(&self) -> bool {
167 self.validate().is_ok()
168 }
169}
170
171pub fn is_valid_sentinel(bytes: &[u8]) -> bool {
173 serde_json::from_slice::<PluginSentinel>(bytes).is_ok_and(|sentinel| sentinel.is_valid())
174}
175
176fn validate_entry(path: &str, hash: &str) -> Result<(), SentinelError> {
177 if valid_entry(path, hash) {
178 return Ok(());
179 }
180 Err(SentinelError::InvalidEntry {
181 path: path.to_string(),
182 })
183}
184
185fn records_revision(value: &Option<String>) -> bool {
187 value
188 .as_deref()
189 .is_some_and(|value| !value.trim().is_empty())
190}
191
192pub fn valid_entry(path: &str, hash: &str) -> bool {
194 !path.is_empty()
195 && !is_absolute_on_any_platform(path)
196 && !path.split(['/', '\\']).any(|component| component == "..")
197 && is_sha256(hash)
198}
199
200fn is_absolute_on_any_platform(path: &str) -> bool {
203 path.starts_with(['/', '\\'])
204 || path.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
205 && path.as_bytes().get(1) == Some(&b':')
206}
207
208pub fn is_sha256(value: &str) -> bool {
209 value.strip_prefix("sha256:").is_some_and(|hex| {
210 hex.len() == 64
211 && hex
212 .bytes()
213 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
214 })
215}