Skip to main content

qualia_client_core/wellfair/api/
disclosure.rs

1//! Disclosure traceability + encrypted sanctuary vault
2
3use super::super::med_reminders::{
4    compute_due_reminders, load_prefs, save_prefs, DueMedReminder, MedReminderPrefs,
5};
6use super::super::sanctuary::{
7    load_prefs as load_sanctuary_prefs, lock_sanctuary, setup_sanctuary, unlock_sanctuary,
8    SanctuaryPrefs,
9};
10use sha2::{Digest, Sha256};
11use wellfare_core::sleep_analytics::{
12    self, SleepDebtReport, SleepHeatmapReport, SleepNightSample, DEFAULT_TARGET_SLEEP_MIN,
13};
14
15use super::super::personal_profile::{new_contact_id, EmergencyContact, EmergencyContactStore};
16
17use super::*;
18
19impl WebizenHostApi {
20    // --- Disclosure traceability (ADR 0011 D5) + duty of inquiry (D8) ---
21
22    /// Record a **transparency cc** — the protective "I informed authority X for purpose Y" note.
23    pub fn record_transparency_cc(
24        &self,
25        credential_id: &str,
26        informed_authority_did: &str,
27        purpose: &str,
28    ) -> Result<(), String> {
29        let cc = crate::disclosure_trace::TransparencyCc {
30            credential_id: credential_id.to_string(),
31            informed_authority_did: informed_authority_did.to_string(),
32            purpose: purpose.to_string(),
33            informed_unix: Self::now_unix(),
34        };
35        self.accountability_store()?
36            .record_transparency_cc(cc, &self.signing_key, Self::now_unix())
37            .map_err(|e| e.to_string())
38    }
39
40    /// Record a **disclosure event** (an access, or an onward-share if `onward_to` is set). A per-recipient
41    /// fingerprint + id are generated. Returns the recorded event (its `fingerprint` is the tracing anchor).
42    pub fn record_disclosure(
43        &self,
44        commitment_hex: &str,
45        credential_id: &str,
46        recipient_did: &str,
47        acting_delegate_did: Option<String>,
48        onward_to: Option<String>,
49    ) -> Result<crate::disclosure_trace::DisclosureEvent, String> {
50        let commitment = crate::accountability_store::parse_commitment_hex(commitment_hex)?;
51        let now = Self::now_unix();
52        let actor = acting_delegate_did.as_deref().unwrap_or(recipient_did);
53        // Deterministic per-recipient/per-disclosure fingerprint (the traitor-tracing anchor).
54        let digest = Sha256::digest(
55            format!("{}:{recipient_did}:{actor}:{now}", hex::encode(commitment)).as_bytes(),
56        );
57        let mut fingerprint = [0u8; 16];
58        fingerprint.copy_from_slice(&digest[..16]);
59        let id = format!("d-{}", hex::encode(&digest[16..22]));
60        let kind = match onward_to {
61            Some(to_did) => crate::disclosure_trace::DisclosureKind::OnwardShare { to_did },
62            None => crate::disclosure_trace::DisclosureKind::DirectAccess,
63        };
64        let event = crate::disclosure_trace::DisclosureEvent {
65            id,
66            payload_commitment: commitment,
67            credential_id: credential_id.to_string(),
68            recipient_did: recipient_did.to_string(),
69            acting_delegate_did,
70            time_unix: now,
71            fingerprint,
72            kind,
73        };
74        self.accountability_store()?
75            .record_disclosure_event(event.clone(), &self.signing_key, now)
76            .map_err(|e| e.to_string())?;
77        Ok(event)
78    }
79
80    /// The disclosure chain for a payload (who saw it, via which route).
81    pub fn disclosure_chain(
82        &self,
83        commitment_hex: &str,
84    ) -> Result<Vec<crate::disclosure_trace::DisclosureEvent>, String> {
85        let c = crate::accountability_store::parse_commitment_hex(commitment_hex)?;
86        self.accountability_store()?
87            .disclosure_chain(&c)
88            .map_err(|e| e.to_string())
89    }
90
91    /// The distinct actors who had access to a payload — the set a leak must be within.
92    pub fn actors_with_access(&self, commitment_hex: &str) -> Result<Vec<String>, String> {
93        let c = crate::accountability_store::parse_commitment_hex(commitment_hex)?;
94        self.accountability_store()?
95            .actors_with_access(&c)
96            .map_err(|e| e.to_string())
97    }
98
99    /// **Trace a leak** by its fingerprint (hex, 16 bytes) → the disclosure + accountable actor.
100    pub fn trace_leak(
101        &self,
102        fingerprint_hex: &str,
103    ) -> Result<Option<crate::disclosure_trace::DisclosureEvent>, String> {
104        let bytes =
105            hex::decode(fingerprint_hex.trim()).map_err(|e| format!("fingerprint not hex: {e}"))?;
106        let fp: crate::disclosure_trace::DisclosureFingerprint = bytes
107            .as_slice()
108            .try_into()
109            .map_err(|_| "fingerprint must be 16 bytes".to_string())?;
110        self.accountability_store()?
111            .trace_leak(&fp)
112            .map_err(|e| e.to_string())
113    }
114
115    /// List transparency cc records.
116    pub fn list_transparency_ccs(
117        &self,
118    ) -> Result<Vec<crate::disclosure_trace::TransparencyCc>, String> {
119        self.accountability_store()?
120            .list_transparency_ccs()
121            .map_err(|e| e.to_string())
122    }
123
124    /// **Assess a duty of inquiry** — classify conduct against the duty (the fair negligence classifier: was
125    /// an accessible means left unchecked, and did a harmful act follow?). Pure; no persistence.
126    pub fn assess_duty_of_inquiry(
127        &self,
128        duty: crate::duty_of_inquiry::DutyOfInquiry,
129        conduct: crate::duty_of_inquiry::ConductAgainstDuty,
130    ) -> crate::duty_of_inquiry::InquiryVerdict {
131        crate::duty_of_inquiry::assess(&duty, &conduct)
132    }
133
134    /// Sleep analytics.
135    pub fn sleep_analytics(
136        &self,
137        target_min: f64,
138    ) -> Result<(SleepDebtReport, SleepHeatmapReport), String> {
139        let sleep_rows = self.list_journal_by_kind("sleep", 128)?;
140        let mut samples = Vec::new();
141        for row in sleep_rows {
142            if let Some(ref summary) = row.summary {
143                if let Some((dur, eff)) = sleep_analytics::parse_sleep_summary_json(summary) {
144                    samples.push(SleepNightSample {
145                        night_unix: row.asserted_instant.to_unix_secs() as u32,
146                        duration_min: dur,
147                        efficiency: eff,
148                    });
149                }
150            }
151        }
152        samples.sort_by_key(|s| s.night_unix);
153        let debt = sleep_analytics::compute_sleep_debt(&samples, target_min);
154        let heatmap = sleep_analytics::compute_weekly_heatmap(&samples, target_min);
155        Ok((debt, heatmap))
156    }
157
158    /// Default sleep analytics.
159    pub fn default_sleep_analytics(&self) -> Result<(SleepDebtReport, SleepHeatmapReport), String> {
160        self.sleep_analytics(DEFAULT_TARGET_SLEEP_MIN)
161    }
162
163    /// Adds emergency-contact.
164    pub fn add_emergency_contact(
165        &self,
166        display_name: &str,
167        relationship: &str,
168        phone: Option<String>,
169        email: Option<String>,
170        notes: Option<String>,
171    ) -> Result<EmergencyContact, String> {
172        let now = Self::now_unix() as u32;
173        let contact = EmergencyContact {
174            id: new_contact_id(display_name, now),
175            display_name: display_name.to_string(),
176            relationship: relationship.to_string(),
177            phone,
178            email,
179            notes,
180            created_at_unix: now,
181        };
182        let store = EmergencyContactStore::open(&self.storage_root).map_err(|e| e.to_string())?;
183        store.append(&contact).map_err(|e| e.to_string())?;
184        Ok(contact)
185    }
186
187    /// Lists emergency contacts.
188    pub fn list_emergency_contacts(&self) -> Result<Vec<EmergencyContact>, String> {
189        let store = EmergencyContactStore::open(&self.storage_root).map_err(|e| e.to_string())?;
190        store.list().map_err(|e| e.to_string())
191    }
192
193    /// Med-reminder prefs.
194    pub fn med_reminder_prefs(&self) -> MedReminderPrefs {
195        load_prefs(&self.storage_root)
196    }
197
198    /// Sets med-reminders-enabled.
199    pub fn set_med_reminders_enabled(&self, enabled: bool) -> Result<MedReminderPrefs, String> {
200        let mut prefs = load_prefs(&self.storage_root);
201        if enabled && !prefs.permission_granted {
202            return Err("Grant reminder permission before enabling notifications".into());
203        }
204        prefs.enabled = enabled;
205        save_prefs(&self.storage_root, &prefs).map_err(|e| e.to_string())?;
206        Ok(prefs)
207    }
208
209    /// Grants med-reminder permission.
210    pub fn grant_med_reminder_permission(&self) -> Result<MedReminderPrefs, String> {
211        let mut prefs = load_prefs(&self.storage_root);
212        prefs.permission_granted = true;
213        prefs.permission_granted_at_unix = Some(Self::now_unix() as u32);
214        save_prefs(&self.storage_root, &prefs).map_err(|e| e.to_string())?;
215        Ok(prefs)
216    }
217
218    /// Lists due med reminders.
219    pub fn list_due_med_reminders(
220        &self,
221        window_minutes: i32,
222    ) -> Result<Vec<DueMedReminder>, String> {
223        let prefs = load_prefs(&self.storage_root);
224        if !prefs.enabled || !prefs.permission_granted {
225            return Ok(Vec::new());
226        }
227        let journal = self
228            .vault
229            .list_health_records(128)
230            .map_err(|e| e.to_string())?;
231        let now = chrono::Local::now().time();
232        Ok(compute_due_reminders(&journal, now, window_minutes))
233    }
234
235    /// Sanctuary prefs.
236    pub fn sanctuary_prefs(&self) -> SanctuaryPrefs {
237        load_sanctuary_prefs(&self.storage_root)
238    }
239
240    /// Sets up sanctuary.
241    pub fn setup_sanctuary(
242        &self,
243        real_pin: &str,
244        decoy_pin: &str,
245    ) -> Result<SanctuaryPrefs, String> {
246        setup_sanctuary(
247            &self.storage_root,
248            real_pin,
249            decoy_pin,
250            Self::now_unix() as u32,
251        )
252    }
253
254    /// Locks sanctuary.
255    pub fn lock_sanctuary(&self) -> Result<SanctuaryPrefs, String> {
256        lock_sanctuary(&self.storage_root)
257    }
258
259    /// Unlocks sanctuary.
260    pub fn unlock_sanctuary(&self, pin: &str) -> Result<SanctuaryPrefs, String> {
261        unlock_sanctuary(&self.storage_root, pin)
262    }
263
264    // --- Encrypted Sanctuary vault (real boundary; native-only, plan §6) ---
265    //
266    // Sensitive free-text notes are stored ONLY inside AEAD-encrypted lane files keyed by a
267    // PBKDF2-derived key — there is no plaintext journal path for them. Nothing is readable
268    // without the PIN, and the decoy PIN opens a separate lane that never aliases real data.
269
270    #[cfg(not(target_arch = "wasm32"))]
271    /// `true` when the sanctuary vault is configured.
272    pub fn sanctuary_vault_configured(&self) -> bool {
273        super::super::sanctuary_vault::is_configured(&self.storage_root)
274    }
275
276    #[cfg(not(target_arch = "wasm32"))]
277    /// Sets up the sanctuary vault.
278    pub fn setup_sanctuary_vault(&self, real_pin: &str, decoy_pin: &str) -> Result<(), String> {
279        super::super::sanctuary_vault::setup(&self.storage_root, real_pin, decoy_pin)
280    }
281
282    /// Verify a PIN and report which lane it opens (real vs duress decoy).
283    #[cfg(not(target_arch = "wasm32"))]
284    pub fn sanctuary_vault_resolve_lane(
285        &self,
286        pin: &str,
287    ) -> Result<super::super::sanctuary_vault::SanctuaryLane, String> {
288        super::super::sanctuary_vault::resolve_lane(&self.storage_root, pin)
289    }
290
291    #[cfg(not(target_arch = "wasm32"))]
292    /// Adds sanctuary-vault-note.
293    pub fn add_sanctuary_vault_note(
294        &self,
295        pin: &str,
296        body: &str,
297    ) -> Result<super::super::sanctuary_vault::SanctuaryLane, String> {
298        super::super::sanctuary_vault::add_note(
299            &self.storage_root,
300            pin,
301            body,
302            Self::now_unix() as u32,
303        )
304    }
305
306    #[cfg(not(target_arch = "wasm32"))]
307    /// Lists sanctuary vault notes.
308    pub fn list_sanctuary_vault_notes(
309        &self,
310        pin: &str,
311    ) -> Result<
312        (
313            super::super::sanctuary_vault::SanctuaryLane,
314            Vec<super::super::sanctuary_vault::SanctuaryVaultNote>,
315        ),
316        String,
317    > {
318        super::super::sanctuary_vault::list_notes(&self.storage_root, pin)
319    }
320}