upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/config.rs
blob: 41175076b522ce63389b82af9027840bce6c8c5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use anyhow::{Context, Result};
use nostr::{FromBech32, PublicKey, ToBech32};
use serde::Deserialize;
use std::path::PathBuf;

#[derive(Debug, Deserialize)]
pub struct AppConfig {
    pub discovery: DiscoveryConfig,
    pub servers: ServersConfig,
    pub storage: StorageConfig,
    pub signing: Option<SigningConfig>,
    pub nip46: Option<Nip46Config>,
}

#[derive(Debug, Deserialize)]
pub struct DiscoveryConfig {
    pub index_relays: Vec<String>,
    #[serde(default = "default_poll_interval")]
    pub poll_interval_secs: u64,
}

fn default_poll_interval() -> u64 {
    300
}

#[derive(Debug, Deserialize)]
pub struct ServersConfig {
    pub known: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct StorageConfig {
    #[serde(default = "default_mirror_dir")]
    pub mirror_dir: PathBuf,
    #[serde(default = "default_database")]
    pub database: PathBuf,
    #[serde(default = "default_health_port")]
    pub health_port: u16,
}

fn default_health_port() -> u16 {
    7335
}

fn default_mirror_dir() -> PathBuf {
    dirs::data_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("grasp-mirror")
        .join("repos")
}

fn default_database() -> PathBuf {
    dirs::data_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("grasp-mirror")
        .join("mirror.db")
}

#[derive(Debug, Deserialize)]
pub struct SigningConfig {
    pub key_file: PathBuf,
}

#[derive(Debug, Deserialize)]
pub struct Nip46Config {
    pub relays: Vec<String>,
    #[serde(default = "default_signing_timeout")]
    pub signing_timeout_secs: u64,
}

fn default_signing_timeout() -> u64 {
    604800
}

pub struct ResolvedConfig {
    pub discovery: DiscoveryConfig,
    pub servers: ServersConfig,
    pub storage: StorageConfig,
    pub signing: Option<SigningConfig>,
    pub nip46: Option<Nip46Config>,
    pub npubs: Vec<PublicKey>,
}

impl ResolvedConfig {
    pub fn load(config_path: &PathBuf) -> Result<Self> {
        let _ = dotenvy::dotenv();

        let config_str = std::fs::read_to_string(config_path)
            .with_context(|| format!("failed to read config from {:?}", config_path))?;
        let app: AppConfig = toml::from_str(&config_str).context("failed to parse config.toml")?;

        let npubs = Self::load_npubs()?;

        std::fs::create_dir_all(&app.storage.mirror_dir)
            .context("failed to create mirror directory")?;
        if let Some(parent) = app.storage.database.parent() {
            std::fs::create_dir_all(parent).context("failed to create database directory")?;
        }

        Ok(Self {
            discovery: app.discovery,
            servers: app.servers,
            storage: app.storage,
            signing: app.signing,
            nip46: app.nip46,
            npubs,
        })
    }

    fn load_npubs() -> Result<Vec<PublicKey>> {
        let raw = std::env::var("MIRROR_NPUBS").unwrap_or_default();
        let mut npubs = Vec::new();

        for entry in raw.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()) {
            let pk = if entry.starts_with("npub1") {
                PublicKey::from_bech32(entry)
                    .with_context(|| format!("invalid npub: {}", entry))?
            } else {
                let bytes = hex::decode(entry)
                    .with_context(|| format!("invalid hex pubkey: {}", entry))?;
                PublicKey::from_slice(&bytes)
                    .with_context(|| format!("invalid pubkey bytes: {}", entry))?
            };
            npubs.push(pk);
        }

        if npubs.is_empty() {
            tracing::warn!("MIRROR_NPUBS is empty — no pubkeys to mirror");
        }

        Ok(npubs)
    }

    pub fn relay_urls(&self) -> Vec<String> {
        let mut relays = self.discovery.index_relays.clone();
        for server in &self.servers.known {
            let relay = format!(
                "wss://{}",
                server
                    .trim_start_matches("https://")
                    .trim_start_matches("http://")
            );
            if !relays.contains(&relay) {
                relays.push(relay);
            }
        }
        relays
    }
}