Skip to main content

hashtree_config/
lib.rs

1//! Shared configuration for hashtree tools
2//!
3//! Reads from ~/.hashtree/config.toml
4
5use anyhow::{Context, Result};
6use serde::{Deserialize, Serialize};
7use std::fs;
8use std::path::PathBuf;
9
10/// Default read-only file servers
11pub const DEFAULT_READ_SERVERS: &[&str] = &["https://cdn.iris.to", "https://blossom.primal.net"];
12
13/// Default write-enabled file servers
14pub const DEFAULT_WRITE_SERVERS: &[&str] = &["https://upload.iris.to"];
15
16/// Default nostr relays
17pub const DEFAULT_RELAYS: &[&str] = &[
18    "wss://temp.iris.to",
19    "wss://nos.lol",
20    "wss://relay.snort.social",
21];
22
23/// Default social graph entrypoint followed when a new identity is initialized.
24pub const DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB: &str =
25    "npub1xdhnr9mrv47kkrn95k6cwecearydeh8e895990n3acntwvmgk2dsdeeycm";
26
27/// Default read-only alias for the social graph entrypoint.
28pub const DEFAULT_SOCIALGRAPH_ENTRYPOINT_ALIAS: &str = "siriusbusiness";
29
30/// Top-level config structure
31#[derive(Debug, Clone, Default, Serialize, Deserialize)]
32pub struct Config {
33    #[serde(default)]
34    pub server: ServerConfig,
35    #[serde(default)]
36    pub storage: StorageConfig,
37    #[serde(default)]
38    pub nostr: NostrConfig,
39    #[serde(default)]
40    pub blossom: BlossomConfig,
41    #[serde(default)]
42    pub sync: SyncConfig,
43    #[serde(default)]
44    pub updater: UpdaterConfig,
45}
46
47/// Server configuration
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct ServerConfig {
50    #[serde(default = "default_bind_address")]
51    pub bind_address: String,
52    #[serde(default = "default_true")]
53    pub enable_auth: bool,
54    #[serde(default)]
55    pub public_writes: bool,
56}
57
58impl Default for ServerConfig {
59    fn default() -> Self {
60        Self {
61            bind_address: default_bind_address(),
62            enable_auth: true,
63            public_writes: false,
64        }
65    }
66}
67
68fn default_bind_address() -> String {
69    "127.0.0.1:8080".to_string()
70}
71
72fn default_true() -> bool {
73    true
74}
75
76/// Storage backend type
77#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "lowercase")]
79pub enum StorageBackend {
80    /// LMDB storage - requires lmdb feature
81    #[default]
82    Lmdb,
83    /// Filesystem storage - stores in ~/.hashtree/blobs/{prefix}/{subdir}/{hash}
84    Fs,
85}
86
87/// Storage configuration
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct StorageConfig {
90    /// Storage backend: "lmdb" (default) or "fs"
91    #[serde(default)]
92    pub backend: StorageBackend,
93    #[serde(default = "default_data_dir")]
94    pub data_dir: String,
95    #[serde(default = "default_max_size_gb")]
96    pub max_size_gb: u64,
97    #[serde(default = "default_storage_evict_orphans")]
98    pub evict_orphans: bool,
99    #[serde(default)]
100    pub s3: Option<S3Config>,
101}
102
103impl Default for StorageConfig {
104    fn default() -> Self {
105        Self {
106            backend: StorageBackend::default(),
107            data_dir: default_data_dir(),
108            max_size_gb: default_max_size_gb(),
109            evict_orphans: default_storage_evict_orphans(),
110            s3: None,
111        }
112    }
113}
114
115fn default_data_dir() -> String {
116    get_hashtree_dir()
117        .join("data")
118        .to_string_lossy()
119        .to_string()
120}
121
122fn default_max_size_gb() -> u64 {
123    10
124}
125
126fn default_storage_evict_orphans() -> bool {
127    true
128}
129
130/// S3-compatible storage configuration
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct S3Config {
133    pub endpoint: String,
134    pub bucket: String,
135    pub region: String,
136    #[serde(default)]
137    pub prefix: Option<String>,
138}
139
140/// Nostr relay configuration
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct NostrConfig {
143    #[serde(default = "default_relays")]
144    pub relays: Vec<String>,
145    #[serde(default)]
146    pub allowed_npubs: Vec<String>,
147    #[serde(default)]
148    pub socialgraph_root: Option<String>,
149    #[serde(default = "default_nostr_bootstrap_follows")]
150    pub bootstrap_follows: Vec<String>,
151    #[serde(default = "default_social_graph_crawl_depth", alias = "crawl_depth")]
152    pub social_graph_crawl_depth: u32,
153    /// Max follow distance to mirror into public event/profile indexes.
154    /// Defaults to social_graph_crawl_depth when unset.
155    #[serde(default)]
156    pub mirror_max_follow_distance: Option<u32>,
157    #[serde(default = "default_max_write_distance")]
158    pub max_write_distance: u32,
159    /// Max size for the trusted social graph store in GB (default: 10)
160    #[serde(default = "default_nostr_db_max_size_gb")]
161    pub db_max_size_gb: u64,
162    /// Max size for the social graph spambox store in GB (default: 1)
163    /// Set to 0 for memory-only spambox (no on-disk DB)
164    #[serde(default = "default_nostr_spambox_max_size_gb")]
165    pub spambox_max_size_gb: u64,
166    /// Require relays to support NIP-77 negentropy for mirror history sync.
167    #[serde(default)]
168    pub negentropy_only: bool,
169    /// Threshold for treating a user as overmuted in mirrored profile indexing/search.
170    #[serde(default = "default_nostr_overmute_threshold")]
171    pub overmute_threshold: f64,
172    /// Kinds mirrored from upstream relays for the trusted hashtree index.
173    #[serde(default = "default_nostr_mirror_kinds")]
174    pub mirror_kinds: Vec<u16>,
175    /// Authors per ordinary history chunk and between durable mirror-root publications.
176    #[serde(default = "default_nostr_history_sync_author_chunk_size")]
177    pub history_sync_author_chunk_size: usize,
178    /// Run a catch-up history sync after relay reconnects.
179    #[serde(default = "default_nostr_history_sync_on_reconnect")]
180    pub history_sync_on_reconnect: bool,
181}
182
183impl Default for NostrConfig {
184    fn default() -> Self {
185        Self {
186            relays: default_relays(),
187            allowed_npubs: vec![],
188            socialgraph_root: None,
189            bootstrap_follows: default_nostr_bootstrap_follows(),
190            social_graph_crawl_depth: default_social_graph_crawl_depth(),
191            mirror_max_follow_distance: None,
192            max_write_distance: default_max_write_distance(),
193            db_max_size_gb: default_nostr_db_max_size_gb(),
194            spambox_max_size_gb: default_nostr_spambox_max_size_gb(),
195            negentropy_only: false,
196            overmute_threshold: default_nostr_overmute_threshold(),
197            mirror_kinds: default_nostr_mirror_kinds(),
198            history_sync_author_chunk_size: default_nostr_history_sync_author_chunk_size(),
199            history_sync_on_reconnect: default_nostr_history_sync_on_reconnect(),
200        }
201    }
202}
203
204fn default_social_graph_crawl_depth() -> u32 {
205    2
206}
207
208fn default_nostr_bootstrap_follows() -> Vec<String> {
209    vec![DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB.to_string()]
210}
211
212fn default_nostr_overmute_threshold() -> f64 {
213    1.0
214}
215
216fn default_max_write_distance() -> u32 {
217    3
218}
219
220fn default_nostr_db_max_size_gb() -> u64 {
221    10
222}
223
224fn default_nostr_spambox_max_size_gb() -> u64 {
225    1
226}
227
228fn default_nostr_history_sync_on_reconnect() -> bool {
229    true
230}
231
232fn default_nostr_mirror_kinds() -> Vec<u16> {
233    vec![
234        0, 1, 3, 5, 6, 7, 16, 20, 1_111, 9_735, 10_000, 30_000, 30_023,
235    ]
236}
237
238fn default_nostr_history_sync_author_chunk_size() -> usize {
239    5_000
240}
241
242fn default_relays() -> Vec<String> {
243    DEFAULT_RELAYS.iter().map(|s| s.to_string()).collect()
244}
245
246/// File server (blossom) configuration
247#[derive(Debug, Clone, Serialize, Deserialize)]
248pub struct BlossomConfig {
249    /// Legacy servers field (both read and write)
250    #[serde(default)]
251    pub servers: Vec<String>,
252    /// Read-only file servers
253    #[serde(default = "default_read_servers")]
254    pub read_servers: Vec<String>,
255    /// Write-enabled file servers
256    #[serde(default = "default_write_servers")]
257    pub write_servers: Vec<String>,
258    /// Max upload size in MB
259    #[serde(default = "default_max_upload_mb")]
260    pub max_upload_mb: u64,
261    /// Require public Blossom and peer-fetched cached blobs to look encrypted.
262    #[serde(default = "default_require_random_untrusted_ingest")]
263    pub require_random_untrusted_ingest: bool,
264    /// Max number of concurrent blob uploads during push/repair.
265    #[serde(default = "default_upload_concurrency")]
266    pub upload_concurrency: usize,
267    /// Force upload all blobs, skipping "server already has" check
268    #[serde(default)]
269    pub force_upload: bool,
270}
271
272impl Default for BlossomConfig {
273    fn default() -> Self {
274        Self {
275            servers: vec![],
276            read_servers: default_read_servers(),
277            write_servers: default_write_servers(),
278            max_upload_mb: default_max_upload_mb(),
279            require_random_untrusted_ingest: default_require_random_untrusted_ingest(),
280            upload_concurrency: default_upload_concurrency(),
281            force_upload: false,
282        }
283    }
284}
285
286fn dedup_preserve_order(servers: Vec<String>) -> Vec<String> {
287    let mut seen = std::collections::HashSet::with_capacity(servers.len());
288    let mut out = Vec::with_capacity(servers.len());
289    for server in servers {
290        if seen.insert(server.clone()) {
291            out.push(server);
292        }
293    }
294    out
295}
296
297fn default_read_servers() -> Vec<String> {
298    DEFAULT_READ_SERVERS.iter().map(|s| s.to_string()).collect()
299}
300
301fn default_write_servers() -> Vec<String> {
302    DEFAULT_WRITE_SERVERS
303        .iter()
304        .map(|s| s.to_string())
305        .collect()
306}
307
308fn default_max_upload_mb() -> u64 {
309    100
310}
311
312fn default_require_random_untrusted_ingest() -> bool {
313    true
314}
315
316fn default_upload_concurrency() -> usize {
317    4
318}
319
320impl BlossomConfig {
321    /// Get all readable servers (read_servers + legacy servers + write_servers),
322    /// preserving configured priority order while deduplicating.
323    /// Dedicated read tiers come before write servers so CDN caches are tried
324    /// before direct origin fallbacks.
325    pub fn all_read_servers(&self) -> Vec<String> {
326        let mut servers = self.read_servers.clone();
327        servers.extend(self.servers.clone());
328        servers.extend(self.write_servers.clone());
329        if servers.is_empty() {
330            servers = default_read_servers();
331            servers.extend(default_write_servers());
332        }
333        dedup_preserve_order(servers)
334    }
335
336    /// Get all write servers (legacy + write_servers), preserving priority order.
337    pub fn all_write_servers(&self) -> Vec<String> {
338        let mut servers = self.servers.clone();
339        servers.extend(self.write_servers.clone());
340        if servers.is_empty() {
341            servers = default_write_servers();
342        }
343        dedup_preserve_order(servers)
344    }
345}
346
347/// Background sync configuration
348#[derive(Debug, Clone, Serialize, Deserialize)]
349pub struct SyncConfig {
350    #[serde(default)]
351    pub enabled: bool,
352    #[serde(default = "default_true")]
353    pub sync_own: bool,
354    #[serde(default)]
355    pub sync_followed: bool,
356    #[serde(default = "default_max_concurrent")]
357    pub max_concurrent: usize,
358    #[serde(default = "default_blossom_timeout_ms")]
359    pub blossom_timeout_ms: u64,
360}
361
362impl Default for SyncConfig {
363    fn default() -> Self {
364        Self {
365            enabled: false,
366            sync_own: true,
367            sync_followed: false,
368            max_concurrent: default_max_concurrent(),
369            blossom_timeout_ms: default_blossom_timeout_ms(),
370        }
371    }
372}
373
374/// htree self-update preferences. Reads `[updater]` from
375/// `~/.hashtree/config.toml`. Auto-check is on by default — `htree` will
376/// quietly check for a newer published binary at most once per
377/// `check_interval_hours` and print a one-liner to stderr when one exists.
378/// Auto-install is off by default; flip it on to install the new binary
379/// in the background and print the result.
380#[derive(Debug, Clone, Serialize, Deserialize)]
381pub struct UpdaterConfig {
382    #[serde(default = "default_true")]
383    pub auto_check: bool,
384    #[serde(default)]
385    pub auto_install: bool,
386    #[serde(default = "default_check_interval_hours")]
387    pub check_interval_hours: u32,
388}
389
390impl Default for UpdaterConfig {
391    fn default() -> Self {
392        Self {
393            auto_check: true,
394            auto_install: false,
395            check_interval_hours: default_check_interval_hours(),
396        }
397    }
398}
399
400fn default_check_interval_hours() -> u32 {
401    24
402}
403
404fn default_max_concurrent() -> usize {
405    4
406}
407
408fn default_blossom_timeout_ms() -> u64 {
409    10000
410}
411
412impl Config {
413    /// Load config from file, or create default if doesn't exist
414    pub fn load() -> Result<Self> {
415        let config_path = get_config_path();
416
417        if config_path.exists() {
418            let content = fs::read_to_string(&config_path).context("Failed to read config file")?;
419            toml::from_str(&content).context("Failed to parse config file")
420        } else {
421            let config = Config::default();
422            config.save()?;
423            Ok(config)
424        }
425    }
426
427    /// Load config, returning default on any error (no panic)
428    pub fn load_or_default() -> Self {
429        Self::load().unwrap_or_default()
430    }
431
432    /// Save config to file
433    pub fn save(&self) -> Result<()> {
434        let config_path = get_config_path();
435
436        if let Some(parent) = config_path.parent() {
437            fs::create_dir_all(parent)?;
438        }
439
440        let content = toml::to_string_pretty(self)?;
441        fs::write(&config_path, content)?;
442
443        Ok(())
444    }
445}
446
447/// Get the hashtree directory (~/.hashtree)
448pub fn get_hashtree_dir() -> PathBuf {
449    if let Ok(dir) = std::env::var("HTREE_CONFIG_DIR") {
450        return PathBuf::from(dir);
451    }
452    dirs::home_dir()
453        .unwrap_or_else(|| PathBuf::from("."))
454        .join(".hashtree")
455}
456
457/// Get the config file path (~/.hashtree/config.toml)
458pub fn get_config_path() -> PathBuf {
459    get_hashtree_dir().join("config.toml")
460}
461
462/// Get the keys file path (~/.hashtree/keys)
463pub fn get_keys_path() -> PathBuf {
464    get_hashtree_dir().join("keys")
465}
466
467/// Get the public alias file path (~/.hashtree/aliases)
468pub fn get_aliases_path() -> PathBuf {
469    get_hashtree_dir().join("aliases")
470}
471
472/// A stored key entry from the keys file
473#[derive(Debug, Clone)]
474pub struct KeyEntry {
475    /// The raw identity token (for example nsec, npub, or hex)
476    pub secret: String,
477    /// Optional alias/petname
478    pub alias: Option<String>,
479}
480
481/// Parse the keys file content into key entries
482/// Format: `<identity> [alias]` per line
483/// Lines starting with # are comments
484pub fn parse_keys_file(content: &str) -> Vec<KeyEntry> {
485    let mut entries = Vec::new();
486    for line in content.lines() {
487        let line = line.trim();
488        if line.is_empty() || line.starts_with('#') {
489            continue;
490        }
491        let parts: Vec<&str> = line.splitn(2, ' ').collect();
492        let secret = parts[0].to_string();
493        let alias = parts.get(1).map(|s| s.trim().to_string());
494        entries.push(KeyEntry { secret, alias });
495    }
496    entries
497}
498
499/// Read and parse keys file, returning the first key's secret
500/// Returns None if file doesn't exist or is empty
501pub fn read_first_key() -> Option<String> {
502    let keys_path = get_keys_path();
503    let content = std::fs::read_to_string(&keys_path).ok()?;
504    let entries = parse_keys_file(&content);
505    entries.into_iter().next().map(|e| e.secret)
506}
507
508/// Get the auth cookie path (~/.hashtree/auth.cookie)
509pub fn get_auth_cookie_path() -> PathBuf {
510    get_hashtree_dir().join("auth.cookie")
511}
512
513/// Get the data directory from config (defaults to ~/.hashtree/data)
514/// Can be overridden with HTREE_DATA_DIR environment variable
515pub fn get_data_dir() -> PathBuf {
516    if let Ok(dir) = std::env::var("HTREE_DATA_DIR") {
517        return PathBuf::from(dir);
518    }
519    let config = Config::load_or_default();
520    PathBuf::from(&config.storage.data_dir)
521}
522
523/// Detect a local hashtree daemon on localhost and return its Blossom base URL.
524pub fn detect_local_daemon_url(bind_address: Option<&str>) -> Option<String> {
525    use std::net::{SocketAddr, TcpStream};
526    use std::time::Duration;
527
528    if !prefer_local_daemon() {
529        return None;
530    }
531
532    let port = local_daemon_port(bind_address);
533    if port == 0 {
534        return None;
535    }
536
537    let addr = SocketAddr::from(([127, 0, 0, 1], port));
538    let timeout = Duration::from_millis(100);
539    TcpStream::connect_timeout(&addr, timeout).ok()?;
540    Some(format!("http://127.0.0.1:{}", port))
541}
542
543/// Detect local Nostr relay URLs (e.g., hashtree daemon or local relay on common ports).
544pub fn detect_local_relay_urls(bind_address: Option<&str>) -> Vec<String> {
545    let mut relays = Vec::new();
546
547    if let Some(list) =
548        parse_env_list("NOSTR_LOCAL_RELAY").or_else(|| parse_env_list("HTREE_LOCAL_RELAY"))
549    {
550        for raw in list {
551            if let Some(url) = normalize_relay_url(&raw) {
552                relays.push(url);
553            }
554        }
555    }
556
557    if let Some(base) = detect_local_daemon_url(bind_address) {
558        if let Some(ws) = normalize_relay_url(&base) {
559            let ws = ws.trim_end_matches('/');
560            let ws = if ws.contains("/ws") {
561                ws.to_string()
562            } else {
563                format!("{}/ws", ws)
564            };
565            relays.push(ws);
566        }
567    }
568
569    let mut ports = parse_env_ports("NOSTR_LOCAL_RELAY_PORTS");
570    if ports.is_empty() {
571        ports.push(4869);
572    }
573
574    let daemon_port = local_daemon_port(bind_address);
575    for port in ports {
576        if port == 0 || port == daemon_port {
577            continue;
578        }
579        if local_port_open(port) {
580            relays.push(format!("ws://127.0.0.1:{port}"));
581        }
582    }
583
584    dedupe_relays(relays)
585}
586
587/// Resolve relays using environment overrides and optional local relay discovery.
588pub fn resolve_relays(config_relays: &[String], bind_address: Option<&str>) -> Vec<String> {
589    let mut base = match parse_env_list("NOSTR_RELAYS") {
590        Some(list) => list,
591        None => config_relays.to_vec(),
592    };
593
594    base = base
595        .into_iter()
596        .filter_map(|r| normalize_relay_url(&r))
597        .collect();
598
599    if !prefer_local_relay() {
600        return dedupe_relays(base);
601    }
602
603    let mut combined = detect_local_relay_urls(bind_address);
604    combined.extend(base);
605    dedupe_relays(combined)
606}
607
608fn local_daemon_port(bind_address: Option<&str>) -> u16 {
609    let default_port = 8080;
610    let Some(addr) = bind_address else {
611        return default_port;
612    };
613    if let Ok(sock) = addr.parse::<std::net::SocketAddr>() {
614        return sock.port();
615    }
616    if let Some((_, port_str)) = addr.rsplit_once(':') {
617        if let Ok(port) = port_str.parse::<u16>() {
618            return port;
619        }
620    }
621    default_port
622}
623
624fn prefer_local_relay() -> bool {
625    for key in ["NOSTR_PREFER_LOCAL", "HTREE_PREFER_LOCAL_RELAY"] {
626        if let Ok(val) = std::env::var(key) {
627            let val = val.trim().to_lowercase();
628            return !matches!(val.as_str(), "0" | "false" | "no" | "off");
629        }
630    }
631    true
632}
633
634fn prefer_local_daemon() -> bool {
635    for key in [
636        "HTREE_LOCAL_DAEMON_ONLY",
637        "HTREE_PREFER_LOCAL_DAEMON",
638        "NOSTR_PREFER_LOCAL",
639        "HTREE_PREFER_LOCAL_RELAY",
640    ] {
641        if let Ok(val) = std::env::var(key) {
642            let val = val.trim().to_lowercase();
643            return !matches!(val.as_str(), "0" | "false" | "no" | "off");
644        }
645    }
646    false
647}
648
649fn parse_env_list(var: &str) -> Option<Vec<String>> {
650    let value = std::env::var(var).ok()?;
651    let mut items = Vec::new();
652    for part in value.split([',', ';', '\n', '\t', ' ']) {
653        let trimmed = part.trim();
654        if !trimmed.is_empty() {
655            items.push(trimmed.to_string());
656        }
657    }
658    if items.is_empty() {
659        None
660    } else {
661        Some(items)
662    }
663}
664
665fn parse_env_ports(var: &str) -> Vec<u16> {
666    let Some(list) = parse_env_list(var) else {
667        return Vec::new();
668    };
669    list.into_iter()
670        .filter_map(|item| item.parse::<u16>().ok())
671        .collect()
672}
673
674fn normalize_relay_url(raw: &str) -> Option<String> {
675    let trimmed = raw.trim();
676    if trimmed.is_empty() {
677        return None;
678    }
679    let trimmed = trimmed.trim_end_matches('/');
680    let lower = trimmed.to_lowercase();
681    if lower.starts_with("ws://") || lower.starts_with("wss://") {
682        return Some(trimmed.to_string());
683    }
684    if lower.starts_with("http://") {
685        return Some(format!("ws://{}", &trimmed[7..]));
686    }
687    if lower.starts_with("https://") {
688        return Some(format!("wss://{}", &trimmed[8..]));
689    }
690    Some(format!("ws://{}", trimmed))
691}
692
693fn local_port_open(port: u16) -> bool {
694    use std::net::{SocketAddr, TcpStream};
695    use std::time::Duration;
696
697    let addr = SocketAddr::from(([127, 0, 0, 1], port));
698    let timeout = Duration::from_millis(100);
699    TcpStream::connect_timeout(&addr, timeout).is_ok()
700}
701
702fn dedupe_relays(relays: Vec<String>) -> Vec<String> {
703    use std::collections::HashSet;
704    let mut seen = HashSet::new();
705    let mut out = Vec::new();
706    for relay in relays {
707        let key = relay.trim_end_matches('/').to_lowercase();
708        if seen.insert(key) {
709            out.push(relay);
710        }
711    }
712    out
713}
714
715#[cfg(test)]
716mod tests {
717    use super::*;
718    use std::net::TcpListener;
719    use std::sync::Mutex;
720
721    static ENV_LOCK: Mutex<()> = Mutex::new(());
722
723    struct EnvGuard {
724        key: &'static str,
725        prev: Option<String>,
726    }
727
728    impl EnvGuard {
729        fn set(key: &'static str, value: &str) -> Self {
730            let prev = std::env::var(key).ok();
731            std::env::set_var(key, value);
732            Self { key, prev }
733        }
734
735        fn clear(key: &'static str) -> Self {
736            let prev = std::env::var(key).ok();
737            std::env::remove_var(key);
738            Self { key, prev }
739        }
740    }
741
742    impl Drop for EnvGuard {
743        fn drop(&mut self) {
744            if let Some(prev) = &self.prev {
745                std::env::set_var(self.key, prev);
746            } else {
747                std::env::remove_var(self.key);
748            }
749        }
750    }
751
752    #[test]
753    fn test_default_config() {
754        let config = Config::default();
755        assert!(!config.blossom.read_servers.is_empty());
756        assert!(!config.blossom.write_servers.is_empty());
757        assert_eq!(
758            config.blossom.upload_concurrency,
759            default_upload_concurrency()
760        );
761        assert!(!config.nostr.relays.is_empty());
762        assert!(config
763            .nostr
764            .relays
765            .contains(&"wss://temp.iris.to".to_string()));
766    }
767
768    #[test]
769    fn test_parse_empty_config() {
770        let config: Config = toml::from_str("").unwrap();
771        assert!(!config.blossom.read_servers.is_empty());
772    }
773
774    #[test]
775    fn test_parse_partial_config() {
776        let toml = r#"
777[blossom]
778write_servers = ["https://custom.server"]
779upload_concurrency = 24
780"#;
781        let config: Config = toml::from_str(toml).unwrap();
782        assert_eq!(config.blossom.write_servers, vec!["https://custom.server"]);
783        assert_eq!(config.blossom.upload_concurrency, 24);
784        assert!(!config.blossom.read_servers.is_empty());
785    }
786
787    #[test]
788    fn test_all_servers() {
789        let config = BlossomConfig {
790            servers: vec!["https://legacy.server".to_string()],
791            ..BlossomConfig::default()
792        };
793
794        let read = config.all_read_servers();
795        assert!(read.contains(&"https://legacy.server".to_string()));
796        assert!(read.contains(&"https://cdn.iris.to".to_string()));
797        assert!(read.contains(&"https://blossom.primal.net".to_string()));
798        assert!(read.contains(&"https://upload.iris.to".to_string()));
799
800        let write = config.all_write_servers();
801        assert!(write.contains(&"https://legacy.server".to_string()));
802        assert!(write.contains(&"https://upload.iris.to".to_string()));
803    }
804
805    #[test]
806    fn test_all_servers_fall_back_to_defaults_when_explicitly_empty() {
807        let config = BlossomConfig {
808            servers: vec![],
809            read_servers: vec![],
810            write_servers: vec![],
811            max_upload_mb: default_max_upload_mb(),
812            require_random_untrusted_ingest: default_require_random_untrusted_ingest(),
813            upload_concurrency: default_upload_concurrency(),
814            force_upload: false,
815        };
816
817        let mut expected_read = default_read_servers();
818        expected_read.extend(default_write_servers());
819        let expected_read = dedup_preserve_order(expected_read);
820        assert_eq!(config.all_read_servers(), expected_read);
821        assert_eq!(
822            config.all_read_servers().first().map(String::as_str),
823            Some("https://cdn.iris.to")
824        );
825        assert_eq!(config.all_write_servers(), default_write_servers());
826    }
827
828    #[test]
829    fn test_storage_backend_default() {
830        let config = Config::default();
831        assert_eq!(config.storage.backend, StorageBackend::Lmdb);
832    }
833
834    #[test]
835    fn test_storage_backend_lmdb() {
836        let toml = r#"
837[storage]
838backend = "lmdb"
839"#;
840        let config: Config = toml::from_str(toml).unwrap();
841        assert_eq!(config.storage.backend, StorageBackend::Lmdb);
842    }
843
844    #[test]
845    fn test_storage_backend_fs_explicit() {
846        let toml = r#"
847[storage]
848backend = "fs"
849"#;
850        let config: Config = toml::from_str(toml).unwrap();
851        assert_eq!(config.storage.backend, StorageBackend::Fs);
852    }
853
854    #[test]
855    fn test_storage_orphan_eviction_defaults_on_and_allows_override() {
856        assert!(Config::default().storage.evict_orphans);
857
858        let toml = r#"
859[storage]
860evict_orphans = false
861"#;
862        let config: Config = toml::from_str(toml).unwrap();
863        assert!(!config.storage.evict_orphans);
864    }
865
866    #[test]
867    fn test_parse_keys_file() {
868        let content = r#"
869nsec1abc123 self
870# comment line
871nsec1def456 work
872
873nsec1ghi789
874"#;
875        let entries = parse_keys_file(content);
876        assert_eq!(entries.len(), 3);
877        assert_eq!(entries[0].secret, "nsec1abc123");
878        assert_eq!(entries[0].alias, Some("self".to_string()));
879        assert_eq!(entries[1].secret, "nsec1def456");
880        assert_eq!(entries[1].alias, Some("work".to_string()));
881        assert_eq!(entries[2].secret, "nsec1ghi789");
882        assert_eq!(entries[2].alias, None);
883    }
884
885    #[test]
886    fn test_local_daemon_port_default() {
887        assert_eq!(local_daemon_port(None), 8080);
888    }
889
890    #[test]
891    fn test_local_daemon_port_parses_ipv4() {
892        assert_eq!(local_daemon_port(Some("127.0.0.1:9090")), 9090);
893    }
894
895    #[test]
896    fn test_local_daemon_port_parses_anyhost() {
897        assert_eq!(local_daemon_port(Some("0.0.0.0:7070")), 7070);
898    }
899
900    #[test]
901    fn test_local_daemon_port_parses_ipv6() {
902        assert_eq!(local_daemon_port(Some("[::1]:6060")), 6060);
903    }
904
905    #[test]
906    fn test_local_daemon_port_parses_hostname() {
907        assert_eq!(local_daemon_port(Some("localhost:5050")), 5050);
908    }
909
910    #[test]
911    fn test_local_daemon_port_invalid() {
912        assert_eq!(local_daemon_port(Some("localhost")), 8080);
913    }
914
915    #[test]
916    fn test_detect_local_daemon_url_respects_prefer_local_flag() {
917        let _lock = ENV_LOCK.lock().unwrap();
918        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
919        let port = listener.local_addr().unwrap().port();
920        let _prefer = EnvGuard::set("NOSTR_PREFER_LOCAL", "0");
921
922        assert_eq!(
923            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
924            None
925        );
926    }
927
928    #[test]
929    fn test_detect_local_daemon_url_requires_opt_in() {
930        let _lock = ENV_LOCK.lock().unwrap();
931        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
932        let port = listener.local_addr().unwrap().port();
933        let _prefer = EnvGuard::clear("HTREE_PREFER_LOCAL_DAEMON");
934        let _prefer_nostr = EnvGuard::clear("NOSTR_PREFER_LOCAL");
935        let _prefer_relay = EnvGuard::clear("HTREE_PREFER_LOCAL_RELAY");
936
937        assert_eq!(
938            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
939            None
940        );
941    }
942
943    #[test]
944    fn test_detect_local_daemon_url_uses_opt_in_flag() {
945        let _lock = ENV_LOCK.lock().unwrap();
946        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
947        let port = listener.local_addr().unwrap().port();
948        let _prefer = EnvGuard::set("HTREE_PREFER_LOCAL_DAEMON", "1");
949
950        assert_eq!(
951            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
952            Some(format!("http://127.0.0.1:{port}"))
953        );
954    }
955
956    #[test]
957    fn test_strict_local_daemon_detection_uses_configured_bind_port() {
958        let _lock = ENV_LOCK.lock().unwrap();
959        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
960        let port = listener.local_addr().unwrap().port();
961        let _strict = EnvGuard::set("HTREE_LOCAL_DAEMON_ONLY", "1");
962        let _prefer = EnvGuard::clear("HTREE_PREFER_LOCAL_DAEMON");
963
964        assert_eq!(
965            detect_local_daemon_url(Some(&format!("127.0.0.1:{port}"))),
966            Some(format!("http://127.0.0.1:{port}"))
967        );
968    }
969
970    #[test]
971    fn test_resolve_relays_prefers_local() {
972        let _lock = ENV_LOCK.lock().unwrap();
973        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
974        let port = listener.local_addr().unwrap().port();
975
976        let _prefer = EnvGuard::set("NOSTR_PREFER_LOCAL", "1");
977        let _ports = EnvGuard::set("NOSTR_LOCAL_RELAY_PORTS", &port.to_string());
978        let _relays = EnvGuard::clear("NOSTR_RELAYS");
979
980        let base = vec!["wss://relay.example".to_string()];
981        let resolved = resolve_relays(&base, Some("127.0.0.1:0"));
982
983        assert!(!resolved.is_empty());
984        assert_eq!(resolved[0], format!("ws://127.0.0.1:{port}"));
985        assert!(resolved.contains(&"wss://relay.example".to_string()));
986    }
987
988    #[test]
989    fn test_resolve_relays_env_override() {
990        let _lock = ENV_LOCK.lock().unwrap();
991        let _prefer = EnvGuard::set("NOSTR_PREFER_LOCAL", "0");
992        let _relays = EnvGuard::set("NOSTR_RELAYS", "wss://relay.one,wss://relay.two");
993
994        let base = vec!["wss://relay.example".to_string()];
995        let resolved = resolve_relays(&base, Some("127.0.0.1:0"));
996
997        assert_eq!(
998            resolved,
999            vec!["wss://relay.one".to_string(), "wss://relay.two".to_string()]
1000        );
1001    }
1002
1003    #[test]
1004    fn test_nostr_config_defaults_include_mirror_settings() {
1005        let config = NostrConfig::default();
1006
1007        assert_eq!(config.social_graph_crawl_depth, 2);
1008        assert_eq!(config.mirror_max_follow_distance, None);
1009        assert_eq!(config.max_write_distance, 3);
1010        assert!(config.socialgraph_root.is_none());
1011        assert_eq!(
1012            config.bootstrap_follows,
1013            vec![DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB.to_string()]
1014        );
1015        assert!(!config.negentropy_only);
1016        assert_eq!(config.overmute_threshold, 1.0);
1017        assert_eq!(
1018            config.mirror_kinds,
1019            vec![0, 1, 3, 5, 6, 7, 16, 20, 1_111, 9_735, 10_000, 30_000, 30_023]
1020        );
1021        assert_eq!(config.history_sync_author_chunk_size, 5_000);
1022        assert!(config.history_sync_on_reconnect);
1023    }
1024
1025    #[test]
1026    fn test_nostr_config_deserializes_mirror_settings() {
1027        let config: NostrConfig = toml::from_str(
1028            r#"
1029relays = ["wss://relay.example"]
1030socialgraph_root = "npub1test"
1031bootstrap_follows = []
1032social_graph_crawl_depth = 6
1033mirror_max_follow_distance = 2
1034max_write_distance = 7
1035negentropy_only = true
1036overmute_threshold = 1.5
1037mirror_kinds = [0, 1, 3, 6, 7, 9735]
1038history_sync_author_chunk_size = 512
1039history_sync_on_reconnect = false
1040"#,
1041        )
1042        .expect("deserialize nostr config");
1043
1044        assert_eq!(config.relays, vec!["wss://relay.example".to_string()]);
1045        assert_eq!(config.socialgraph_root.as_deref(), Some("npub1test"));
1046        assert!(config.bootstrap_follows.is_empty());
1047        assert_eq!(config.social_graph_crawl_depth, 6);
1048        assert_eq!(config.mirror_max_follow_distance, Some(2));
1049        assert_eq!(config.max_write_distance, 7);
1050        assert!(config.negentropy_only);
1051        assert_eq!(config.overmute_threshold, 1.5);
1052        assert_eq!(config.mirror_kinds, vec![0, 1, 3, 6, 7, 9_735]);
1053        assert_eq!(config.history_sync_author_chunk_size, 512);
1054        assert!(!config.history_sync_on_reconnect);
1055    }
1056
1057    #[test]
1058    fn test_nostr_config_deserializes_legacy_crawl_depth_alias() {
1059        let config: NostrConfig = toml::from_str(
1060            r#"
1061relays = ["wss://relay.example"]
1062crawl_depth = 5
1063"#,
1064        )
1065        .expect("deserialize nostr config");
1066
1067        assert_eq!(config.social_graph_crawl_depth, 5);
1068    }
1069}