Skip to main content

weirdnet_ext/
manifest.rs

1//! Extension manifests and their signatures.
2//!
3//! A manifest says what an extension is (id, name, version), who made it (the author's
4//! Weirdnet user id and public key), what it needs (host API version, capabilities, site
5//! patterns), and every file in the package with its size and BLAKE3 hash. The author's user
6//! key (Ed25519) signs the exact `manifest.json` bytes under the domain
7//! [`MANIFEST_DOMAIN`].
8
9use 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
15/// The signature domain of manifests.
16pub const MANIFEST_DOMAIN: &[u8] = b"weirdnet-ext/manifest/v1\n";
17/// The manifest format this crate writes and reads.
18pub const FORMAT: u32 = 1;
19
20/// A capability an extension asks for, optionally limited to patterns.
21#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
22pub struct Capability {
23    /// Such as `page.read`, `net.fetch`, `storage`.
24    pub name: String,
25    /// URL or site patterns (`*` matches any run of characters); empty means unrestricted.
26    #[serde(default, skip_serializing_if = "Vec::is_empty")]
27    pub patterns: Vec<String>,
28}
29
30impl Capability {
31    /// A capability without patterns.
32    pub fn new(name: impl Into<String>) -> Self {
33        Self { name: name.into(), patterns: Vec::new() }
34    }
35
36    /// A capability limited to `patterns`.
37    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/// A native binary for one target.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Native {
45    /// `os-arch`, such as `linux-x86_64` or `macos-aarch64` (see [`current_target`]).
46    pub target: String,
47    /// Path of the binary in the package's files.
48    pub path: String,
49}
50
51/// A file in the package.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct FileEntry {
54    /// Relative path (`/`-separated, no `..`).
55    pub path: String,
56    /// Size in bytes.
57    pub size: u64,
58    /// BLAKE3, hex.
59    pub blake3: String,
60}
61
62/// An extension manifest.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct Manifest {
65    /// [`FORMAT`].
66    pub format: u32,
67    /// Lowercase id, such as `com.example.reader` (`a-z0-9.-_`, 3 to 128 characters).
68    pub id: String,
69    /// Display name.
70    pub name: String,
71    /// Semantic version.
72    pub version: String,
73    /// The author's Weirdnet user id (32 hex characters).
74    pub author: String,
75    /// The author's public key (libp2p protobuf encoding, base64).
76    pub author_key: String,
77    /// The lowest host API version the extension needs.
78    pub api_version: u32,
79    /// Capabilities asked for.
80    #[serde(default)]
81    pub capabilities: Vec<Capability>,
82    /// Sites the extension works on.
83    #[serde(default)]
84    pub sites: Vec<String>,
85    /// Native binaries per target.
86    #[serde(default)]
87    pub native: Vec<Native>,
88    /// The WebAssembly component, if any (runs where native code can't).
89    #[serde(default)]
90    pub wasm: Option<String>,
91    /// Every file in the package.
92    pub files: Vec<FileEntry>,
93}
94
95/// The target this build runs on, as used in [`Native::target`].
96pub fn current_target() -> String {
97    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
98}
99
100/// The Weirdnet user id of a public key: 32 hex characters of the SHA-256 of its protobuf
101/// encoding (the same as `weirdnet_net::user::user_id`).
102pub fn user_id(key: &PublicKey) -> String {
103    use sha2::Digest;
104    hex::encode(&sha2::Sha256::digest(key.encode_protobuf())[..16])
105}
106
107/// Checks a relative package path.
108pub 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    /// The author's public key.
128    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    /// The parsed version.
134    pub fn semver(&self) -> Result<semver::Version> {
135        semver::Version::parse(&self.version).map_err(|_| invalid(format!("bad version {:?}", self.version)))
136    }
137
138    /// The binary for `target`, if the package has one.
139    pub fn native_for(&self, target: &str) -> Option<&Native> {
140        self.native.iter().find(|n| n.target == target)
141    }
142
143    /// Checks the shape: format, id, version, author, paths, and that binaries are listed.
144    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    /// Fills in the author from `key`.
192    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
198/// Signs manifest bytes with the author's user key.
199pub 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
203/// Verifies `sig` over `manifest_json`, parses and checks the manifest.
204pub 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}