Skip to main content

qualia_core_db/wasm_bridge/
device_storage.rs

1//! Device storage + backup-folder policy for Web Civics / mobile installs.
2//!
3//! Primary durable store on browser/PWA/mobile WebView is OPFS (see
4//! [`crate::wasm_storage`]). A **user-chosen backup folder** (File System Access
5//! API on Chromium/Android WebView, or a host-provided Documents path on
6//! Flutter/Tauri) holds export snapshots so OPFS wipe / site-data clear is
7//! recoverable.
8//!
9//! This module is **policy + receipt verification** (no Window dependency).
10//! Host adapters (`docs/js/webcivics-device-storage.js`) perform the actual
11//! pickers, OPFS I/O, and IndexedDB handle persistence.
12
13use serde::{Deserialize, Serialize};
14
15/// OPFS directory name under `navigator.storage.getDirectory()`.
16pub const WEBCIVICS_OPFS_DIR: &str = "webcivics";
17/// Manifest file inside the OPFS vault.
18pub const VAULT_MANIFEST_NAME: &str = "vault-manifest.v1.json";
19/// IndexedDB database id used by the JS host to remember the backup folder handle.
20pub const BACKUP_IDB_NAME: &str = "webcivics-device-storage-v1";
21pub const BACKUP_IDB_STORE: &str = "handles";
22pub const BACKUP_IDB_KEY: &str = "backup_dir_handle";
23/// Suggested subdirectory name inside the user-picked backup folder.
24pub const BACKUP_SUBDIR: &str = "webcivics-backups";
25/// Minimum free bytes before the host should refuse a large ingest.
26pub const MIN_PRIMARY_HEADROOM_BYTES: u64 = 8 * 1024 * 1024;
27/// Soft target: keep at least this many dated backup snapshots.
28pub const DEFAULT_BACKUP_RETENTION: u32 = 5;
29
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
31#[serde(rename_all = "camelCase")]
32pub struct DeviceStoragePolicy {
33    pub profile: &'static str,
34    pub engine_version: &'static str,
35    pub primary: PrimaryStorePolicy,
36    pub backup: BackupStorePolicy,
37    pub recovery: RecoveryPolicy,
38    pub capabilities: Vec<&'static str>,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
42#[serde(rename_all = "camelCase")]
43pub struct PrimaryStorePolicy {
44    pub kind: &'static str,
45    pub opfs_directory: &'static str,
46    pub manifest_name: &'static str,
47    pub persist_permission: bool,
48    pub block_size_bytes: u32,
49    pub min_headroom_bytes: u64,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct BackupStorePolicy {
55    pub kind: &'static str,
56    pub idb_name: &'static str,
57    pub idb_store: &'static str,
58    pub idb_key: &'static str,
59    pub suggested_subdir: &'static str,
60    pub retention_count: u32,
61    pub formats: Vec<&'static str>,
62    /// Hosts without `showDirectoryPicker` (many iOS PWAs) must use download/share.
63    pub fallback_when_no_picker: &'static str,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
67#[serde(rename_all = "camelCase")]
68pub struct RecoveryPolicy {
69    pub restore_requires_manifest: bool,
70    pub verify_content_hash: bool,
71    pub primary_wipe_does_not_erase_backup: bool,
72}
73
74/// Canonical policy document for Civics / mobile hosts.
75pub fn device_storage_policy() -> DeviceStoragePolicy {
76    DeviceStoragePolicy {
77        profile: "webcivics-device-storage",
78        engine_version: "0.0.39",
79        primary: PrimaryStorePolicy {
80            kind: "opfs",
81            opfs_directory: WEBCIVICS_OPFS_DIR,
82            manifest_name: VAULT_MANIFEST_NAME,
83            persist_permission: true,
84            block_size_bytes: 40_960,
85            min_headroom_bytes: MIN_PRIMARY_HEADROOM_BYTES,
86        },
87        backup: BackupStorePolicy {
88            kind: "user-directory-or-host-path",
89            idb_name: BACKUP_IDB_NAME,
90            idb_store: BACKUP_IDB_STORE,
91            idb_key: BACKUP_IDB_KEY,
92            suggested_subdir: BACKUP_SUBDIR,
93            retention_count: DEFAULT_BACKUP_RETENTION,
94            formats: vec![
95                "application/vnd.web-civics.vault-backup+json",
96                "application/ld+json",
97                "text/turtle",
98            ],
99            fallback_when_no_picker: "download-blob-or-share-sheet",
100        },
101        recovery: RecoveryPolicy {
102            restore_requires_manifest: true,
103            verify_content_hash: true,
104            primary_wipe_does_not_erase_backup: true,
105        },
106        capabilities: vec![
107            "device-storage-policy",
108            "opfs-primary-vault",
109            "backup-folder-link",
110            "backup-export-restore",
111        ],
112    }
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
116#[serde(rename_all = "camelCase")]
117pub struct StoragePlanInput {
118    pub quota_bytes: u64,
119    pub usage_bytes: u64,
120    pub backup_folder_linked: bool,
121    pub last_backup_unix: Option<u64>,
122    pub now_unix: u64,
123    /// Seconds after which a backup is considered stale (default 7 days).
124    #[serde(default = "default_stale_secs")]
125    pub stale_after_secs: u64,
126}
127
128fn default_stale_secs() -> u64 {
129    7 * 24 * 3600
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
133#[serde(rename_all = "camelCase")]
134pub struct StoragePlan {
135    pub available_bytes: u64,
136    pub primary_ok: bool,
137    pub recommend_persist: bool,
138    pub recommend_link_backup_folder: bool,
139    pub recommend_run_backup: bool,
140    pub warnings: Vec<&'static str>,
141    pub engine_version: &'static str,
142}
143
144/// Decide whether the host should persist, link a backup folder, or run a backup.
145pub fn plan_device_storage(input: &StoragePlanInput) -> StoragePlan {
146    let available = input.quota_bytes.saturating_sub(input.usage_bytes);
147    let mut warnings = Vec::new();
148    let primary_ok = available >= MIN_PRIMARY_HEADROOM_BYTES;
149    if !primary_ok {
150        warnings.push("primary_headroom_low");
151    }
152    let recommend_link = !input.backup_folder_linked;
153    if recommend_link {
154        warnings.push("backup_folder_not_linked");
155    }
156    let stale = match input.last_backup_unix {
157        Some(t) => input.now_unix.saturating_sub(t) > input.stale_after_secs,
158        None => true,
159    };
160    let recommend_run = input.backup_folder_linked && stale;
161    if recommend_run {
162        warnings.push("backup_stale_or_missing");
163    }
164    StoragePlan {
165        available_bytes: available,
166        primary_ok,
167        recommend_persist: true,
168        recommend_link_backup_folder: recommend_link,
169        recommend_run_backup: recommend_run,
170        warnings,
171        engine_version: "0.0.39",
172    }
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
176#[serde(rename_all = "camelCase")]
177pub struct BackupManifest {
178    pub schema: String,
179    pub created_unix: u64,
180    pub content_sha256: String,
181    pub byte_length: u64,
182    pub primary_kind: String,
183    pub notes: Option<String>,
184}
185
186#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
187#[serde(rename_all = "camelCase")]
188pub struct BackupVerifyResult {
189    pub ok: bool,
190    pub errors: Vec<&'static str>,
191    pub engine_version: &'static str,
192}
193
194/// Fail-closed checks for a backup snapshot manifest (host supplies SHA-256 hex).
195pub fn verify_backup_manifest(m: &BackupManifest, payload_sha256_hex: &str) -> BackupVerifyResult {
196    let mut errors = Vec::new();
197    if m.schema != "webcivics.vault-backup.v1" {
198        errors.push("schema_mismatch");
199    }
200    if m.content_sha256.len() != 64 || !m.content_sha256.chars().all(|c| c.is_ascii_hexdigit()) {
201        errors.push("content_hash_malformed");
202    }
203    if !payload_sha256_hex.eq_ignore_ascii_case(&m.content_sha256) {
204        errors.push("content_hash_mismatch");
205    }
206    if m.byte_length == 0 {
207        errors.push("empty_payload");
208    }
209    if m.primary_kind != "opfs" && m.primary_kind != "host-path" {
210        errors.push("unknown_primary_kind");
211    }
212    BackupVerifyResult {
213        ok: errors.is_empty(),
214        errors,
215        engine_version: "0.0.39",
216    }
217}
218
219#[cfg(target_arch = "wasm32")]
220mod wasm_exports {
221    use super::*;
222    use wasm_bindgen::prelude::*;
223
224    #[wasm_bindgen]
225    /// WASM bridge: device-storage-policy.
226    pub fn device_storage_policy_wasm() -> Result<JsValue, JsValue> {
227        serde_wasm_bindgen::to_value(&device_storage_policy())
228            .map_err(|e| JsValue::from_str(&e.to_string()))
229    }
230
231    #[wasm_bindgen]
232    /// WASM bridge: plan-device-storage.
233    pub fn plan_device_storage_wasm(val: JsValue) -> Result<JsValue, JsValue> {
234        let input: StoragePlanInput = serde_wasm_bindgen::from_value(val)?;
235        serde_wasm_bindgen::to_value(&plan_device_storage(&input))
236            .map_err(|e| JsValue::from_str(&e.to_string()))
237    }
238
239    #[wasm_bindgen]
240    /// WASM bridge: verify-backup-manifest.
241    pub fn verify_backup_manifest_wasm(
242        manifest: JsValue,
243        payload_sha256_hex: &str,
244    ) -> Result<JsValue, JsValue> {
245        let m: BackupManifest = serde_wasm_bindgen::from_value(manifest)?;
246        serde_wasm_bindgen::to_value(&verify_backup_manifest(&m, payload_sha256_hex))
247            .map_err(|e| JsValue::from_str(&e.to_string()))
248    }
249}
250
251#[cfg(target_arch = "wasm32")]
252pub use wasm_exports::*;
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn policy_names_opfs_and_backup_subdir() {
260        let p = device_storage_policy();
261        assert_eq!(p.primary.opfs_directory, "webcivics");
262        assert_eq!(p.backup.suggested_subdir, "webcivics-backups");
263        assert!(p.recovery.primary_wipe_does_not_erase_backup);
264    }
265
266    #[test]
267    fn plan_flags_missing_backup_and_low_headroom() {
268        let plan = plan_device_storage(&StoragePlanInput {
269            quota_bytes: 10_000_000,
270            usage_bytes: 9_500_000,
271            backup_folder_linked: false,
272            last_backup_unix: None,
273            now_unix: 1_000_000,
274            stale_after_secs: 100,
275        });
276        assert!(!plan.primary_ok);
277        assert!(plan.recommend_link_backup_folder);
278        assert!(!plan.recommend_run_backup); // cannot run until linked
279        assert!(plan.warnings.contains(&"backup_folder_not_linked"));
280    }
281
282    #[test]
283    fn plan_recommends_stale_backup_when_linked() {
284        let plan = plan_device_storage(&StoragePlanInput {
285            quota_bytes: 100_000_000,
286            usage_bytes: 1_000,
287            backup_folder_linked: true,
288            last_backup_unix: Some(1),
289            now_unix: 1_000_000,
290            stale_after_secs: 60,
291        });
292        assert!(plan.primary_ok);
293        assert!(plan.recommend_run_backup);
294    }
295
296    #[test]
297    fn verify_rejects_hash_mismatch() {
298        let m = BackupManifest {
299            schema: "webcivics.vault-backup.v1".into(),
300            created_unix: 1,
301            content_sha256: "a".repeat(64),
302            byte_length: 12,
303            primary_kind: "opfs".into(),
304            notes: None,
305        };
306        let r = verify_backup_manifest(&m, &"b".repeat(64));
307        assert!(!r.ok);
308        assert!(r.errors.contains(&"content_hash_mismatch"));
309    }
310
311    #[test]
312    fn verify_accepts_matching_manifest() {
313        let hash = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
314        let m = BackupManifest {
315            schema: "webcivics.vault-backup.v1".into(),
316            created_unix: 1,
317            content_sha256: hash.into(),
318            byte_length: 12,
319            primary_kind: "opfs".into(),
320            notes: Some("test".into()),
321        };
322        let r = verify_backup_manifest(&m, hash);
323        assert!(r.ok);
324        assert!(r.errors.is_empty());
325    }
326}