Skip to main content

qualia_cooperative_core/qapp_package/
manifest.rs

1//! `QappManifest` — the transport-neutral definition of a companion qapp.
2//!
3//! A qapp is a person-defined mini-application (a cooperative front, a health tracker, a
4//! journal, a directory, …) that is ultimately delivered to a phone as an installable PWA
5//! wrapping a WebAssembly bundle. This module defines *what a qapp is*: its identity, the
6//! **least-privilege** capabilities it requests, a content-addressed reference to its wasm
7//! bundle, and the presentation metadata a PWA needs (icons, colours, display mode).
8//!
9//! It does **not** build wasm and it does not deliver anything — it only describes. The wasm
10//! bundle is referenced by path + SHA-256 hash + size (see [`WasmRef`]); producing that bundle
11//! and serving it over a secure origin are separate, later pieces (see the module doc in
12//! `qapp_package/mod.rs`).
13
14use serde::{Deserialize, Serialize};
15
16/// The kind of qapp. **Extensible**: [`QappKind::Custom`] carries an arbitrary id so new kinds
17/// need no code change. Serializes in `snake_case`; `Custom("x")` serializes as its inner string.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum QappKind {
21    Cooperative,
22    Health,
23    Journal,
24    Directory,
25    Custom(String),
26}
27
28impl QappKind {
29    /// A stable string form. Well-known kinds return their snake_case name; `Custom` returns
30    /// its inner id verbatim.
31    pub fn as_str(&self) -> &str {
32        match self {
33            QappKind::Cooperative => "cooperative",
34            QappKind::Health => "health",
35            QappKind::Journal => "journal",
36            QappKind::Directory => "directory",
37            QappKind::Custom(id) => id.as_str(),
38        }
39    }
40}
41
42impl Default for QappKind {
43    fn default() -> Self {
44        QappKind::Cooperative
45    }
46}
47
48/// A least-privilege scope a qapp requests. An empty `capabilities` list is the safest default
49/// (the qapp is granted nothing). **Extensible** via [`Capability::Custom`].
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum Capability {
53    ReadRecords,
54    WriteRecords,
55    Sync,
56    BlobStore,
57    Notifications,
58    Camera,
59    Custom(String),
60}
61
62impl Capability {
63    /// A stable string form; `Custom` returns its inner id verbatim.
64    pub fn as_str(&self) -> &str {
65        match self {
66            Capability::ReadRecords => "read_records",
67            Capability::WriteRecords => "write_records",
68            Capability::Sync => "sync",
69            Capability::BlobStore => "blob_store",
70            Capability::Notifications => "notifications",
71            Capability::Camera => "camera",
72            Capability::Custom(id) => id.as_str(),
73        }
74    }
75}
76
77/// A content-addressed reference to the qapp's compiled wasm bundle. This module references the
78/// bundle; it does not produce it. `sha256_hex` binds the manifest to an exact artifact so a
79/// later delivery layer can verify integrity.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct WasmRef {
82    /// Path (relative to the served PWA scope) at which the wasm bundle is fetched, e.g.
83    /// `"./qapp.wasm"`.
84    pub path: String,
85    /// Lower-case hex SHA-256 of the wasm bytes. Empty until a bundle is attached.
86    pub sha256_hex: String,
87    /// Size of the wasm bundle in bytes.
88    pub size_bytes: u64,
89}
90
91impl Default for WasmRef {
92    fn default() -> Self {
93        Self {
94            path: "./qapp.wasm".to_string(),
95            sha256_hex: String::new(),
96            size_bytes: 0,
97        }
98    }
99}
100
101/// An icon reference for the PWA manifest / home-screen install.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct IconRef {
104    /// Icon source path (relative to scope), e.g. `"./icons/icon-192.png"`.
105    pub src: String,
106    /// Space-separated size list, e.g. `"192x192"` or `"any"`.
107    pub sizes: String,
108    /// `"any"` or `"maskable"` (may be a space-separated combination).
109    pub purpose: String,
110}
111
112/// The transport-neutral definition of a qapp. Everything a PWA generator or a delivery layer
113/// needs to describe, present, and integrity-check the qapp — without knowing how it is served.
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115pub struct QappManifest {
116    /// Reverse-DNS-ish stable id, e.g. `"coop.qualia.journal"`.
117    pub id: String,
118    /// Human-facing full name.
119    pub name: String,
120    /// Short name for constrained surfaces (home screen), defaults to `name`.
121    pub short_name: String,
122    /// Semver string, e.g. `"0.1.0"`.
123    pub version: String,
124    /// One-line description.
125    pub description: String,
126    /// The kind of qapp (extensible).
127    pub kind: QappKind,
128    /// Least-privilege scopes requested. Empty = nothing granted.
129    pub capabilities: Vec<Capability>,
130    /// Content-addressed reference to the wasm bundle.
131    pub entry_wasm: WasmRef,
132    /// Icons for install / launch surfaces.
133    pub icons: Vec<IconRef>,
134    /// PWA theme colour (CSS colour string).
135    pub theme_color: String,
136    /// PWA background colour (CSS colour string).
137    pub background_color: String,
138    /// PWA display mode, e.g. `"standalone"`, `"fullscreen"`, `"minimal-ui"`, `"browser"`.
139    pub display: String,
140    /// Whether the qapp is expected to work offline (drives service-worker precache intent).
141    pub offline: bool,
142}
143
144impl QappManifest {
145    /// Create a manifest with sane defaults. `short_name` defaults to `name`; the wasm ref,
146    /// icons, and capabilities start empty/least-privilege.
147    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
148        let name = name.into();
149        Self {
150            id: id.into(),
151            short_name: name.clone(),
152            name,
153            version: "0.1.0".to_string(),
154            description: String::new(),
155            kind: QappKind::default(),
156            capabilities: Vec::new(),
157            entry_wasm: WasmRef::default(),
158            icons: Vec::new(),
159            theme_color: "#101418".to_string(),
160            background_color: "#0b0d10".to_string(),
161            display: "standalone".to_string(),
162            offline: true,
163        }
164    }
165
166    /// Set the kind.
167    pub fn with_kind(mut self, kind: QappKind) -> Self {
168        self.kind = kind;
169        self
170    }
171
172    /// Add a requested capability (least-privilege: only add what is needed).
173    pub fn with_capability(mut self, capability: Capability) -> Self {
174        self.capabilities.push(capability);
175        self
176    }
177
178    /// Set the content-addressed wasm reference.
179    pub fn with_entry(mut self, entry_wasm: WasmRef) -> Self {
180        self.entry_wasm = entry_wasm;
181        self
182    }
183
184    /// Add an icon reference.
185    pub fn with_icon(mut self, icon: IconRef) -> Self {
186        self.icons.push(icon);
187        self
188    }
189
190    /// Set the description.
191    pub fn with_description(mut self, description: impl Into<String>) -> Self {
192        self.description = description.into();
193        self
194    }
195
196    /// Set the version (semver string).
197    pub fn with_version(mut self, version: impl Into<String>) -> Self {
198        self.version = version.into();
199        self
200    }
201
202    /// Validate the manifest, returning the full list of problems (empty = valid).
203    ///
204    /// Hard errors: empty id, id without a dot (not reverse-DNS-ish), empty name, empty version.
205    /// A manifest with no icons is reported as a problem (an icon is required for a usable
206    /// install), consistent with the task's rule that a manifest with no icon *and* no name
207    /// must error — here we are stricter and always flag a missing icon, but the message is
208    /// clearly an install-quality issue.
209    pub fn validate(&self) -> Result<(), Vec<String>> {
210        let mut problems = Vec::new();
211
212        if self.id.trim().is_empty() {
213            problems.push("id must not be empty".to_string());
214        } else if !self.id.contains('.') {
215            problems.push(format!(
216                "id \"{}\" must be reverse-DNS-ish (contain at least one '.')",
217                self.id
218            ));
219        }
220
221        if self.name.trim().is_empty() {
222            problems.push("name must not be empty".to_string());
223        }
224
225        if self.version.trim().is_empty() {
226            problems.push("version must not be empty".to_string());
227        }
228
229        if self.icons.is_empty() {
230            problems
231                .push("at least one icon is required for a usable home-screen install".to_string());
232        }
233
234        if problems.is_empty() {
235            Ok(())
236        } else {
237            Err(problems)
238        }
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn new_has_sane_defaults() {
248        let m = QappManifest::new("coop.qualia.journal", "Qualia Journal");
249        assert_eq!(m.id, "coop.qualia.journal");
250        assert_eq!(m.name, "Qualia Journal");
251        assert_eq!(m.short_name, "Qualia Journal");
252        assert_eq!(m.version, "0.1.0");
253        assert_eq!(m.display, "standalone");
254        assert_eq!(m.theme_color, "#101418");
255        assert_eq!(m.background_color, "#0b0d10");
256        assert!(m.offline);
257        assert!(
258            m.capabilities.is_empty(),
259            "least privilege = empty by default"
260        );
261        assert_eq!(m.kind, QappKind::Cooperative);
262    }
263
264    #[test]
265    fn builders_compose() {
266        let m = QappManifest::new("coop.qualia.journal", "Qualia Journal")
267            .with_kind(QappKind::Journal)
268            .with_version("1.2.3")
269            .with_description("A private journal")
270            .with_capability(Capability::ReadRecords)
271            .with_capability(Capability::WriteRecords)
272            .with_entry(WasmRef {
273                path: "./journal.wasm".to_string(),
274                sha256_hex: "deadbeef".to_string(),
275                size_bytes: 4096,
276            })
277            .with_icon(IconRef {
278                src: "./icons/icon-192.png".to_string(),
279                sizes: "192x192".to_string(),
280                purpose: "any".to_string(),
281            });
282        assert_eq!(m.kind, QappKind::Journal);
283        assert_eq!(m.version, "1.2.3");
284        assert_eq!(m.description, "A private journal");
285        assert_eq!(m.capabilities.len(), 2);
286        assert_eq!(m.entry_wasm.path, "./journal.wasm");
287        assert_eq!(m.icons.len(), 1);
288    }
289
290    #[test]
291    fn manifest_serde_round_trips() {
292        let m = QappManifest::new("coop.qualia.directory", "Directory")
293            .with_kind(QappKind::Directory)
294            .with_capability(Capability::Sync)
295            .with_icon(IconRef {
296                src: "./i.png".to_string(),
297                sizes: "any".to_string(),
298                purpose: "maskable".to_string(),
299            });
300        let json = serde_json::to_string(&m).expect("serialize");
301        let back: QappManifest = serde_json::from_str(&json).expect("deserialize");
302        assert_eq!(m, back);
303    }
304
305    #[test]
306    fn well_known_kind_serializes_snake_case() {
307        let json = serde_json::to_string(&QappKind::Cooperative).unwrap();
308        assert_eq!(json, "\"cooperative\"");
309        let json = serde_json::to_string(&QappKind::Health).unwrap();
310        assert_eq!(json, "\"health\"");
311    }
312
313    #[test]
314    fn custom_kind_serializes_to_its_string() {
315        let json =
316            serde_json::to_string(&QappKind::Custom("coop.custom.kind".to_string())).unwrap();
317        assert_eq!(json, "{\"custom\":\"coop.custom.kind\"}");
318        assert_eq!(QappKind::Custom("x".to_string()).as_str(), "x");
319    }
320
321    #[test]
322    fn custom_capability_serializes_to_its_string() {
323        let json = serde_json::to_string(&Capability::Custom("geolocation".to_string())).unwrap();
324        assert_eq!(json, "{\"custom\":\"geolocation\"}");
325        assert_eq!(
326            Capability::Custom("geolocation".to_string()).as_str(),
327            "geolocation"
328        );
329        // Well-known snake_case check.
330        assert_eq!(
331            serde_json::to_string(&Capability::ReadRecords).unwrap(),
332            "\"read_records\""
333        );
334    }
335
336    #[test]
337    fn validate_ok_for_complete_manifest() {
338        let m = QappManifest::new("coop.qualia.journal", "Journal").with_icon(IconRef {
339            src: "./i.png".to_string(),
340            sizes: "192x192".to_string(),
341            purpose: "any".to_string(),
342        });
343        assert_eq!(m.validate(), Ok(()));
344    }
345
346    #[test]
347    fn validate_catches_empty_id() {
348        let m = QappManifest::new("", "Journal").with_icon(IconRef {
349            src: "./i.png".to_string(),
350            sizes: "any".to_string(),
351            purpose: "any".to_string(),
352        });
353        let problems = m.validate().unwrap_err();
354        assert!(problems.iter().any(|p| p.contains("id must not be empty")));
355    }
356
357    #[test]
358    fn validate_catches_missing_dot() {
359        let m = QappManifest::new("journal", "Journal").with_icon(IconRef {
360            src: "./i.png".to_string(),
361            sizes: "any".to_string(),
362            purpose: "any".to_string(),
363        });
364        let problems = m.validate().unwrap_err();
365        assert!(problems.iter().any(|p| p.contains("reverse-DNS-ish")));
366    }
367
368    #[test]
369    fn validate_catches_empty_name() {
370        let m = QappManifest::new("coop.qualia.journal", "").with_icon(IconRef {
371            src: "./i.png".to_string(),
372            sizes: "any".to_string(),
373            purpose: "any".to_string(),
374        });
375        let problems = m.validate().unwrap_err();
376        assert!(problems
377            .iter()
378            .any(|p| p.contains("name must not be empty")));
379    }
380
381    #[test]
382    fn validate_reports_missing_icon() {
383        let m = QappManifest::new("coop.qualia.journal", "Journal");
384        let problems = m.validate().unwrap_err();
385        assert!(problems.iter().any(|p| p.contains("icon")));
386    }
387
388    #[test]
389    fn validate_accumulates_all_problems() {
390        // Empty id, empty name, empty version, no icon → four problems at once.
391        let mut m = QappManifest::new("", "");
392        m.version = String::new();
393        let problems = m.validate().unwrap_err();
394        assert_eq!(problems.len(), 4, "problems: {problems:?}");
395    }
396}