1use std::collections::HashSet;
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use super::Descriptor;
9#[cfg(feature = "schema")]
10use super::descriptor::PLAIN_TEXT_PATTERN;
11use super::descriptor::plain_text;
12
13pub const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
15pub const MAX_PLUGIN_ARTIFACTS: usize = 64;
17pub const MAX_PLUGIN_RESOURCES: usize = 64;
19pub const MAX_PLUGIN_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
21pub const MAX_PLUGIN_RESOURCE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
23pub const MAX_PLUGIN_RESOURCES_TOTAL_BYTES: u64 = 4 * 1024 * 1024 * 1024;
25
26#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
28#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
29#[serde(deny_unknown_fields)]
30pub struct PluginManifest {
31 pub id: String,
33 pub version: String,
35 #[cfg_attr(feature = "schema", schemars(extend("const" = alpha2_plugin_abi::ABI)))]
37 pub abi: String,
38 pub kind: PluginKind,
40 #[cfg_attr(feature = "schema", schemars(length(min = 1)))]
42 pub artifacts: Vec<PluginArtifact>,
43 #[serde(default, skip_serializing_if = "Vec::is_empty")]
45 pub resources: Vec<PluginResource>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub about: Option<PluginAbout>,
49 pub descriptor: Descriptor,
51}
52
53pub const MAX_ABOUT_NAME_CHARS: usize = 80;
55pub const MAX_ABOUT_SUMMARY_CHARS: usize = 400;
57pub const MAX_ABOUT_AUTHOR_CHARS: usize = 80;
59pub const MAX_ABOUT_HOMEPAGE_CHARS: usize = 2048;
61pub const MAX_ABOUT_LICENSE_CHARS: usize = 256;
63
64#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
66#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
67#[serde(deny_unknown_fields)]
68pub struct PluginAbout {
69 #[cfg_attr(
71 feature = "schema",
72 schemars(length(min = 1, max = MAX_ABOUT_NAME_CHARS), regex(pattern = PLAIN_TEXT_PATTERN))
73 )]
74 pub name: String,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
77 #[cfg_attr(
78 feature = "schema",
79 schemars(length(max = MAX_ABOUT_SUMMARY_CHARS), regex(pattern = PLAIN_TEXT_PATTERN))
80 )]
81 pub summary: Option<String>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 #[cfg_attr(
85 feature = "schema",
86 schemars(length(max = MAX_ABOUT_AUTHOR_CHARS), regex(pattern = PLAIN_TEXT_PATTERN))
87 )]
88 pub author: Option<String>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
91 #[cfg_attr(
92 feature = "schema",
93 schemars(length(max = MAX_ABOUT_HOMEPAGE_CHARS), regex(pattern = HOMEPAGE_PATTERN))
94 )]
95 pub homepage: Option<String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
98 #[cfg_attr(
99 feature = "schema",
100 schemars(length(max = MAX_ABOUT_LICENSE_CHARS), regex(pattern = LICENSE_PATTERN))
101 )]
102 pub license: Option<String>,
103}
104
105#[cfg(feature = "schema")]
106const HOMEPAGE_PATTERN: &str = "^https://[!-~]+$";
107#[cfg(feature = "schema")]
108const LICENSE_PATTERN: &str = r"^[A-Za-z0-9.+:() -]+$";
109
110impl PluginAbout {
111 fn validate(&self) -> Result<(), String> {
112 let text = |field: &str, value: &str, min: usize, max: usize| {
113 if plain_text(value, min, max) {
114 Ok(())
115 } else {
116 Err(format!(
117 "about.{field} is not {min} to {max} characters without control characters"
118 ))
119 }
120 };
121 text("name", &self.name, 1, MAX_ABOUT_NAME_CHARS)?;
122 if let Some(summary) = &self.summary {
123 text("summary", summary, 0, MAX_ABOUT_SUMMARY_CHARS)?;
124 }
125 if let Some(author) = &self.author {
126 text("author", author, 0, MAX_ABOUT_AUTHOR_CHARS)?;
127 }
128 if let Some(homepage) = &self.homepage {
129 let rest = homepage.strip_prefix("https://").unwrap_or_default();
130 if homepage.len() > MAX_ABOUT_HOMEPAGE_CHARS
131 || rest.is_empty()
132 || !rest.bytes().all(|byte| matches!(byte, b'!'..=b'~'))
133 {
134 return Err(format!(
135 "about.homepage is not an https: URL of printable ASCII, at most \
136 {MAX_ABOUT_HOMEPAGE_CHARS} characters"
137 ));
138 }
139 }
140 if let Some(license) = &self.license
141 && (license.len() > MAX_ABOUT_LICENSE_CHARS || !spdx_expression(license))
142 {
143 return Err(format!(
144 "about.license {license:?} is not an SPDX license expression of at most \
145 {MAX_ABOUT_LICENSE_CHARS} characters"
146 ));
147 }
148 Ok(())
149 }
150}
151
152fn spdx_expression(text: &str) -> bool {
154 let spaced = text.replace('(', " ( ").replace(')', " ) ");
155 let tokens = spaced.split_ascii_whitespace().collect::<Vec<_>>();
156 let mut at = 0;
157 spdx_or(&tokens, &mut at, 0) && at == tokens.len()
158}
159
160const SPDX_MAX_NESTING: usize = 32;
161
162fn spdx_id(token: &str) -> bool {
163 !matches!(token, "AND" | "OR" | "WITH" | "(" | ")")
164 && !token.is_empty()
165 && token
166 .bytes()
167 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b':'))
168}
169
170fn spdx_or(tokens: &[&str], at: &mut usize, depth: usize) -> bool {
171 spdx_and(tokens, at, depth)
172 && loop {
173 if tokens.get(*at) != Some(&"OR") {
174 break true;
175 }
176 *at += 1;
177 if !spdx_and(tokens, at, depth) {
178 break false;
179 }
180 }
181}
182
183fn spdx_and(tokens: &[&str], at: &mut usize, depth: usize) -> bool {
184 spdx_term(tokens, at, depth)
185 && loop {
186 if tokens.get(*at) != Some(&"AND") {
187 break true;
188 }
189 *at += 1;
190 if !spdx_term(tokens, at, depth) {
191 break false;
192 }
193 }
194}
195
196fn spdx_term(tokens: &[&str], at: &mut usize, depth: usize) -> bool {
197 let Some(&token) = tokens.get(*at) else {
198 return false;
199 };
200 *at += 1;
201 if token == "(" {
202 if depth >= SPDX_MAX_NESTING
203 || !spdx_or(tokens, at, depth + 1)
204 || tokens.get(*at) != Some(&")")
205 {
206 return false;
207 }
208 *at += 1;
209 return true;
210 }
211 if !spdx_id(token.strip_suffix('+').unwrap_or(token)) {
212 return false;
213 }
214 if tokens.get(*at) == Some(&"WITH") {
215 *at += 1;
216 let exception = tokens.get(*at).is_some_and(|token| spdx_id(token));
217 *at += 1;
218 return exception;
219 }
220 true
221}
222
223#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
225#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
226#[serde(rename_all = "snake_case")]
227pub enum PluginKind {
228 Extractor,
230}
231
232#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
234#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
235#[serde(deny_unknown_fields)]
236pub struct PluginArtifact {
237 pub target: String,
239 #[serde(rename = "type")]
241 pub kind: ArtifactKind,
242 pub url: String,
244 #[cfg_attr(feature = "schema", schemars(regex(pattern = r"^[0-9a-f]{64}$")))]
246 pub sha256: String,
247 #[cfg_attr(feature = "schema", schemars(range(max = MAX_PLUGIN_ARTIFACT_BYTES)))]
249 pub bytes: u64,
250}
251
252#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
254#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
255#[serde(rename_all = "snake_case")]
256pub enum ArtifactKind {
257 Wasm,
259 Cdylib,
261 Staticlib,
263}
264
265pub const MAX_PLUGIN_SLOTS: usize = 16;
267pub const MAX_SLOT_ACCEPT: usize = 16;
269pub const MAX_SLOT_ACCEPT_BYTES: usize = 64;
271pub const MAX_SLOT_NAME_BYTES: usize = 64;
273
274#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
276#[serde(try_from = "ResourceEntry", into = "ResourceEntry")]
277pub struct PluginResource {
278 pub name: String,
280 pub source: ResourceSource,
282}
283
284#[derive(Clone, Debug, PartialEq)]
286pub enum ResourceSource {
287 Pinned(PinnedResource),
289 Supplied(SuppliedSlot),
291}
292
293#[derive(Clone, Debug, PartialEq, Eq)]
295pub struct PinnedResource {
296 pub url: String,
298 pub sha256: String,
300 pub bytes: u64,
302}
303
304#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
306#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
307#[serde(deny_unknown_fields)]
308pub struct SuppliedSlot {
309 pub shape: SlotShape,
311 #[serde(default = "required_default", skip_serializing_if = "is_true")]
313 #[cfg_attr(feature = "schema", schemars(extend("default" = true)))]
314 pub required: bool,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
317 #[cfg_attr(feature = "schema", schemars(range(min = 1)))]
318 pub max_bytes: Option<u64>,
319 #[serde(default, skip_serializing_if = "Vec::is_empty")]
321 #[cfg_attr(
322 feature = "schema",
323 schemars(length(max = MAX_SLOT_ACCEPT), inner(length(min = 1, max = MAX_SLOT_ACCEPT_BYTES)))
324 )]
325 pub accept: Vec<String>,
326}
327
328const fn required_default() -> bool {
329 true
330}
331
332#[expect(
333 clippy::trivially_copy_pass_by_ref,
334 reason = "serde passes a reference"
335)]
336const fn is_true(value: &bool) -> bool {
337 *value
338}
339
340#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
342#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
343#[serde(rename_all = "snake_case")]
344pub enum SlotShape {
345 File,
347 Directory,
349}
350
351impl PluginResource {
352 #[must_use]
354 pub const fn pinned(&self) -> Option<&PinnedResource> {
355 match &self.source {
356 ResourceSource::Pinned(pinned) => Some(pinned),
357 ResourceSource::Supplied(_) => None,
358 }
359 }
360
361 #[must_use]
363 pub const fn slot(&self) -> Option<&SuppliedSlot> {
364 match &self.source {
365 ResourceSource::Pinned(_) => None,
366 ResourceSource::Supplied(slot) => Some(slot),
367 }
368 }
369}
370
371#[derive(Deserialize, Serialize)]
373#[serde(deny_unknown_fields)]
374struct ResourceEntry {
375 name: String,
376 #[serde(default, skip_serializing_if = "Option::is_none")]
377 url: Option<String>,
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 sha256: Option<String>,
380 #[serde(default, skip_serializing_if = "Option::is_none")]
381 bytes: Option<u64>,
382 #[serde(default, skip_serializing_if = "Option::is_none")]
383 supplied: Option<SuppliedSlot>,
384}
385
386impl TryFrom<ResourceEntry> for PluginResource {
387 type Error = String;
388
389 fn try_from(entry: ResourceEntry) -> Result<Self, String> {
390 let ResourceEntry {
391 name,
392 url,
393 sha256,
394 bytes,
395 supplied,
396 } = entry;
397 let source = match (url, sha256, bytes, supplied) {
398 (Some(url), Some(sha256), Some(bytes), None) => {
399 ResourceSource::Pinned(PinnedResource { url, sha256, bytes })
400 }
401 (None, None, None, Some(slot)) => ResourceSource::Supplied(slot),
402 (None, None, None, None) => {
403 return Err(format!(
404 "resource {name:?} has neither url, sha256 and bytes nor supplied"
405 ));
406 }
407 (_, _, _, Some(_)) => {
408 return Err(format!(
409 "resource {name:?} has supplied and a pin; a resource is one or the other"
410 ));
411 }
412 _ => {
413 return Err(format!(
414 "resource {name:?} needs all of url, sha256 and bytes"
415 ));
416 }
417 };
418 Ok(Self { name, source })
419 }
420}
421
422impl From<PluginResource> for ResourceEntry {
423 fn from(resource: PluginResource) -> Self {
424 let mut entry = Self {
425 name: resource.name,
426 url: None,
427 sha256: None,
428 bytes: None,
429 supplied: None,
430 };
431 match resource.source {
432 ResourceSource::Pinned(PinnedResource { url, sha256, bytes }) => {
433 entry.url = Some(url);
434 entry.sha256 = Some(sha256);
435 entry.bytes = Some(bytes);
436 }
437 ResourceSource::Supplied(slot) => entry.supplied = Some(slot),
438 }
439 entry
440 }
441}
442
443#[cfg(feature = "schema")]
444mod resource_schema {
445 use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
446
447 use super::{MAX_PLUGIN_RESOURCE_BYTES, SuppliedSlot};
448
449 #[derive(JsonSchema)]
451 #[schemars(deny_unknown_fields, rename = "PinnedResource")]
452 #[expect(dead_code, reason = "a shape for the schema alone")]
453 struct PinnedResourceEntry {
454 #[schemars(length(min = 1))]
456 name: String,
457 url: String,
459 #[schemars(regex(pattern = r"^[0-9a-f]{64}$"))]
461 sha256: String,
462 #[schemars(range(max = MAX_PLUGIN_RESOURCE_BYTES))]
464 bytes: u64,
465 }
466
467 #[derive(JsonSchema)]
469 #[schemars(deny_unknown_fields, rename = "SuppliedResource")]
470 #[expect(dead_code, reason = "a shape for the schema alone")]
471 struct SuppliedResourceEntry {
472 #[schemars(regex(pattern = r"^[A-Za-z0-9_-][A-Za-z0-9._-]{0,63}$"))]
474 name: String,
475 supplied: SuppliedSlot,
477 }
478
479 impl JsonSchema for super::PluginResource {
480 fn schema_name() -> std::borrow::Cow<'static, str> {
481 "PluginResource".into()
482 }
483
484 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
485 json_schema!({
486 "description": "A file a plugin reads: pinned by the manifest, or a slot the \
487 caller fills at load time.",
488 "oneOf": [
489 generator.subschema_for::<PinnedResourceEntry>(),
490 generator.subschema_for::<SuppliedResourceEntry>(),
491 ]
492 })
493 }
494 }
495}
496
497#[must_use]
499pub fn is_slot_name(name: &str) -> bool {
500 let allowed = |byte: u8| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-');
501 name.len() <= MAX_SLOT_NAME_BYTES
502 && name.bytes().next().is_some_and(allowed)
503 && name.bytes().all(|byte| allowed(byte) || byte == b'.')
504}
505
506#[derive(Clone, Debug, Eq, PartialEq)]
508#[non_exhaustive]
509pub enum ManifestError {
510 UnsupportedAbi(String),
512 Invalid(String),
514}
515
516impl fmt::Display for ManifestError {
517 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
518 match self {
519 Self::UnsupportedAbi(abi) => write!(
520 formatter,
521 "the plugin needs ABI {abi}; this build implements {}",
522 alpha2_plugin_abi::ABI
523 ),
524 Self::Invalid(why) => write!(formatter, "invalid plugin manifest: {why}"),
525 }
526 }
527}
528
529impl std::error::Error for ManifestError {}
530
531impl PluginManifest {
532 pub fn from_json(text: &str) -> Result<Self, ManifestError> {
538 if text.len() > MAX_MANIFEST_BYTES {
539 return Err(ManifestError::Invalid(format!(
540 "longer than {MAX_MANIFEST_BYTES} bytes"
541 )));
542 }
543 let value: serde_json::Value = serde_json::from_str(text)
544 .map_err(|error| ManifestError::Invalid(error.to_string()))?;
545 match value.get("abi").and_then(serde_json::Value::as_str) {
546 Some(abi) if abi != alpha2_plugin_abi::ABI => {
547 return Err(ManifestError::UnsupportedAbi(abi.to_owned()));
548 }
549 _ => {}
550 }
551 let manifest: Self = serde_json::from_value(value)
552 .map_err(|error| ManifestError::Invalid(error.to_string()))?;
553 manifest.validate().map_err(ManifestError::Invalid)?;
554 Ok(manifest)
555 }
556
557 fn validate(&self) -> Result<(), String> {
558 if self.id != self.descriptor.id {
559 return Err(format!(
560 "id {} differs from the descriptor's {}",
561 self.id, self.descriptor.id
562 ));
563 }
564 if !semver(&self.version) {
565 return Err(format!(
566 "version {} is not a semantic version",
567 self.version
568 ));
569 }
570 super::session::validate_descriptor(&self.descriptor).map_err(|error| error.to_string())?;
571 if self.artifacts.is_empty() || self.artifacts.len() > MAX_PLUGIN_ARTIFACTS {
572 return Err(format!("needs 1 to {MAX_PLUGIN_ARTIFACTS} artifacts"));
573 }
574 if self.resources.len() > MAX_PLUGIN_RESOURCES {
575 return Err(format!("lists more than {MAX_PLUGIN_RESOURCES} resources"));
576 }
577 let mut targets = HashSet::new();
578 for artifact in &self.artifacts {
579 if artifact.target.is_empty() || !targets.insert((&artifact.target, artifact.kind)) {
580 return Err(format!(
581 "artifact target {:?} is empty or listed twice for one type",
582 artifact.target
583 ));
584 }
585 if (artifact.target == WASM_TARGET) != (artifact.kind == ArtifactKind::Wasm) {
586 return Err(format!(
587 "artifact {}: only the wasm32 target is a wasm module",
588 artifact.url
589 ));
590 }
591 check_file(&artifact.url, &artifact.sha256)?;
592 if artifact.bytes > MAX_PLUGIN_ARTIFACT_BYTES {
593 return Err(format!(
594 "artifact {} is longer than {MAX_PLUGIN_ARTIFACT_BYTES} bytes",
595 artifact.url
596 ));
597 }
598 }
599 self.validate_resources()?;
600 self.about.as_ref().map_or(Ok(()), PluginAbout::validate)
601 }
602
603 fn validate_resources(&self) -> Result<(), String> {
604 let mut names = HashSet::new();
605 let mut directories = Vec::new();
606 let (mut slots, mut total) = (0_usize, 0_u64);
607 for resource in &self.resources {
608 if resource.name.is_empty() || !names.insert(&resource.name) {
609 return Err(format!(
610 "resource name {:?} is empty or repeated",
611 resource.name
612 ));
613 }
614 match &resource.source {
615 ResourceSource::Pinned(pinned) => {
616 check_file(&pinned.url, &pinned.sha256)?;
617 if pinned.bytes > MAX_PLUGIN_RESOURCE_BYTES {
618 return Err(format!(
619 "resource {} is longer than {MAX_PLUGIN_RESOURCE_BYTES} bytes",
620 resource.name
621 ));
622 }
623 total = total.saturating_add(pinned.bytes);
624 }
625 ResourceSource::Supplied(slot) => {
626 slots += 1;
627 check_slot(&resource.name, slot)?;
628 if slot.shape == SlotShape::Directory {
629 directories.push(format!("{}/", resource.name));
630 }
631 }
632 }
633 }
634 if slots > MAX_PLUGIN_SLOTS {
635 return Err(format!(
636 "declares more than {MAX_PLUGIN_SLOTS} resource slots"
637 ));
638 }
639 if let Some(resource) = self.resources.iter().find(|resource| {
640 resource.pinned().is_some()
641 && directories
642 .iter()
643 .any(|prefix| resource.name.starts_with(prefix.as_str()))
644 }) {
645 return Err(format!(
646 "pinned resource {} lies under a directory slot's names",
647 resource.name
648 ));
649 }
650 if total > MAX_PLUGIN_RESOURCES_TOTAL_BYTES {
651 return Err(format!(
652 "the pinned resources are longer than {MAX_PLUGIN_RESOURCES_TOTAL_BYTES} bytes \
653 together"
654 ));
655 }
656 Ok(())
657 }
658
659 #[must_use]
661 pub fn artifact(&self, target: &str, kind: ArtifactKind) -> Option<&PluginArtifact> {
662 self.artifacts
663 .iter()
664 .find(|artifact| artifact.target == target && artifact.kind == kind)
665 }
666}
667
668pub const WASM_TARGET: &str = "wasm32";
670
671#[derive(Clone, Copy, Debug, Eq, PartialEq)]
673pub enum Reference<'a> {
674 Relative(&'a str),
676 Https(&'a str),
678}
679
680fn scheme(url: &str) -> Option<&str> {
682 let (scheme, _) = url.split_once(':')?;
683 let valid = scheme.starts_with(|c: char| c.is_ascii_alphabetic())
684 && scheme
685 .chars()
686 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
687 valid.then_some(scheme)
688}
689
690pub fn reference(url: &str) -> Result<Reference<'_>, String> {
696 let refused = |why: &str| Err(format!("{url}: {why}"));
697 if url.is_empty() {
698 return Err("a URL is empty".to_owned());
699 }
700 match scheme(url) {
701 Some("https") => return Ok(Reference::Https(url)),
702 Some(scheme) if scheme.len() == 1 => {
703 return refused("a drive-prefixed path is not under the manifest");
704 }
705 Some(_) => return refused("only https: URLs and paths under the manifest are allowed"),
706 None => {}
707 }
708 if url.contains(['\\', '\0']) {
709 return refused("a path takes neither backslashes nor NUL");
710 }
711 if url.starts_with('/') {
712 return refused("an absolute path is not under the manifest");
713 }
714 let path = url.split(['?', '#']).next().unwrap_or_default();
715 let mut depth = 0_usize;
716 for segment in path.split('/') {
717 match segment {
718 "" | "." => {}
719 ".." => {
720 depth = depth
721 .checked_sub(1)
722 .ok_or_else(|| format!("{url}: the path climbs above the manifest"))?;
723 }
724 _ => depth += 1,
725 }
726 }
727 Ok(Reference::Relative(url))
728}
729
730fn check_slot(name: &str, slot: &SuppliedSlot) -> Result<(), String> {
731 if !is_slot_name(name) {
732 return Err(format!(
733 "slot name {name:?} is not 1 to {MAX_SLOT_NAME_BYTES} of A-Z, a-z, 0-9, '.', '_' and \
734 '-', not starting with '.'"
735 ));
736 }
737 if slot.max_bytes == Some(0) {
738 return Err(format!("slot {name}: max_bytes is 0"));
739 }
740 if slot.accept.len() > MAX_SLOT_ACCEPT {
741 return Err(format!(
742 "slot {name}: accept lists more than {MAX_SLOT_ACCEPT} suffixes"
743 ));
744 }
745 if let Some(suffix) = slot
746 .accept
747 .iter()
748 .find(|suffix| suffix.is_empty() || suffix.len() > MAX_SLOT_ACCEPT_BYTES)
749 {
750 return Err(format!(
751 "slot {name}: accept suffix {suffix:?} is empty or longer than \
752 {MAX_SLOT_ACCEPT_BYTES} bytes"
753 ));
754 }
755 Ok(())
756}
757
758fn check_file(url: &str, sha256: &str) -> Result<(), String> {
759 reference(url)?;
760 if sha256.len() != 64
761 || !sha256
762 .bytes()
763 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
764 {
765 return Err(format!(
766 "{url}: sha256 is not 64 lowercase hexadecimal digits"
767 ));
768 }
769 Ok(())
770}
771
772fn semver(version: &str) -> bool {
774 let (rest, build) = version
775 .split_once('+')
776 .map_or((version, None), |(a, b)| (a, Some(b)));
777 let (core, pre) = rest
778 .split_once('-')
779 .map_or((rest, None), |(a, b)| (a, Some(b)));
780 let identifiers = |text: &str| {
781 text.split('.').all(|part| {
782 !part.is_empty()
783 && part
784 .bytes()
785 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
786 })
787 };
788 let numbers = core.split('.').collect::<Vec<_>>();
789 numbers.len() == 3
790 && numbers.iter().all(|part| {
791 !part.is_empty()
792 && part.bytes().all(|byte| byte.is_ascii_digit())
793 && (part.len() == 1 || !part.starts_with('0'))
794 })
795 && pre.is_none_or(identifiers)
796 && build.is_none_or(identifiers)
797}
798
799#[cfg(feature = "schema")]
801#[must_use]
802pub fn plugin_manifest_json_schema() -> serde_json::Value {
803 let mut schema = schemars::generate::SchemaSettings::draft2020_12()
804 .for_deserialize()
805 .into_generator()
806 .into_root_schema_for::<PluginManifest>();
807 schema.insert(
808 "$id".to_owned(),
809 serde_json::Value::String(PLUGIN_MANIFEST_SCHEMA_ID.to_owned()),
810 );
811 schema.insert(
812 "title".to_owned(),
813 serde_json::Value::String(format!(
814 "alpha2 plugin manifest, ABI {}",
815 alpha2_plugin_abi::ABI
816 )),
817 );
818 let mut value = schema.to_value();
819 alpha2_model::finish_json_schema(&mut value);
820 value
821}
822
823pub const PLUGIN_MANIFEST_SCHEMA_ID: &str = "https://alpha2.sh/schema/plugin-manifest.v1.json";
825
826#[cfg(feature = "schema")]
828#[must_use]
829pub fn plugin_manifest_shape_json() -> serde_json::Value {
830 let mut value = plugin_manifest_json_schema();
831 alpha2_model::strip_json_schema_prose(&mut value);
832 value
833}