use crate::error::{Error, Result, invalid};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as B64;
use libp2p_identity::{Keypair, PublicKey};
use serde::{Deserialize, Serialize};
pub const MANIFEST_DOMAIN: &[u8] = b"weirdnet-ext/manifest/v1\n";
pub const FORMAT: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Capability {
pub name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub patterns: Vec<String>,
}
impl Capability {
pub fn new(name: impl Into<String>) -> Self {
Self { name: name.into(), patterns: Vec::new() }
}
pub fn with_patterns(name: impl Into<String>, patterns: &[&str]) -> Self {
Self { name: name.into(), patterns: patterns.iter().map(|p| p.to_string()).collect() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Native {
pub target: String,
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileEntry {
pub path: String,
pub size: u64,
pub blake3: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
pub format: u32,
pub id: String,
pub name: String,
pub version: String,
pub author: String,
pub author_key: String,
pub api_version: u32,
#[serde(default)]
pub capabilities: Vec<Capability>,
#[serde(default)]
pub sites: Vec<String>,
#[serde(default)]
pub native: Vec<Native>,
#[serde(default)]
pub wasm: Option<String>,
pub files: Vec<FileEntry>,
}
pub fn current_target() -> String {
format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
}
pub fn user_id(key: &PublicKey) -> String {
use sha2::Digest;
hex::encode(&sha2::Sha256::digest(key.encode_protobuf())[..16])
}
pub fn check_path(p: &str) -> Result<()> {
let ok = !p.is_empty()
&& p.len() <= 512
&& !p.starts_with('/')
&& !p.contains('\\')
&& p.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
&& !p.chars().any(|c| c.is_control());
if ok { Ok(()) } else { Err(invalid(format!("bad path {p:?}"))) }
}
fn check_id(id: &str) -> Result<()> {
let ok = (3..=128).contains(&id.len())
&& id.bytes().all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_'))
&& !id.starts_with('.')
&& !id.contains("..");
if ok { Ok(()) } else { Err(invalid(format!("bad extension id {id:?}"))) }
}
impl Manifest {
pub fn public_key(&self) -> Result<PublicKey> {
let b = B64.decode(&self.author_key).map_err(|_| invalid("bad author key"))?;
PublicKey::try_decode_protobuf(&b).map_err(|_| invalid("bad author key"))
}
pub fn semver(&self) -> Result<semver::Version> {
semver::Version::parse(&self.version).map_err(|_| invalid(format!("bad version {:?}", self.version)))
}
pub fn native_for(&self, target: &str) -> Option<&Native> {
self.native.iter().find(|n| n.target == target)
}
pub fn check(&self) -> Result<()> {
if self.format != FORMAT {
return Err(invalid(format!("manifest format {} (this host reads {FORMAT})", self.format)));
}
check_id(&self.id)?;
self.semver()?;
if self.name.trim().is_empty() || self.name.len() > 128 {
return Err(invalid("bad name"));
}
let key = self.public_key()?;
if user_id(&key) != self.author {
return Err(Error::Verify("the author id is not the author key's".into()));
}
let mut seen = std::collections::HashSet::new();
for f in &self.files {
check_path(&f.path)?;
if f.path == "manifest.json" || f.path == "manifest.sig" {
return Err(invalid("reserved file name"));
}
if !seen.insert(f.path.as_str()) {
return Err(invalid(format!("{} is listed twice", f.path)));
}
if f.blake3.len() != 64 || !f.blake3.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(invalid(format!("bad hash for {}", f.path)));
}
}
for n in &self.native {
if !seen.contains(n.path.as_str()) {
return Err(invalid(format!("binary {} is not in the files", n.path)));
}
}
if let Some(w) = &self.wasm
&& !seen.contains(w.as_str())
{
return Err(invalid(format!("{w} is not in the files")));
}
for c in &self.capabilities {
if c.name.is_empty()
|| c.name.len() > 64
|| !c.name.bytes().all(|b| b.is_ascii_lowercase() || b == b'.' || b == b'_' || b.is_ascii_digit())
{
return Err(invalid(format!("bad capability {:?}", c.name)));
}
}
Ok(())
}
pub fn set_author(&mut self, key: &PublicKey) {
self.author = user_id(key);
self.author_key = B64.encode(key.encode_protobuf());
}
}
pub fn sign(key: &Keypair, manifest_json: &[u8]) -> Result<Vec<u8>> {
key.sign(&[MANIFEST_DOMAIN, manifest_json].concat()).map_err(|e| invalid(format!("signing: {e}")))
}
pub fn verify(manifest_json: &[u8], sig: &[u8]) -> Result<Manifest> {
let m: Manifest = serde_json::from_slice(manifest_json).map_err(|e| invalid(format!("manifest.json: {e}")))?;
let key = m.public_key()?;
if !key.verify(&[MANIFEST_DOMAIN, manifest_json].concat(), sig) {
return Err(Error::Verify("the manifest signature does not check out".into()));
}
m.check()?;
Ok(m)
}