Skip to main content

fetchium_core/privacy/
modes.rs

1//! Privacy mode definitions and enforcement (PRD §36).
2
3use crate::error::FetchiumError;
4
5/// The four privacy operating modes.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum PrivacyMode {
9    /// Normal operation — cache, history, PIE all enabled.
10    Standard,
11    /// No cache, no history, no PIE updates; nothing written to disk.
12    Private,
13    /// Route all HTTP through Tor SOCKS5 proxy (requires Tor daemon).
14    Tor,
15    /// Zero network — only local index queries (requires Phase 5 index).
16    AirGap,
17}
18
19impl std::fmt::Display for PrivacyMode {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        match self {
22            PrivacyMode::Standard => write!(f, "standard"),
23            PrivacyMode::Private => write!(f, "private"),
24            PrivacyMode::Tor => write!(f, "tor"),
25            PrivacyMode::AirGap => write!(f, "air-gap"),
26        }
27    }
28}
29
30impl PrivacyMode {
31    pub fn from_str_loose(s: &str) -> Option<Self> {
32        match s.to_lowercase().trim() {
33            "standard" | "normal" | "default" => Some(PrivacyMode::Standard),
34            "private" | "incognito" | "no-trace" => Some(PrivacyMode::Private),
35            "tor" | "onion" => Some(PrivacyMode::Tor),
36            "air-gap" | "airgap" | "offline" => Some(PrivacyMode::AirGap),
37            _ => None,
38        }
39    }
40}
41
42/// Runtime configuration modified by a privacy mode.
43///
44/// Callers should create this with `RuntimeConfig::default()`, then call
45/// `apply_mode()` to override fields based on the selected mode.
46#[derive(Debug, Clone)]
47pub struct RuntimeConfig {
48    pub cache_enabled: bool,
49    pub pie_enabled: bool,
50    pub history_enabled: bool,
51    pub embedding_cache_enabled: bool,
52    pub network_enabled: bool,
53    pub local_index_only: bool,
54    /// SOCKS5 proxy URL, e.g. `socks5://127.0.0.1:9050`
55    pub proxy: Option<String>,
56    pub user_agent: Option<String>,
57}
58
59impl Default for RuntimeConfig {
60    fn default() -> Self {
61        Self {
62            cache_enabled: true,
63            pie_enabled: true,
64            history_enabled: true,
65            embedding_cache_enabled: true,
66            network_enabled: true,
67            local_index_only: false,
68            proxy: None,
69            user_agent: None,
70        }
71    }
72}
73
74/// Apply a privacy mode to a `RuntimeConfig`.
75pub fn apply_mode(mode: PrivacyMode, config: &mut RuntimeConfig) -> Result<(), FetchiumError> {
76    match mode {
77        PrivacyMode::Standard => {}
78        PrivacyMode::Private => {
79            config.cache_enabled = false;
80            config.pie_enabled = false;
81            config.history_enabled = false;
82            config.embedding_cache_enabled = false;
83            tracing::info!("Privacy: private mode — cache/history/PIE disabled");
84        }
85        PrivacyMode::Tor => {
86            // Verify Tor is reachable before committing
87            check_tor_available()?;
88            config.proxy = Some("socks5://127.0.0.1:9050".to_string());
89            config.user_agent = Some(
90                "Mozilla/5.0 (Windows NT 10.0; rv:128.0) Gecko/20100101 Firefox/128.0".to_string(),
91            );
92            tracing::info!("Privacy: Tor mode — routing via SOCKS5 proxy");
93        }
94        PrivacyMode::AirGap => {
95            config.network_enabled = false;
96            config.local_index_only = true;
97            tracing::info!("Privacy: air-gap mode — local index only");
98        }
99    }
100    Ok(())
101}
102
103/// Check if Tor SOCKS5 proxy is reachable on 127.0.0.1:9050.
104fn check_tor_available() -> Result<(), FetchiumError> {
105    use std::net::TcpStream;
106    use std::time::Duration;
107    TcpStream::connect_timeout(
108        &"127.0.0.1:9050".parse().unwrap(),
109        Duration::from_secs(2),
110    )
111    .map(|_| ())
112    .map_err(|_| {
113        FetchiumError::Internal(
114            "Tor SOCKS5 proxy not reachable at 127.0.0.1:9050. \
115             Install Tor and ensure it is running (`tor` or `brew install tor && brew services start tor`)."
116                .into(),
117        )
118    })
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn private_mode_disables_cache() {
127        let mut cfg = RuntimeConfig::default();
128        apply_mode(PrivacyMode::Private, &mut cfg).unwrap();
129        assert!(!cfg.cache_enabled);
130        assert!(!cfg.pie_enabled);
131    }
132
133    #[test]
134    fn air_gap_disables_network() {
135        let mut cfg = RuntimeConfig::default();
136        apply_mode(PrivacyMode::AirGap, &mut cfg).unwrap();
137        assert!(!cfg.network_enabled);
138        assert!(cfg.local_index_only);
139    }
140
141    #[test]
142    fn mode_from_str_loose() {
143        assert_eq!(
144            PrivacyMode::from_str_loose("private"),
145            Some(PrivacyMode::Private)
146        );
147        assert_eq!(PrivacyMode::from_str_loose("TOR"), Some(PrivacyMode::Tor));
148        assert_eq!(PrivacyMode::from_str_loose("unknown"), None);
149    }
150}