atagen

malice

public
Star0
Watch0
38a9760b78e47d373dfb35d3882a586dc9587211
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
crates/malice-push/src/env.rsRust38 lines1.4 KB
1
use std::path::Path;
2
3
use crate::{Allowlist, Sender, Vapid};
4
5
/// `MALICE_PUBLIC_URL`, the origin browsers and the homeserver reach this server at.
6
pub fn public_url() -> Option<String> {
7
    let url = std::env::var("MALICE_PUBLIC_URL").ok()?;
8
    let url = url.trim().trim_end_matches('/');
9
    match url::Url::parse(url) {
10
        Ok(parsed) if matches!(parsed.scheme(), "http" | "https") && parsed.has_host() => {
11
            Some(url.to_owned())
12
        }
13
        _ => {
14
            tracing::warn!("ignoring MALICE_PUBLIC_URL, it is not an http(s) URL");
15
            None
16
        }
17
    }
18
}
19
20
/// The VAPID `sub`: `MALICE_PUSH_CONTACT`, else the public URL.
21
pub fn contact(public_url: Option<&str>) -> String {
22
    std::env::var("MALICE_PUSH_CONTACT")
23
        .ok()
24
        .map(|contact| contact.trim().to_owned())
25
        .filter(|contact| contact.starts_with("mailto:") || contact.starts_with("https://"))
26
        .or_else(|| {
27
            public_url
28
                .filter(|url| url.starts_with("https://"))
29
                .map(str::to_owned)
30
        })
31
        .unwrap_or_else(|| "mailto:webpush@localhost".to_owned())
32
}
33
34
/// A sender with the VAPID key kept in `dir`, configured from the environment.
35
pub fn sender(dir: &Path, public_url: Option<&str>) -> Result<Sender, String> {
36
    let vapid = Vapid::load_or_create(&dir.join("vapid.pk8"))?;
37
    Sender::new(vapid, contact(public_url), Allowlist::from_env())
38
}