Skip to main content

weirdnet_update/
manifest.rs

1//! Update manifests and update kinds.
2
3use crate::ids::{check_id, check_text, check_unique};
4use crate::rollout::RolloutPlan;
5use crate::target::Rule;
6use crate::{Error, Hash32, Result, Timestamp};
7use semver::Version;
8use serde::{Deserialize, Serialize};
9use std::collections::BTreeSet;
10
11/// Most files in one update.
12pub const MAX_FILES: usize = 10_000;
13/// Most capabilities one update may request.
14pub const MAX_CAPABILITIES: usize = 256;
15/// Longest file path.
16pub const MAX_PATH: usize = 512;
17
18/// Operating systems in the WeirdBrains platform matrix.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
20#[serde(rename_all = "kebab-case")]
21#[allow(missing_docs)]
22pub enum Platform {
23    Linux,
24    Macos,
25    Windows,
26    Android,
27    Ios,
28    Freebsd,
29    Openbsd,
30    Ghostbsd,
31    Dragonfly,
32}
33
34impl Platform {
35    /// The lowercase name used in targeting rules.
36    pub fn as_str(self) -> &'static str {
37        match self {
38            Self::Linux => "linux",
39            Self::Macos => "macos",
40            Self::Windows => "windows",
41            Self::Android => "android",
42            Self::Ios => "ios",
43            Self::Freebsd => "freebsd",
44            Self::Openbsd => "openbsd",
45            Self::Ghostbsd => "ghostbsd",
46            Self::Dragonfly => "dragonfly",
47        }
48    }
49}
50
51/// CPU architectures.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
53#[serde(rename_all = "kebab-case")]
54#[allow(missing_docs)]
55pub enum Arch {
56    X86_64,
57    Aarch64,
58}
59
60/// How a full package reaches the user.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
62#[serde(rename_all = "kebab-case")]
63#[allow(missing_docs)]
64pub enum PackageFormat {
65    TarGz,
66    Zip,
67    Deb,
68    Rpm,
69    PkgTarZst,
70    Nix,
71    Homebrew,
72    Winget,
73    App,
74    Dmg,
75    Exe,
76    Msi,
77    Apk,
78    Ipa,
79    BsdPkg,
80}
81
82/// What the client does with a verified full package.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum InstallMode {
85    /// User-level swap of a versioned directory or bundle (tar.gz, zip, .app, standalone exe).
86    Swap,
87    /// The platform installer shows its own confirmation (APK `PackageInstaller`, MSI, dmg, ipa).
88    PlatformInstaller,
89    /// Run the system package manager after a user-approved privilege prompt (deb, rpm, BSD pkg).
90    PrivilegedPackageManager,
91    /// Never install: tell the user the command (TAUR, Nix, Homebrew, winget own these files).
92    NotifyOnly,
93}
94
95impl PackageFormat {
96    /// The install path for this format. Nothing escalates privileges without a prompt.
97    pub fn install_mode(self) -> InstallMode {
98        match self {
99            Self::TarGz | Self::Zip | Self::App | Self::Exe => InstallMode::Swap,
100            Self::Dmg | Self::Msi | Self::Apk | Self::Ipa => InstallMode::PlatformInstaller,
101            Self::Deb | Self::Rpm | Self::BsdPkg => InstallMode::PrivilegedPackageManager,
102            Self::PkgTarZst | Self::Nix | Self::Homebrew | Self::Winget => InstallMode::NotifyOnly,
103        }
104    }
105}
106
107/// A full, signed replacement build.
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub struct FullPackage {
110    /// Target OS.
111    pub platform: Platform,
112    /// Target CPU.
113    pub arch: Arch,
114    /// Package format.
115    pub format: PackageFormat,
116    /// The platform signing identity the package must keep (APK cert SHA-256, Apple Team ID,
117    /// Authenticode subject). The client compares it with the running build's.
118    pub signing_identity: String,
119}
120
121/// A Dart code patch. **Placeholder:** the format is reserved so manifests can name it, but no
122/// client accepts it yet (Android/desktop AOT swap is Salty Gull G6, the iOS interpreter G9).
123#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124pub struct DartPatch {
125    /// Engine build the patch was made against.
126    pub engine_hash: String,
127    /// Target OS.
128    pub platform: Platform,
129    /// Target CPU.
130    pub arch: Arch,
131}
132
133/// What an update carries.
134#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(rename_all = "kebab-case")]
136pub enum UpdateKind {
137    /// Non-code resources: images, fonts, translations, Remote Flutter Widgets files, config.
138    Assets,
139    /// WebAssembly components for the `weirdnet-ext` host (Pulley interpreter on iOS).
140    Wasm {
141        /// Host ABI version the components target; the client refuses other versions.
142        host_abi: u32,
143    },
144    /// A whole new build.
145    Full(FullPackage),
146    /// Reserved: see [`DartPatch`].
147    DartPatch(DartPatch),
148    /// "A new version is in the store." Downloads nothing.
149    StoreNotice {
150        /// Store page to open.
151        url: String,
152    },
153}
154
155impl UpdateKind {
156    /// Short name for errors and logs.
157    pub fn name(&self) -> &'static str {
158        match self {
159            Self::Assets => "assets",
160            Self::Wasm { .. } => "wasm",
161            Self::Full(_) => "full",
162            Self::DartPatch(_) => "dart-patch",
163            Self::StoreNotice { .. } => "store-notice",
164        }
165    }
166}
167
168/// Security advisory severity.
169#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
170#[serde(rename_all = "kebab-case")]
171#[allow(missing_docs)]
172pub enum Severity {
173    Low,
174    Medium,
175    High,
176    Critical,
177}
178
179/// A security label: shown with a distinct badge, never installed without consent.
180#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
181pub struct SecurityLabel {
182    /// Severity.
183    pub severity: Severity,
184    /// The publisher's advisory text.
185    pub advisory: String,
186}
187
188/// Display labels.
189#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
190pub struct Labels {
191    /// Set for security updates.
192    #[serde(default)]
193    pub security: Option<SecurityLabel>,
194    /// The publisher recommends this update.
195    #[serde(default)]
196    pub recommended: bool,
197}
198
199/// One file of an update.
200#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
201pub struct FileEntry {
202    /// Relative path inside the update (`/`-separated, no `..`).
203    pub path: String,
204    /// Exact size in bytes.
205    pub size: u64,
206    /// BLAKE3 of the content.
207    pub blake3: Hash32,
208}
209
210impl FileEntry {
211    /// An entry describing `data` at `path`.
212    pub fn describe(path: &str, data: &[u8]) -> Self {
213        Self { path: path.to_owned(), size: data.len() as u64, blake3: Hash32::of(data) }
214    }
215
216    /// Checks downloaded bytes against the entry.
217    pub fn verify(&self, data: &[u8]) -> Result<()> {
218        let mut v = self.verifier();
219        v.update(data)?;
220        v.finish()
221    }
222
223    /// An incremental checker for streamed or chunked downloads.
224    pub fn verifier(&self) -> FileVerifier<'_> {
225        FileVerifier { entry: self, hasher: blake3::Hasher::new(), seen: 0 }
226    }
227
228    fn validate(&self) -> Result<()> {
229        let p = &self.path;
230        let bad = p.is_empty()
231            || p.len() > MAX_PATH
232            || p.starts_with('/')
233            || p.contains('\\')
234            || p.contains('\0')
235            || p.split('/').any(|c| c.is_empty() || c == "." || c == "..")
236            || p.as_bytes().get(1) == Some(&b':');
237        if bad {
238            return Err(Error::File { path: p.clone(), reason: "unsafe or malformed path".into() });
239        }
240        Ok(())
241    }
242}
243
244/// Incremental size and hash check; fails as soon as more bytes arrive than declared.
245pub struct FileVerifier<'a> {
246    entry: &'a FileEntry,
247    hasher: blake3::Hasher,
248    seen: u64,
249}
250
251impl FileVerifier<'_> {
252    /// Feeds the next bytes.
253    pub fn update(&mut self, data: &[u8]) -> Result<()> {
254        self.seen = self.seen.saturating_add(data.len() as u64);
255        if self.seen > self.entry.size {
256            return Err(Error::File { path: self.entry.path.clone(), reason: "larger than declared".into() });
257        }
258        self.hasher.update(data);
259        Ok(())
260    }
261
262    /// Checks the final size and hash.
263    pub fn finish(self) -> Result<()> {
264        if self.seen != self.entry.size {
265            return Err(Error::File { path: self.entry.path.clone(), reason: "size mismatch".into() });
266        }
267        if Hash32::from(self.hasher.finalize()) != self.entry.blake3 {
268            return Err(Error::File { path: self.entry.path.clone(), reason: "hash mismatch".into() });
269        }
270        Ok(())
271    }
272}
273
274/// A signed description of one update on one channel.
275#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
276pub struct UpdateManifest {
277    /// App id.
278    pub app: String,
279    /// Channel (stable, beta, custom).
280    pub channel: String,
281    /// Unique id of this update.
282    pub update_id: String,
283    /// Per-(app, channel) sequence number; strictly increasing.
284    pub seq: u64,
285    /// What the update carries.
286    pub kind: UpdateKind,
287    /// Version of the build or bundle.
288    pub version: Version,
289    /// Base releases this applies to; empty means any.
290    #[serde(default)]
291    pub base_releases: Vec<String>,
292    /// Files and their hashes.
293    #[serde(default)]
294    pub files: Vec<FileEntry>,
295    /// Lowest client version this applies to.
296    #[serde(default)]
297    pub min_client: Option<Version>,
298    /// Highest client version this applies to.
299    #[serde(default)]
300    pub max_client: Option<Version>,
301    /// Capabilities requested (Wasm modules). New ones always ask again.
302    #[serde(default)]
303    pub capabilities: Vec<String>,
304    /// Display labels.
305    #[serde(default)]
306    pub labels: Labels,
307    /// On-device targeting rule; `None` targets everyone.
308    #[serde(default)]
309    pub targeting: Option<Rule>,
310    /// Staged rollout; `None` means 100%.
311    #[serde(default)]
312    pub rollout: Option<RolloutPlan>,
313    /// Set when this record rolls back to an older build: names the update it replaces, and
314    /// allows a lower version.
315    #[serde(default)]
316    pub rollback_of: Option<String>,
317    /// Release notes.
318    #[serde(default)]
319    pub notes: String,
320    /// Creation time.
321    pub created: Timestamp,
322    /// Expiry; always enforced.
323    pub expires: Timestamp,
324}
325
326impl UpdateManifest {
327    /// Structural checks.
328    pub fn validate(&self) -> Result<()> {
329        check_id("app", &self.app)?;
330        check_id("channel", &self.channel)?;
331        check_id("update id", &self.update_id)?;
332        if self.expires <= self.created {
333            return Err(Error::invalid("manifest", "expires must be after created"));
334        }
335        for b in &self.base_releases {
336            check_id("base release", b)?;
337        }
338        if let (Some(lo), Some(hi)) = (&self.min_client, &self.max_client)
339            && lo > hi
340        {
341            return Err(Error::invalid("manifest", "min_client above max_client"));
342        }
343        if self.files.len() > MAX_FILES {
344            return Err(Error::invalid("manifest", format!("more than {MAX_FILES} files")));
345        }
346        let mut paths = BTreeSet::new();
347        for f in &self.files {
348            f.validate()?;
349            if !paths.insert(f.path.as_str()) {
350                return Err(Error::File { path: f.path.clone(), reason: "listed twice".into() });
351            }
352        }
353        match &self.kind {
354            UpdateKind::StoreNotice { url } => {
355                if !self.files.is_empty() {
356                    return Err(Error::invalid("manifest", "a store notice carries no files"));
357                }
358                if !url.starts_with("https://") || url.len() > 2048 {
359                    return Err(Error::invalid("manifest", "store url must be https"));
360                }
361            }
362            _ if self.files.is_empty() => return Err(Error::invalid("manifest", "no files")),
363            UpdateKind::Full(p) => check_id("signing identity", &p.signing_identity)?,
364            UpdateKind::DartPatch(p) => check_id("engine hash", &p.engine_hash)?,
365            UpdateKind::Assets | UpdateKind::Wasm { .. } => {}
366        }
367        if self.capabilities.len() > MAX_CAPABILITIES {
368            return Err(Error::invalid("manifest", format!("more than {MAX_CAPABILITIES} capabilities")));
369        }
370        for c in &self.capabilities {
371            check_id("capability", c)?;
372        }
373        check_unique("capabilities", &self.capabilities)?;
374        if let Some(s) = &self.labels.security {
375            check_text("advisory", &s.advisory)?;
376        }
377        check_text("notes", &self.notes)?;
378        if let Some(r) = &self.rollback_of {
379            check_id("rollback_of", r)?;
380        }
381        if let Some(rule) = &self.targeting {
382            rule.validate()?;
383        }
384        if let Some(plan) = &self.rollout {
385            plan.validate()?;
386        }
387        Ok(())
388    }
389
390    /// `app/channel`, for messages.
391    pub fn target(&self) -> String {
392        format!("{}/{}", self.app, self.channel)
393    }
394
395    /// Total bytes to download.
396    pub fn total_size(&self) -> u64 {
397        self.files.iter().map(|f| f.size).fold(0u64, u64::saturating_add)
398    }
399}