Skip to main content

hyprstream_tui/
private_store.rs

1//! Encrypted per-session history store.
2//!
3//! # Wire format (per session file)
4//!
5//! ```text
6//! nonce(12B, OsRng) || AES-256-GCM(plaintext=serde_json(entries), aad=session_uuid.as_bytes())
7//! ```
8//!
9//! - **Nonce**: 12 fresh random bytes from `OsRng` on every write. Never reused.
10//! - **AAD**: the 16-byte session UUID binds the ciphertext to its filename,
11//!   preventing file-swap attacks.
12//! - **Key**: `Zeroizing<[u8; 32]>` derived by the caller (native: from signing
13//!   key seed via `derive_key`; browser: session-scoped Web Crypto key).
14//! - **Writes**: atomic — `{uuid}.enc.tmp` → `fs::rename` → `{uuid}.enc`.
15
16use std::collections::HashMap;
17use std::path::PathBuf;
18
19#[cfg(not(target_os = "wasi"))]
20use parking_lot::Mutex;
21#[cfg(target_os = "wasi")]
22#[allow(clippy::disallowed_types)]
23use std::sync::Mutex;
24
25use aes_gcm::{
26    aead::{Aead, KeyInit, Payload},
27    Aes256Gcm, Nonce,
28};
29use rand::RngCore;
30use serde::{Deserialize, Serialize};
31use uuid::Uuid;
32use zeroize::Zeroizing;
33
34// ============================================================================
35// StorageKey
36// ============================================================================
37
38/// 32-byte AES-256 key, zeroed on drop.
39pub type StorageKey = Zeroizing<[u8; 32]>;
40
41// ============================================================================
42// StorageBackend
43// ============================================================================
44
45/// Backend abstraction for raw byte reads and atomic writes.
46pub trait StorageBackend: Send + Sync {
47    /// Atomically write `data` to the file for `session_id`.
48    fn write(&self, session_id: &Uuid, data: &[u8]) -> std::io::Result<()>;
49    /// Read the raw bytes for `session_id`. Returns `None` if no file exists.
50    fn read(&self, session_id: &Uuid) -> std::io::Result<Option<Vec<u8>>>;
51    /// Write data under a fixed domain name (e.g. "manifest").
52    fn write_named(&self, name: &str, data: &[u8]) -> std::io::Result<()>;
53    /// Read data from a fixed domain name. Returns `None` if not found.
54    fn read_named(&self, name: &str) -> std::io::Result<Option<Vec<u8>>>;
55    /// Delete the file for `session_id`.
56    fn delete(&self, session_id: &Uuid) -> std::io::Result<()>;
57}
58
59// ============================================================================
60// ConversationMeta
61// ============================================================================
62
63/// Metadata for a single private conversation (stored in the manifest).
64#[derive(Serialize, Deserialize, Clone, Debug)]
65pub struct ConversationMeta {
66    pub uuid: Uuid,
67    pub model_ref: String,
68    pub created_at: u64,
69    pub last_active: u64,
70    pub label: Option<String>,
71}
72
73// ============================================================================
74// FsBackend
75// ============================================================================
76
77/// Filesystem backend.
78///
79/// Native path: `$XDG_DATA_HOME/hyprstream/private/v1/`
80/// WASM path:   `/private/v1/` (requires OPFS preopen — Phase W1)
81pub struct FsBackend {
82    dir: PathBuf,
83}
84
85impl FsBackend {
86    /// Create the backend and ensure the directory exists.
87    /// Returns an error (not a fallback) if the directory cannot be created.
88    pub fn new(dir: PathBuf) -> std::io::Result<Self> {
89        std::fs::create_dir_all(&dir)?;
90        Ok(Self { dir })
91    }
92}
93
94impl StorageBackend for FsBackend {
95    fn write(&self, session_id: &Uuid, data: &[u8]) -> std::io::Result<()> {
96        let tmp = self.dir.join(format!("{}.enc.tmp", session_id));
97        let final_path = self.dir.join(format!("{}.enc", session_id));
98        std::fs::write(&tmp, data)?;
99        std::fs::rename(&tmp, &final_path)
100    }
101
102    fn read(&self, session_id: &Uuid) -> std::io::Result<Option<Vec<u8>>> {
103        let path = self.dir.join(format!("{}.enc", session_id));
104        match std::fs::read(&path) {
105            Ok(data) => Ok(Some(data)),
106            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
107            Err(e) => Err(e),
108        }
109    }
110
111    fn write_named(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
112        let tmp = self.dir.join(format!("{}.enc.tmp", name));
113        let final_path = self.dir.join(format!("{}.enc", name));
114        std::fs::write(&tmp, data)?;
115        std::fs::rename(&tmp, &final_path)
116    }
117
118    fn read_named(&self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
119        let path = self.dir.join(format!("{}.enc", name));
120        match std::fs::read(&path) {
121            Ok(data) => Ok(Some(data)),
122            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
123            Err(e) => Err(e),
124        }
125    }
126
127    fn delete(&self, session_id: &Uuid) -> std::io::Result<()> {
128        let path = self.dir.join(format!("{}.enc", session_id));
129        match std::fs::remove_file(&path) {
130            Ok(()) => Ok(()),
131            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
132            Err(e) => Err(e),
133        }
134    }
135}
136
137// ============================================================================
138// MemoryBackend
139// ============================================================================
140
141/// In-memory backend for tests and ephemeral sessions.
142#[derive(Default)]
143pub struct MemoryBackend {
144    store: Mutex<HashMap<Uuid, Vec<u8>>>,
145}
146
147impl MemoryBackend {
148    pub fn new() -> Self {
149        Self::default()
150    }
151}
152
153impl StorageBackend for MemoryBackend {
154    fn write(&self, session_id: &Uuid, data: &[u8]) -> std::io::Result<()> {
155        store_lock(&self.store).insert(*session_id, data.to_vec());
156        Ok(())
157    }
158
159    fn read(&self, session_id: &Uuid) -> std::io::Result<Option<Vec<u8>>> {
160        Ok(store_lock(&self.store).get(session_id).cloned())
161    }
162
163    fn write_named(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
164        // Use a deterministic UUID derived from the name for the in-memory map.
165        let key = Uuid::new_v5(&Uuid::NAMESPACE_OID, name.as_bytes());
166        store_lock(&self.store).insert(key, data.to_vec());
167        Ok(())
168    }
169
170    fn read_named(&self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
171        let key = Uuid::new_v5(&Uuid::NAMESPACE_OID, name.as_bytes());
172        Ok(store_lock(&self.store).get(&key).cloned())
173    }
174
175    fn delete(&self, session_id: &Uuid) -> std::io::Result<()> {
176        store_lock(&self.store).remove(session_id);
177        Ok(())
178    }
179}
180
181/// Acquire the store lock in a cfg-portable way.
182/// - `parking_lot::Mutex::lock()` returns `MutexGuard<T>` directly.
183/// - `std::sync::Mutex::lock()` returns `Result<MutexGuard<T>, PoisonError>`.
184fn store_lock(
185    m: &Mutex<HashMap<Uuid, Vec<u8>>>,
186) -> impl std::ops::DerefMut<Target = HashMap<Uuid, Vec<u8>>> + '_ {
187    #[cfg(not(target_os = "wasi"))]
188    {
189        m.lock()
190    }
191    #[cfg(target_os = "wasi")]
192    {
193        m.lock().unwrap_or_else(|e| e.into_inner())
194    }
195}
196
197// ============================================================================
198// PrivateStore
199// ============================================================================
200
201/// Encrypted per-session history store.
202///
203/// Generic over `StorageBackend` so the same code works with `FsBackend`
204/// (native/WASM) and `MemoryBackend` (tests).
205pub struct PrivateStore<B: StorageBackend> {
206    backend: B,
207    key: StorageKey,
208}
209
210impl<B: StorageBackend> PrivateStore<B> {
211    pub fn new(backend: B, key: StorageKey) -> Self {
212        Self { backend, key }
213    }
214
215    /// Encrypt `entries` and atomically write to storage.
216    ///
217    /// A fresh 12-byte nonce is generated from `OsRng` on every call.
218    pub fn save<T: Serialize>(&self, session_id: &Uuid, entries: &[T]) -> anyhow::Result<()> {
219        let plaintext = serde_json::to_vec(entries)?;
220        let aad = session_id.as_bytes();
221
222        let mut nonce_bytes = [0u8; 12];
223        rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
224
225        let cipher = Aes256Gcm::new(self.key.as_ref().into());
226        let ciphertext = cipher
227            .encrypt(
228                Nonce::from_slice(&nonce_bytes),
229                Payload {
230                    msg: &plaintext,
231                    aad,
232                },
233            )
234            .map_err(|e| anyhow::anyhow!("AES-GCM encrypt: {}", e))?;
235
236        let mut file_data = Vec::with_capacity(12 + ciphertext.len());
237        file_data.extend_from_slice(&nonce_bytes);
238        file_data.extend_from_slice(&ciphertext);
239
240        self.backend.write(session_id, &file_data)?;
241        Ok(())
242    }
243
244    /// Delete the encrypted history file for `session_id`.
245    pub fn delete(&self, session_id: &Uuid) -> anyhow::Result<()> {
246        self.backend.delete(session_id)?;
247        Ok(())
248    }
249
250    /// Load and decrypt entries for `session_id`.
251    /// Returns `None` if no history file exists yet.
252    pub fn load<T: for<'de> Deserialize<'de>>(
253        &self,
254        session_id: &Uuid,
255    ) -> anyhow::Result<Option<Vec<T>>> {
256        let Some(file_data) = self.backend.read(session_id)? else {
257            return Ok(None);
258        };
259        if file_data.len() < 12 {
260            return Err(anyhow::anyhow!(
261                "private history file too short ({} bytes)",
262                file_data.len()
263            ));
264        }
265        let (nonce_bytes, ciphertext) = file_data.split_at(12);
266        let aad = session_id.as_bytes();
267
268        let cipher = Aes256Gcm::new(self.key.as_ref().into());
269        let plaintext = cipher
270            .decrypt(
271                Nonce::from_slice(nonce_bytes),
272                Payload {
273                    msg: ciphertext,
274                    aad,
275                },
276            )
277            .map_err(|e| anyhow::anyhow!("AES-GCM decrypt: {}", e))?;
278
279        let entries: Vec<T> = serde_json::from_slice(&plaintext)?;
280        Ok(Some(entries))
281    }
282
283    // ====================================================================
284    // Manifest CRUD
285    // ====================================================================
286
287    /// Fixed domain tag used as AAD for manifest encryption.
288    const MANIFEST_AAD: &'static [u8] = b"hyprstream-manifest-v1";
289    const MANIFEST_NAME: &'static str = "manifest";
290
291    /// List all conversations for a given model.
292    pub fn list_conversations(&self, model_ref: &str) -> Vec<ConversationMeta> {
293        self.load_manifest()
294            .into_iter()
295            .filter(|c| c.model_ref == model_ref)
296            .collect()
297    }
298
299    /// List all conversations across all models.
300    pub fn list_all_conversations(&self) -> Vec<ConversationMeta> {
301        self.load_manifest()
302    }
303
304    /// Register a new conversation in the manifest.
305    pub fn register_conversation(&self, meta: ConversationMeta) -> anyhow::Result<()> {
306        let mut manifest = self.load_manifest();
307        manifest.push(meta);
308        self.save_manifest(&manifest)
309    }
310
311    /// Update the `last_active` timestamp for a conversation.
312    pub fn update_last_active(&self, uuid: &Uuid) -> anyhow::Result<()> {
313        let mut manifest = self.load_manifest();
314        if let Some(entry) = manifest.iter_mut().find(|c| c.uuid == *uuid) {
315            entry.last_active = current_unix_secs();
316            self.save_manifest(&manifest)?;
317        }
318        Ok(())
319    }
320
321    /// Delete a conversation: removes both the history file and the manifest entry.
322    pub fn delete_conversation(&self, uuid: &Uuid) -> anyhow::Result<()> {
323        self.delete(uuid)?;
324        let mut manifest = self.load_manifest();
325        manifest.retain(|c| c.uuid != *uuid);
326        self.save_manifest(&manifest)
327    }
328
329    fn load_manifest(&self) -> Vec<ConversationMeta> {
330        let data = match self.backend.read_named(Self::MANIFEST_NAME) {
331            Ok(Some(d)) => d,
332            _ => return Vec::new(),
333        };
334        if data.len() < 12 {
335            return Vec::new();
336        }
337        let (nonce_bytes, ciphertext) = data.split_at(12);
338        let cipher = Aes256Gcm::new(self.key.as_ref().into());
339        let plaintext = match cipher.decrypt(
340            Nonce::from_slice(nonce_bytes),
341            Payload {
342                msg: ciphertext,
343                aad: Self::MANIFEST_AAD,
344            },
345        ) {
346            Ok(p) => p,
347            Err(_) => return Vec::new(),
348        };
349        serde_json::from_slice(&plaintext).unwrap_or_default()
350    }
351
352    fn save_manifest(&self, entries: &[ConversationMeta]) -> anyhow::Result<()> {
353        let plaintext = serde_json::to_vec(entries)?;
354        let mut nonce_bytes = [0u8; 12];
355        rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
356        let cipher = Aes256Gcm::new(self.key.as_ref().into());
357        let ciphertext = cipher
358            .encrypt(
359                Nonce::from_slice(&nonce_bytes),
360                Payload {
361                    msg: &plaintext,
362                    aad: Self::MANIFEST_AAD,
363                },
364            )
365            .map_err(|e| anyhow::anyhow!("manifest encrypt: {}", e))?;
366        let mut file_data = Vec::with_capacity(12 + ciphertext.len());
367        file_data.extend_from_slice(&nonce_bytes);
368        file_data.extend_from_slice(&ciphertext);
369        self.backend.write_named(Self::MANIFEST_NAME, &file_data)?;
370        Ok(())
371    }
372}
373
374fn current_unix_secs() -> u64 {
375    std::time::SystemTime::now()
376        .duration_since(std::time::UNIX_EPOCH)
377        .unwrap_or_default()
378        .as_secs()
379}
380
381// ============================================================================
382// Tests
383// ============================================================================
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    fn test_key() -> StorageKey {
390        Zeroizing::new([0x42u8; 32])
391    }
392
393    #[test]
394    fn round_trip_memory_backend() {
395        let store = PrivateStore::new(MemoryBackend::new(), test_key());
396        let session = Uuid::new_v4();
397        let entries = vec!["hello", "world"];
398        store.save(&session, &entries).unwrap();
399        let loaded: Vec<String> = store.load(&session).unwrap().unwrap();
400        assert_eq!(loaded, entries);
401    }
402
403    #[test]
404    fn missing_session_returns_none() {
405        let store = PrivateStore::new(MemoryBackend::new(), test_key());
406        let session = Uuid::new_v4();
407        let loaded: Option<Vec<String>> = store.load(&session).unwrap();
408        assert!(loaded.is_none());
409    }
410
411    #[test]
412    fn wrong_key_fails_decrypt() {
413        let store1 = PrivateStore::new(MemoryBackend::new(), test_key());
414        let session = Uuid::new_v4();
415        store1.save(&session, &["secret"]).unwrap();
416
417        // Extract the ciphertext bytes from the MemoryBackend by saving with store1.
418        let raw = store1.backend.read(&session).unwrap().unwrap();
419
420        // Create a second store with a different key sharing the same backend.
421        let wrong_key = Zeroizing::new([0x00u8; 32]);
422        let store2 = PrivateStore {
423            backend: MemoryBackend::new(),
424            key: wrong_key,
425        };
426        // Manually write the ciphertext into store2's backend.
427        store2.backend.write(&session, &raw).unwrap();
428
429        let result: anyhow::Result<Option<Vec<String>>> = store2.load(&session);
430        assert!(result.is_err(), "wrong key should fail decryption");
431    }
432
433    #[test]
434    fn manifest_round_trip() {
435        let store = PrivateStore::new(MemoryBackend::new(), test_key());
436        let uuid = Uuid::new_v4();
437        let meta = ConversationMeta {
438            uuid,
439            model_ref: "qwen3:main".to_owned(),
440            created_at: 1000,
441            last_active: 1000,
442            label: None,
443        };
444        store.register_conversation(meta).unwrap();
445        let convos = store.list_conversations("qwen3:main");
446        assert_eq!(convos.len(), 1);
447        assert_eq!(convos[0].uuid, uuid);
448
449        // Different model returns empty.
450        assert!(store.list_conversations("other:model").is_empty());
451    }
452
453    #[test]
454    fn manifest_delete_conversation() {
455        let store = PrivateStore::new(MemoryBackend::new(), test_key());
456        let uuid = Uuid::new_v4();
457        store.save(&uuid, &["data"]).unwrap();
458        store
459            .register_conversation(ConversationMeta {
460                uuid,
461                model_ref: "m".to_owned(),
462                created_at: 1,
463                last_active: 1,
464                label: None,
465            })
466            .unwrap();
467        store.delete_conversation(&uuid).unwrap();
468        assert!(store.list_all_conversations().is_empty());
469        let loaded: Option<Vec<String>> = store.load(&uuid).unwrap();
470        assert!(loaded.is_none());
471    }
472
473    #[test]
474    fn aad_binding_prevents_session_swap() {
475        let backend = MemoryBackend::new();
476        let key = test_key();
477
478        let session_a = Uuid::new_v4();
479        let session_b = Uuid::new_v4();
480
481        let store = PrivateStore::new(MemoryBackend::new(), test_key());
482        store.save(&session_a, &["data for A"]).unwrap();
483
484        // Extract A's ciphertext and plant it under session_b's key.
485        let raw_a = store.backend.read(&session_a).unwrap().unwrap();
486        let store2 = PrivateStore { backend, key };
487        store2.backend.write(&session_b, &raw_a).unwrap();
488
489        let result: anyhow::Result<Option<Vec<String>>> = store2.load(&session_b);
490        assert!(result.is_err(), "AAD mismatch should fail decryption");
491    }
492}