Skip to main content

qualia_client_core/wellfair/
sanctuary.rs

1//! Sanctuary vault state — setup, lock, decoy session (SAF-01..20; no destructive PIN).
2
3use std::fs;
4use std::path::Path;
5
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8
9use super::journal::JournalEntry;
10
11pub const SANCTUARY_PREFS_FILE: &str = "wellfair/sanctuary_prefs.json";
12
13/// Journal kinds hidden while Sanctuary is locked (including decoy session).
14pub const SANCTUARY_PROTECTED_KINDS: &[&str] = &["therapy_note", "sanctuary_note", "welfare_case"];
15
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
17pub struct SanctuaryPrefs {
18    pub enabled: bool,
19    pub locked: bool,
20    pub decoy_session: bool,
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub real_pin_hash_hex: Option<String>,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub decoy_pin_hash_hex: Option<String>,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub armed_at_unix: Option<u32>,
27}
28
29impl Default for SanctuaryPrefs {
30    fn default() -> Self {
31        Self {
32            enabled: false,
33            locked: false,
34            decoy_session: false,
35            real_pin_hash_hex: None,
36            decoy_pin_hash_hex: None,
37            armed_at_unix: None,
38        }
39    }
40}
41
42/// Hashes a PIN.
43pub fn hash_pin(pin: &str) -> String {
44    hex::encode(Sha256::digest(pin.as_bytes()))
45}
46
47/// Loads prefs.
48pub fn load_prefs(storage_root: impl AsRef<Path>) -> SanctuaryPrefs {
49    let path = storage_root.as_ref().join(SANCTUARY_PREFS_FILE);
50    if !path.exists() {
51        return SanctuaryPrefs::default();
52    }
53    fs::read_to_string(&path)
54        .ok()
55        .and_then(|s| serde_json::from_str(&s).ok())
56        .unwrap_or_default()
57}
58
59/// Saves prefs.
60pub fn save_prefs(storage_root: impl AsRef<Path>, prefs: &SanctuaryPrefs) -> std::io::Result<()> {
61    let path = storage_root.as_ref().join(SANCTUARY_PREFS_FILE);
62    if let Some(parent) = path.parent() {
63        fs::create_dir_all(parent)?;
64    }
65    let json =
66        serde_json::to_string_pretty(prefs).map_err(|e| std::io::Error::other(e.to_string()))?;
67    fs::write(&path, json)
68}
69
70/// Sets up sanctuary.
71pub fn setup_sanctuary(
72    storage_root: impl AsRef<Path>,
73    real_pin: &str,
74    decoy_pin: &str,
75    now_unix: u32,
76) -> Result<SanctuaryPrefs, String> {
77    if real_pin.len() < 4 || decoy_pin.len() < 4 {
78        return Err("PIN must be at least 4 characters".into());
79    }
80    if real_pin == decoy_pin {
81        return Err("Decoy PIN must differ from the real unlock PIN".into());
82    }
83    let prefs = SanctuaryPrefs {
84        enabled: true,
85        locked: false,
86        decoy_session: false,
87        real_pin_hash_hex: Some(hash_pin(real_pin)),
88        decoy_pin_hash_hex: Some(hash_pin(decoy_pin)),
89        armed_at_unix: Some(now_unix),
90    };
91    save_prefs(storage_root, &prefs).map_err(|e| e.to_string())?;
92    Ok(prefs)
93}
94
95/// Locks sanctuary.
96pub fn lock_sanctuary(storage_root: impl AsRef<Path>) -> Result<SanctuaryPrefs, String> {
97    let mut prefs = load_prefs(&storage_root);
98    if !prefs.enabled {
99        return Err("Sanctuary is not set up".into());
100    }
101    prefs.locked = true;
102    prefs.decoy_session = false;
103    save_prefs(&storage_root, &prefs).map_err(|e| e.to_string())?;
104    Ok(prefs)
105}
106
107/// Unlocks sanctuary.
108pub fn unlock_sanctuary(
109    storage_root: impl AsRef<Path>,
110    pin: &str,
111) -> Result<SanctuaryPrefs, String> {
112    let mut prefs = load_prefs(&storage_root);
113    if !prefs.enabled {
114        return Err("Sanctuary is not set up".into());
115    }
116    let hash = hash_pin(pin);
117    let real = prefs.real_pin_hash_hex.as_deref();
118    let decoy = prefs.decoy_pin_hash_hex.as_deref();
119    if Some(hash.as_str()) == real {
120        prefs.locked = false;
121        prefs.decoy_session = false;
122        save_prefs(&storage_root, &prefs).map_err(|e| e.to_string())?;
123        return Ok(prefs);
124    }
125    if Some(hash.as_str()) == decoy {
126        prefs.locked = true;
127        prefs.decoy_session = true;
128        save_prefs(&storage_root, &prefs).map_err(|e| e.to_string())?;
129        return Ok(prefs);
130    }
131    Err("Incorrect PIN".into())
132}
133
134/// `true` when sanctuary-protected-kind.
135pub fn is_sanctuary_protected_kind(kind: &str) -> bool {
136    SANCTUARY_PROTECTED_KINDS.contains(&kind)
137}
138
139/// Applies sanctuary-projection.
140pub fn apply_sanctuary_projection(
141    prefs: &SanctuaryPrefs,
142    entries: Vec<JournalEntry>,
143) -> Vec<JournalEntry> {
144    if !prefs.enabled || !prefs.locked {
145        return entries;
146    }
147    entries
148        .into_iter()
149        .filter(|e| !is_sanctuary_protected_kind(&e.kind))
150        .collect()
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use crate::wellfair::journal::JournalEntry;
157
158    fn entry(kind: &str) -> JournalEntry {
159        JournalEntry {
160            id: format!("urn:test:{kind}"),
161            kind: kind.into(),
162            asserted_time_unix: 0,
163            asserted_instant: wellfare_core::record::InstantBridge::default(),
164            evidence_type: "SelfReported".into(),
165            sensitivity: "Classified".into(),
166            blob_hash: None,
167            source: "test".into(),
168            committed_unix: 0,
169            summary: None,
170        }
171    }
172
173    #[test]
174    fn locked_sanctuary_hides_protected_kinds() {
175        let prefs = SanctuaryPrefs {
176            enabled: true,
177            locked: true,
178            decoy_session: false,
179            ..Default::default()
180        };
181        let rows = vec![entry("weight"), entry("therapy_note"), entry("life_event")];
182        let out = apply_sanctuary_projection(&prefs, rows);
183        assert_eq!(out.len(), 2);
184        assert!(out.iter().all(|e| !is_sanctuary_protected_kind(&e.kind)));
185    }
186
187    #[test]
188    fn decoy_pin_keeps_locked_with_decoy_flag() {
189        let dir = tempfile::tempdir().unwrap();
190        setup_sanctuary(dir.path(), "real-pin-1", "decoy-pin-2", 10).unwrap();
191        lock_sanctuary(dir.path()).unwrap();
192        let prefs = unlock_sanctuary(dir.path(), "decoy-pin-2").unwrap();
193        assert!(prefs.locked);
194        assert!(prefs.decoy_session);
195    }
196
197    #[test]
198    fn real_pin_unlocks() {
199        let dir = tempfile::tempdir().unwrap();
200        setup_sanctuary(dir.path(), "real-pin-1", "decoy-pin-2", 10).unwrap();
201        lock_sanctuary(dir.path()).unwrap();
202        let prefs = unlock_sanctuary(dir.path(), "real-pin-1").unwrap();
203        assert!(!prefs.locked);
204        assert!(!prefs.decoy_session);
205    }
206}