Skip to main content

qualia_core_db/q42/app_manifest/
manifest.rs

1//! Versioned portable application manifest schema (APP-02).
2
3use super::error::AppManifestError;
4use super::paths::validate_package_relative_path;
5use super::permissions::{PermissionIntent, PresentationHint};
6
7/// Manifest schema version encoded on the wire.
8pub const APP_MANIFEST_VERSION: u16 = 1;
9/// Soft ceiling for a single serialized manifest (cold metadata).
10pub const MAX_MANIFEST_BYTES: usize = 256 * 1024;
11/// Maximum entry projections retained.
12pub const MAX_ENTRIES: usize = 32;
13/// Maximum required capability rows.
14pub const MAX_CAPABILITIES: usize = 64;
15/// Maximum required asset rows.
16pub const MAX_ASSETS: usize = 64;
17/// Maximum permission intents.
18pub const MAX_PERMISSIONS: usize = 32;
19/// Maximum presentation hints.
20pub const MAX_HINTS: usize = 64;
21/// Maximum compatibility feature tags.
22pub const MAX_FEATURES: usize = 32;
23
24/// Host-agnostic entry projection kind.
25///
26/// These name *projection surfaces*, not Host/Vibe invoke IDs.
27#[repr(u8)]
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum ProjectionKind {
31    Manifold = 1,
32    Container = 2,
33    FocusedMiniApp = 3,
34    DesktopHost = 4,
35}
36
37impl ProjectionKind {
38    /// Builds `ProjectionKind` from `u8`.
39    pub fn from_u8(value: u8) -> Result<Self, AppManifestError> {
40        match value {
41            1 => Ok(Self::Manifold),
42            2 => Ok(Self::Container),
43            3 => Ok(Self::FocusedMiniApp),
44            4 => Ok(Self::DesktopHost),
45            _ => Err(AppManifestError::InvalidProjection),
46        }
47    }
48}
49
50/// Author identity recorded on the manifest.
51#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
52pub struct AppAuthor {
53    pub name: String,
54    /// Author DID or empty when unsigned draft (still requires non-empty name).
55    pub did: String,
56}
57
58/// App identity / version / author block.
59#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
60pub struct AppIdentity {
61    pub app_id: String,
62    pub version: String,
63    pub author: AppAuthor,
64}
65
66/// One entry into a projection surface.
67///
68/// `entry_id` is an app-local symbolic name (not a Host/Vibe invoke ID).
69/// `relative_path` is a package-relative resource path (validated).
70#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
71pub struct EntryProjection {
72    pub projection: ProjectionKind,
73    pub entry_id: String,
74    pub relative_path: String,
75}
76
77/// Capability the host must provide before launch.
78#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79pub struct RequiredCapability {
80    pub id: String,
81    pub min_version: String,
82}
83
84/// Governed asset the package depends on.
85#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
86pub struct RequiredAsset {
87    pub asset_id: String,
88    /// Optional expected SHA-256; all-zero means “unspecified”.
89    pub expected_sha256: [u8; 32],
90}
91
92/// State schema reference (SHACL / semantic shape id + version).
93#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
94pub struct StateSchema {
95    pub schema_id: String,
96    pub schema_version: String,
97}
98
99/// Engine / feature compatibility window.
100#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
101pub struct Compatibility {
102    pub min_engine_version: String,
103    /// Empty string means no upper bound.
104    pub max_engine_version: String,
105    pub required_features: Vec<String>,
106}
107
108/// Package integrity digests.
109#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
110pub struct Integrity {
111    pub package_sha256: [u8; 32],
112}
113
114/// Update channel descriptor (no network fetch performed here).
115#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
116pub struct UpdateChannel {
117    /// Channel id such as `none`, `stable`, or a DID-shaped channel name.
118    pub channel_id: String,
119    /// Optional package-relative feed descriptor path (validated when non-empty).
120    pub relative_feed: String,
121}
122
123/// Versioned portable application manifest v1.
124///
125/// Field order on this struct is the canonical serialization order.
126#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
127pub struct PortableAppManifest {
128    pub identity: AppIdentity,
129    pub entries: Vec<EntryProjection>,
130    pub required_capabilities: Vec<RequiredCapability>,
131    pub required_assets: Vec<RequiredAsset>,
132    pub state_schema: StateSchema,
133    pub permission_intents: Vec<PermissionIntent>,
134    /// Layout / theme suggestions only — never authority (see permissions module).
135    pub presentation_hints: Vec<PresentationHint>,
136    pub compatibility: Compatibility,
137    pub integrity: Integrity,
138    pub update_channel: UpdateChannel,
139}
140
141impl PortableAppManifest {
142    /// Fail closed on missing identity, unknown projection paths, oversize lists,
143    /// empty integrity, or unsafe path fields.
144    pub fn validate(&self) -> Result<(), AppManifestError> {
145        if self.identity.app_id.trim().is_empty() {
146            return Err(AppManifestError::MissingAppId);
147        }
148        if self.identity.version.trim().is_empty() {
149            return Err(AppManifestError::MissingVersion);
150        }
151        if self.identity.author.name.trim().is_empty() {
152            return Err(AppManifestError::MissingAuthor);
153        }
154        if self.state_schema.schema_id.trim().is_empty() {
155            return Err(AppManifestError::MissingStateSchema);
156        }
157        if self.entries.is_empty() {
158            return Err(AppManifestError::EmptyEntries);
159        }
160        if self.integrity.package_sha256 == [0u8; 32] {
161            return Err(AppManifestError::MissingIntegrity);
162        }
163        if self.entries.len() > MAX_ENTRIES
164            || self.required_capabilities.len() > MAX_CAPABILITIES
165            || self.required_assets.len() > MAX_ASSETS
166            || self.permission_intents.len() > MAX_PERMISSIONS
167            || self.presentation_hints.len() > MAX_HINTS
168            || self.compatibility.required_features.len() > MAX_FEATURES
169        {
170            return Err(AppManifestError::Oversize);
171        }
172        for entry in &self.entries {
173            if entry.entry_id.trim().is_empty() {
174                return Err(AppManifestError::EmptyEntries);
175            }
176            validate_package_relative_path(&entry.relative_path)?;
177            if entry.relative_path.is_empty() {
178                return Err(AppManifestError::PathTraversal);
179            }
180        }
181        for asset in &self.required_assets {
182            if asset.asset_id.trim().is_empty() {
183                return Err(AppManifestError::MissingAppId);
184            }
185        }
186        for cap in &self.required_capabilities {
187            if cap.id.trim().is_empty() {
188                return Err(AppManifestError::MissingAppId);
189            }
190        }
191        validate_package_relative_path(&self.update_channel.relative_feed)?;
192        Ok(())
193    }
194
195    /// Verify a package payload digest against the integrity block.
196    pub fn verify_package_digest(&self, digest: &[u8; 32]) -> Result<(), AppManifestError> {
197        if digest == &self.integrity.package_sha256 {
198            Ok(())
199        } else {
200            Err(AppManifestError::InvalidDigest)
201        }
202    }
203}
204
205/// Compute SHA-256 into a caller-owned buffer.
206pub fn sha256_into(bytes: &[u8], out: &mut [u8; 32]) {
207    use sha2::{Digest, Sha256};
208    let digest = Sha256::digest(bytes);
209    out.copy_from_slice(&digest);
210}
211
212/// Convenience SHA-256 for cold tests and tooling.
213pub fn sha256_of(bytes: &[u8]) -> [u8; 32] {
214    let mut out = [0u8; 32];
215    sha256_into(bytes, &mut out);
216    out
217}