1use 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
34pub type StorageKey = Zeroizing<[u8; 32]>;
40
41pub trait StorageBackend: Send + Sync {
47 fn write(&self, session_id: &Uuid, data: &[u8]) -> std::io::Result<()>;
49 fn read(&self, session_id: &Uuid) -> std::io::Result<Option<Vec<u8>>>;
51 fn write_named(&self, name: &str, data: &[u8]) -> std::io::Result<()>;
53 fn read_named(&self, name: &str) -> std::io::Result<Option<Vec<u8>>>;
55 fn delete(&self, session_id: &Uuid) -> std::io::Result<()>;
57}
58
59#[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
73pub struct FsBackend {
82 dir: PathBuf,
83}
84
85impl FsBackend {
86 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#[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 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
181fn 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
197pub 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 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 pub fn delete(&self, session_id: &Uuid) -> anyhow::Result<()> {
246 self.backend.delete(session_id)?;
247 Ok(())
248 }
249
250 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 const MANIFEST_AAD: &'static [u8] = b"hyprstream-manifest-v1";
289 const MANIFEST_NAME: &'static str = "manifest";
290
291 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 pub fn list_all_conversations(&self) -> Vec<ConversationMeta> {
301 self.load_manifest()
302 }
303
304 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 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 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#[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 let raw = store1.backend.read(&session).unwrap().unwrap();
419
420 let wrong_key = Zeroizing::new([0x00u8; 32]);
422 let store2 = PrivateStore {
423 backend: MemoryBackend::new(),
424 key: wrong_key,
425 };
426 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 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 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}