1use 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
11pub const MAX_FILES: usize = 10_000;
13pub const MAX_CAPABILITIES: usize = 256;
15pub const MAX_PATH: usize = 512;
17
18#[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 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#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum InstallMode {
85 Swap,
87 PlatformInstaller,
89 PrivilegedPackageManager,
91 NotifyOnly,
93}
94
95impl PackageFormat {
96 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub struct FullPackage {
110 pub platform: Platform,
112 pub arch: Arch,
114 pub format: PackageFormat,
116 pub signing_identity: String,
119}
120
121#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124pub struct DartPatch {
125 pub engine_hash: String,
127 pub platform: Platform,
129 pub arch: Arch,
131}
132
133#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(rename_all = "kebab-case")]
136pub enum UpdateKind {
137 Assets,
139 Wasm {
141 host_abi: u32,
143 },
144 Full(FullPackage),
146 DartPatch(DartPatch),
148 StoreNotice {
150 url: String,
152 },
153}
154
155impl UpdateKind {
156 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#[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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
181pub struct SecurityLabel {
182 pub severity: Severity,
184 pub advisory: String,
186}
187
188#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
190pub struct Labels {
191 #[serde(default)]
193 pub security: Option<SecurityLabel>,
194 #[serde(default)]
196 pub recommended: bool,
197}
198
199#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
201pub struct FileEntry {
202 pub path: String,
204 pub size: u64,
206 pub blake3: Hash32,
208}
209
210impl FileEntry {
211 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 pub fn verify(&self, data: &[u8]) -> Result<()> {
218 let mut v = self.verifier();
219 v.update(data)?;
220 v.finish()
221 }
222
223 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
244pub struct FileVerifier<'a> {
246 entry: &'a FileEntry,
247 hasher: blake3::Hasher,
248 seen: u64,
249}
250
251impl FileVerifier<'_> {
252 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
276pub struct UpdateManifest {
277 pub app: String,
279 pub channel: String,
281 pub update_id: String,
283 pub seq: u64,
285 pub kind: UpdateKind,
287 pub version: Version,
289 #[serde(default)]
291 pub base_releases: Vec<String>,
292 #[serde(default)]
294 pub files: Vec<FileEntry>,
295 #[serde(default)]
297 pub min_client: Option<Version>,
298 #[serde(default)]
300 pub max_client: Option<Version>,
301 #[serde(default)]
303 pub capabilities: Vec<String>,
304 #[serde(default)]
306 pub labels: Labels,
307 #[serde(default)]
309 pub targeting: Option<Rule>,
310 #[serde(default)]
312 pub rollout: Option<RolloutPlan>,
313 #[serde(default)]
316 pub rollback_of: Option<String>,
317 #[serde(default)]
319 pub notes: String,
320 pub created: Timestamp,
322 pub expires: Timestamp,
324}
325
326impl UpdateManifest {
327 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 pub fn target(&self) -> String {
392 format!("{}/{}", self.app, self.channel)
393 }
394
395 pub fn total_size(&self) -> u64 {
397 self.files.iter().map(|f| f.size).fold(0u64, u64::saturating_add)
398 }
399}