1use cpa_core::gostr::GoStr;
5use sha2::{Digest, Sha256};
6
7use super::url;
8use super::version::normalize_version;
9use crate::go_struct;
10use crate::gojson;
11
12pub const DEFAULT_REGISTRY_URL: &str =
13 "https://raw.githubusercontent.com/router-for-me/CLIProxyAPI-Plugins-Store/main/registry.json";
14pub const DEFAULT_SOURCE_ID: &str = "official";
15pub const DEFAULT_SOURCE_NAME: &str = "Official";
16pub const SCHEMA_VERSION: isize = 1;
17pub const SCHEMA_VERSION_V2: isize = 2;
18pub const INSTALL_TYPE_GITHUB_RELEASE: &str = "github-release";
19pub const INSTALL_TYPE_DIRECT: &str = "direct";
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Source {
24 pub id: String,
25 pub name: String,
26 pub url: String,
27}
28
29go_struct! {
30 pub struct Artifact("pluginstore.Artifact") {
31 "goos" omitempty => goos: String,
32 "goarch" omitempty => goarch: String,
33 "url" omitempty => url: String,
34 "sha256" omitempty => sha256: String,
35 "size" omitempty => size: i64,
36 }
37}
38
39go_struct! {
40 pub struct InstallPlan("pluginstore.InstallPlan") {
41 "type" omitempty => install_type: String,
42 "artifacts" omitempty => artifacts: Vec<Artifact>,
43 }
44}
45
46go_struct! {
47 pub struct Version("pluginstore.Version") {
48 "version" => version: String,
49 "install" omitempty => install: InstallPlan,
50 }
51}
52
53go_struct! {
54 pub struct Plugin("pluginstore.Plugin") {
55 "id" => id: String,
56 "name" => name: String,
57 "description" => description: String,
58 "author" => author: String,
59 "version" => version: String,
60 "versions" omitempty => versions: Vec<Version>,
61 "repository" omitempty => repository: String,
62 "logo" omitempty => logo: String,
63 "homepage" omitempty => homepage: String,
64 "license" omitempty => license: String,
65 "tags" omitempty => tags: Vec<String>,
66 "install" omitempty => install: InstallPlan,
67 "auth_required" omitempty => auth_required: bool,
68 }
69}
70
71go_struct! {
72 pub struct Registry("pluginstore.Registry") {
73 "schema_version" => schema_version: isize,
74 "plugins" => plugins: Vec<Plugin>,
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
80pub struct Platform {
81 pub goos: String,
82 pub goarch: String,
83}
84
85pub fn default_source() -> Source {
86 Source {
87 id: DEFAULT_SOURCE_ID.into(),
88 name: DEFAULT_SOURCE_NAME.into(),
89 url: DEFAULT_REGISTRY_URL.into(),
90 }
91}
92
93pub fn normalize_sources(registry_urls: &[String]) -> Result<Vec<Source>, String> {
95 let mut out = vec![default_source()];
96 let mut seen_ids: Vec<(String, String)> = vec![(DEFAULT_SOURCE_ID.into(), DEFAULT_REGISTRY_URL.into())];
97 let mut seen_urls: Vec<String> = vec![DEFAULT_REGISTRY_URL.into()];
98 for raw in registry_urls {
99 let registry_url = raw.trim();
100 if registry_url.is_empty() || seen_urls.iter().any(|u| u == registry_url) {
101 continue;
102 }
103 let source = Source {
104 id: source_id(registry_url),
105 name: source_name(registry_url),
106 url: registry_url.into(),
107 };
108 if let Some((_, existing)) = seen_ids.iter().find(|(id, _)| *id == source.id) {
109 return Err(format!(
110 "plugin store source id collision for {} and {}",
111 cpa_common::gostr::quote(existing),
112 cpa_common::gostr::quote(registry_url)
113 ));
114 }
115 seen_ids.push((source.id.clone(), registry_url.into()));
116 seen_urls.push(registry_url.into());
117 out.push(source);
118 }
119 Ok(out)
120}
121
122pub fn source_id(registry_url: &str) -> String {
124 let sum = Sha256::digest(registry_url.trim().as_bytes());
125 let hex: String = sum.iter().map(|b| format!("{b:02x}")).collect();
126 format!("source-{}", &hex[..12])
127}
128
129pub fn source_name(registry_url: &str) -> String {
131 match url::parse(registry_url.trim()) {
132 Some(u) if !u.host.trim().is_empty() => u.host,
133 _ => registry_url.trim().into(),
134 }
135}
136
137pub fn parse_registry(data: &[u8]) -> Result<Registry, String> {
141 let mut registry: Registry = gojson::from_slice_first(data).map_err(|e| format!("decode registry: {e}"))?;
143 normalize_registry(&mut registry);
144 validate_registry(®istry)?;
145 Ok(registry)
146}
147
148fn normalize_registry(registry: &mut Registry) {
149 for plugin in &mut registry.plugins {
150 for field in [
151 &mut plugin.id,
152 &mut plugin.name,
153 &mut plugin.description,
154 &mut plugin.author,
155 &mut plugin.version,
156 &mut plugin.repository,
157 &mut plugin.logo,
158 &mut plugin.homepage,
159 &mut plugin.license,
160 ] {
161 *field = field.trim().to_owned();
162 }
163 plugin.install = normalize_install_plan(&plugin.install);
164 for version in &mut plugin.versions {
165 version.version = normalize_version(&version.version);
166 version.install = normalize_install_plan(&version.install);
167 }
168 for tag in &mut plugin.tags {
169 *tag = tag.trim().to_owned();
170 }
171 }
172}
173
174pub fn validate_registry(registry: &Registry) -> Result<(), String> {
176 if registry.schema_version != SCHEMA_VERSION && registry.schema_version != SCHEMA_VERSION_V2 {
177 return Err(format!("unsupported schema_version {}", registry.schema_version));
178 }
179 let mut seen: Vec<&str> = Vec::new();
180 for (index, plugin) in registry.plugins.iter().enumerate() {
181 if registry.schema_version == SCHEMA_VERSION && plugin_install_type(plugin) == INSTALL_TYPE_DIRECT {
182 return Err(format!(
183 "plugins[{index}]: direct install requires schema_version {SCHEMA_VERSION_V2}"
184 ));
185 }
186 validate_plugin(plugin).map_err(|e| format!("plugins[{index}]: {e}"))?;
187 let id = plugin.id.trim();
188 if seen.contains(&id) {
189 return Err(format!(
190 "plugins[{index}]: duplicate plugin id {}",
191 cpa_common::gostr::quote(id)
192 ));
193 }
194 seen.push(id);
195 }
196 Ok(())
197}
198
199pub fn validate_plugin(plugin: &Plugin) -> Result<(), String> {
203 let install_type = plugin_install_type(plugin);
204 let mut required = vec![
205 ("id", &plugin.id),
206 ("name", &plugin.name),
207 ("description", &plugin.description),
208 ("author", &plugin.author),
209 ];
210 if install_type == INSTALL_TYPE_GITHUB_RELEASE {
211 required.push(("repository", &plugin.repository));
212 }
213 if let Some((field, _)) = required.iter().find(|(_, v)| v.trim().is_empty()) {
214 return Err(format!("missing required field {field}"));
215 }
216 if !valid_plugin_id(plugin.id.trim()) {
217 return Err(format!("invalid plugin id {}", cpa_common::gostr::quote(&plugin.id)));
218 }
219 let version = plugin.version.trim();
220 if !version.is_empty() && !valid_plugin_version(version) {
221 return Err(format!(
222 "invalid plugin version {}",
223 cpa_common::gostr::quote(&plugin.version)
224 ));
225 }
226 match install_type.as_str() {
227 INSTALL_TYPE_GITHUB_RELEASE => github_repository_parts(&plugin.repository).map(|_| ()),
228 INSTALL_TYPE_DIRECT => {
229 if version.is_empty() {
230 return Err("missing required field version".into());
231 }
232 validate_install_plan(&plugin.install)?;
233 validate_plugin_versions(plugin)
234 }
235 _ => Err(format!(
236 "unsupported install type {}",
237 cpa_common::gostr::quote(&plugin.install.install_type)
238 )),
239 }
240}
241
242pub fn validate_plugin_versions(plugin: &Plugin) -> Result<(), String> {
244 let mut seen: Vec<String> = Vec::new();
245 let plugin_type = plugin_install_type(plugin);
246 for (index, version) in plugin.versions.iter().enumerate() {
247 let v = normalize_version(&version.version);
248 if !valid_plugin_version(&v) {
249 return Err(format!(
250 "versions[{index}]: invalid plugin version {}",
251 cpa_common::gostr::quote(&v)
252 ));
253 }
254 if seen.contains(&v) {
255 return Err(format!(
256 "versions[{index}]: duplicate plugin version {}",
257 cpa_common::gostr::quote(&v)
258 ));
259 }
260 seen.push(v);
261 let mut install = version.install.clone();
262 let mut install_type = install.install_type.trim().go_lower();
263 if install_type.is_empty() {
264 install_type = plugin_type.clone();
265 install.install_type = install_type.clone();
266 }
267 if install_type != plugin_type {
268 return Err(format!(
269 "versions[{index}]: install type {} does not match plugin install type {}",
270 cpa_common::gostr::quote(&install_type),
271 cpa_common::gostr::quote(&plugin_type)
272 ));
273 }
274 validate_install_plan(&install).map_err(|e| format!("versions[{index}]: {e}"))?;
275 }
276 Ok(())
277}
278
279pub fn plugin_install_type(plugin: &Plugin) -> String {
281 match plugin.install.install_type.trim().go_lower() {
282 t if t.is_empty() => INSTALL_TYPE_GITHUB_RELEASE.into(),
283 t => t,
284 }
285}
286
287pub fn normalize_install_plan(plan: &InstallPlan) -> InstallPlan {
289 let mut plan = plan.clone();
290 plan.install_type = plan.install_type.trim().go_lower();
291 for artifact in &mut plan.artifacts {
292 normalize_artifact(artifact);
293 }
294 plan
295}
296
297fn normalize_artifact(artifact: &mut Artifact) {
298 artifact.goos = normalize_goos(&artifact.goos);
299 artifact.goarch = normalize_goarch(&artifact.goarch);
300 artifact.url = artifact.url.trim().to_owned();
301 artifact.sha256 = artifact.sha256.trim().go_lower();
302}
303
304pub fn validate_install_plan(plan: &InstallPlan) -> Result<(), String> {
306 let plan = normalize_install_plan(plan);
307 if plan.install_type.is_empty() {
308 return Err("missing install type".into());
309 }
310 if plan.install_type != INSTALL_TYPE_DIRECT && plan.install_type != INSTALL_TYPE_GITHUB_RELEASE {
311 return Err(format!(
312 "unsupported install type {}",
313 cpa_common::gostr::quote(&plan.install_type)
314 ));
315 }
316 if plan.install_type != INSTALL_TYPE_DIRECT {
317 return Ok(());
318 }
319 if plan.artifacts.is_empty() {
320 return Err("direct install requires at least one artifact".into());
321 }
322 for (index, artifact) in plan.artifacts.iter().enumerate() {
323 validate_artifact(artifact).map_err(|e| format!("artifacts[{index}]: {e}"))?;
324 }
325 Ok(())
326}
327
328pub fn validate_artifact(artifact: &Artifact) -> Result<(), String> {
330 let mut artifact = artifact.clone();
331 normalize_artifact(&mut artifact);
332 if artifact.goos.is_empty() {
333 return Err("missing goos".into());
334 }
335 if artifact.goarch.is_empty() {
336 return Err("missing goarch".into());
337 }
338 if artifact.url.is_empty() {
339 return Err("missing url".into());
340 }
341 let parsed = match url::parse(&artifact.url) {
342 Some(u) if !u.scheme.is_empty() && !u.host.is_empty() => u,
343 _ => return Err("invalid artifact url".into()),
344 };
345 if parsed.scheme != "https" && parsed.scheme != "http" {
346 return Err("artifact url must use http or https".into());
347 }
348 if url::has_sensitive_query_parameter(&parsed) {
349 return Err("artifact url contains sensitive query parameter".into());
350 }
351 if artifact.sha256.is_empty() {
352 return Err("missing sha256".into());
353 }
354 if artifact.sha256.len() != 64 {
355 return Err("invalid sha256 length".into());
356 }
357 if let Some(bad) = artifact.sha256.bytes().position(|b| !b.is_ascii_hexdigit()) {
358 return Err(format!(
359 "invalid sha256: encoding/hex: invalid byte: {}",
360 go_rune_literal(char::from(artifact.sha256.as_bytes()[bad]))
361 ));
362 }
363 if artifact.size < 0 {
364 return Err("invalid size".into());
365 }
366 Ok(())
367}
368
369pub(super) fn go_rune_literal(c: char) -> String {
371 if c.is_control() {
372 format!("U+{:04X}", c as u32)
373 } else {
374 format!("U+{:04X} '{c}'", c as u32)
375 }
376}
377
378pub fn plugin_platforms(plugin: &Plugin) -> Vec<Platform> {
380 let mut out: Vec<Platform> = Vec::new();
381 for artifact in plugin_artifacts(plugin) {
382 let platform = Platform {
383 goos: artifact.goos,
384 goarch: artifact.goarch,
385 };
386 if platform.goos.is_empty() || platform.goarch.is_empty() || out.contains(&platform) {
387 continue;
388 }
389 out.push(platform);
390 }
391 out
392}
393
394pub fn plugin_artifacts(plugin: &Plugin) -> Vec<Artifact> {
396 if plugin_install_type(plugin) != INSTALL_TYPE_DIRECT {
397 return Vec::new();
398 }
399 let mut out = normalize_install_plan(&plugin.install).artifacts;
400 for version in &plugin.versions {
401 out.extend(normalize_install_plan(&version.install).artifacts);
402 }
403 out
404}
405
406pub(super) fn normalize_goos(goos: &str) -> String {
407 match goos.trim().go_lower().as_str() {
408 "mac" | "macos" | "osx" => "darwin".into(),
409 other => other.into(),
410 }
411}
412
413pub(super) fn normalize_goarch(goarch: &str) -> String {
414 match goarch.trim().go_lower().as_str() {
415 "x64" | "x86_64" => "amd64".into(),
416 "aarch64" => "arm64".into(),
417 other => other.into(),
418 }
419}
420
421pub(super) fn valid_plugin_version(version: &str) -> bool {
423 let b = version.as_bytes();
424 !b.is_empty()
425 && b[0].is_ascii_digit()
426 && b.iter()
427 .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'+' | b'-'))
428}
429
430pub(super) fn valid_plugin_id(id: &str) -> bool {
432 let b = id.as_bytes();
433 !b.is_empty()
434 && b.len() <= 128
435 && b[0].is_ascii_alphanumeric()
436 && b.iter()
437 .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
438}
439
440pub fn github_repository_parts(repository: &str) -> Result<(String, String), String> {
442 const SHAPE: &str = "repository must be https://github.com/{owner}/{repo}";
443 let parsed = url::parse_err(repository.trim()).map_err(|e| format!("invalid repository URL: {e}"))?;
444 if parsed.scheme != "https"
445 || parsed.host != "github.com"
446 || !parsed.raw_query.is_empty()
447 || !parsed.fragment.is_empty()
448 {
449 return Err(SHAPE.into());
450 }
451 let segments: Vec<&str> = parsed.raw_path.trim_matches('/').split('/').collect();
452 if segments.len() != 2 || segments[0].is_empty() || segments[1].is_empty() {
453 return Err(SHAPE.into());
454 }
455 let owner = url::path_unescape(segments[0]).map_err(|e| format!("invalid repository owner: {e}"))?;
456 let repo = url::path_unescape(segments[1]).map_err(|e| format!("invalid repository name: {e}"))?;
457 if repo.ends_with(".git") {
458 return Err(SHAPE.into());
459 }
460 Ok((owner, repo))
461}
462
463impl Registry {
464 pub fn plugin_by_id(&self, id: &str) -> Option<&Plugin> {
466 let id = id.trim();
467 self.plugins.iter().find(|p| p.id.trim() == id)
468 }
469}