1use crate::error::{Error, Result, invalid};
10use base64::Engine;
11use base64::engine::general_purpose::STANDARD as B64;
12use libp2p_identity::{Keypair, PublicKey};
13use serde::{Deserialize, Serialize};
14
15pub const MANIFEST_DOMAIN: &[u8] = b"weirdnet-ext/manifest/v1\n";
17pub const FORMAT: u32 = 1;
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
22pub struct Capability {
23 pub name: String,
25 #[serde(default, skip_serializing_if = "Vec::is_empty")]
27 pub patterns: Vec<String>,
28}
29
30impl Capability {
31 pub fn new(name: impl Into<String>) -> Self {
33 Self { name: name.into(), patterns: Vec::new() }
34 }
35
36 pub fn with_patterns(name: impl Into<String>, patterns: &[&str]) -> Self {
38 Self { name: name.into(), patterns: patterns.iter().map(|p| p.to_string()).collect() }
39 }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Native {
45 pub target: String,
47 pub path: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct FileEntry {
54 pub path: String,
56 pub size: u64,
58 pub blake3: String,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct Manifest {
65 pub format: u32,
67 pub id: String,
69 pub name: String,
71 pub version: String,
73 pub author: String,
75 pub author_key: String,
77 pub api_version: u32,
79 #[serde(default)]
81 pub capabilities: Vec<Capability>,
82 #[serde(default)]
84 pub sites: Vec<String>,
85 #[serde(default)]
87 pub native: Vec<Native>,
88 #[serde(default)]
90 pub wasm: Option<String>,
91 pub files: Vec<FileEntry>,
93}
94
95pub fn current_target() -> String {
97 format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
98}
99
100pub fn user_id(key: &PublicKey) -> String {
103 use sha2::Digest;
104 hex::encode(&sha2::Sha256::digest(key.encode_protobuf())[..16])
105}
106
107pub fn check_path(p: &str) -> Result<()> {
109 let ok = !p.is_empty()
110 && p.len() <= 512
111 && !p.starts_with('/')
112 && !p.contains('\\')
113 && p.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
114 && !p.chars().any(|c| c.is_control());
115 if ok { Ok(()) } else { Err(invalid(format!("bad path {p:?}"))) }
116}
117
118fn check_id(id: &str) -> Result<()> {
119 let ok = (3..=128).contains(&id.len())
120 && id.bytes().all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_'))
121 && !id.starts_with('.')
122 && !id.contains("..");
123 if ok { Ok(()) } else { Err(invalid(format!("bad extension id {id:?}"))) }
124}
125
126impl Manifest {
127 pub fn public_key(&self) -> Result<PublicKey> {
129 let b = B64.decode(&self.author_key).map_err(|_| invalid("bad author key"))?;
130 PublicKey::try_decode_protobuf(&b).map_err(|_| invalid("bad author key"))
131 }
132
133 pub fn semver(&self) -> Result<semver::Version> {
135 semver::Version::parse(&self.version).map_err(|_| invalid(format!("bad version {:?}", self.version)))
136 }
137
138 pub fn native_for(&self, target: &str) -> Option<&Native> {
140 self.native.iter().find(|n| n.target == target)
141 }
142
143 pub fn check(&self) -> Result<()> {
145 if self.format != FORMAT {
146 return Err(invalid(format!("manifest format {} (this host reads {FORMAT})", self.format)));
147 }
148 check_id(&self.id)?;
149 self.semver()?;
150 if self.name.trim().is_empty() || self.name.len() > 128 {
151 return Err(invalid("bad name"));
152 }
153 let key = self.public_key()?;
154 if user_id(&key) != self.author {
155 return Err(Error::Verify("the author id is not the author key's".into()));
156 }
157 let mut seen = std::collections::HashSet::new();
158 for f in &self.files {
159 check_path(&f.path)?;
160 if f.path == "manifest.json" || f.path == "manifest.sig" {
161 return Err(invalid("reserved file name"));
162 }
163 if !seen.insert(f.path.as_str()) {
164 return Err(invalid(format!("{} is listed twice", f.path)));
165 }
166 if f.blake3.len() != 64 || !f.blake3.bytes().all(|b| b.is_ascii_hexdigit()) {
167 return Err(invalid(format!("bad hash for {}", f.path)));
168 }
169 }
170 for n in &self.native {
171 if !seen.contains(n.path.as_str()) {
172 return Err(invalid(format!("binary {} is not in the files", n.path)));
173 }
174 }
175 if let Some(w) = &self.wasm
176 && !seen.contains(w.as_str())
177 {
178 return Err(invalid(format!("{w} is not in the files")));
179 }
180 for c in &self.capabilities {
181 if c.name.is_empty()
182 || c.name.len() > 64
183 || !c.name.bytes().all(|b| b.is_ascii_lowercase() || b == b'.' || b == b'_' || b.is_ascii_digit())
184 {
185 return Err(invalid(format!("bad capability {:?}", c.name)));
186 }
187 }
188 Ok(())
189 }
190
191 pub fn set_author(&mut self, key: &PublicKey) {
193 self.author = user_id(key);
194 self.author_key = B64.encode(key.encode_protobuf());
195 }
196}
197
198pub fn sign(key: &Keypair, manifest_json: &[u8]) -> Result<Vec<u8>> {
200 key.sign(&[MANIFEST_DOMAIN, manifest_json].concat()).map_err(|e| invalid(format!("signing: {e}")))
201}
202
203pub fn verify(manifest_json: &[u8], sig: &[u8]) -> Result<Manifest> {
205 let m: Manifest = serde_json::from_slice(manifest_json).map_err(|e| invalid(format!("manifest.json: {e}")))?;
206 let key = m.public_key()?;
207 if !key.verify(&[MANIFEST_DOMAIN, manifest_json].concat(), sig) {
208 return Err(Error::Verify("the manifest signature does not check out".into()));
209 }
210 m.check()?;
211 Ok(m)
212}