master
Colby Knox v2.1.10: Every request to the wiki says where Parts Search runs (the CLI thread, PR #7), so the wiki can tell Hydrogen… 75e82ba
//! X-Adom-Host: which Adom host launched this CLI, so the wiki can tell local
//! Hydrogen traffic from cloud containers and bare machines. The first rule
//! that matches wins:
//! 1. ADOM_HOST, when set and not empty (any launcher can claim its CLIs);
//! 2. the first line of ~/.adom/host (Hydrogen rewrites it on every launch);
//! 3. `cloud` when /var/run/adom/api-key exists (an Adom cloud container);
//! 4. the OS name: windows, macos or linux.
//!
//! Read once per process, never cached across runs. Only a short, cleaned
//! name and version goes out: never a path, a username or a machine name.

use std::path::Path;
use std::sync::OnceLock;

pub const HEADER: &str = "X-Adom-Host";
const MAX_LEN: usize = 80;

pub fn value() -> &'static str {
    static V: OnceLock<String> = OnceLock::new();
    V.get_or_init(|| {
        let home = std::env::var_os("HOME")
            .or_else(|| std::env::var_os("USERPROFILE"))
            .filter(|h| !h.is_empty())
            .map(std::path::PathBuf::from);
        detect(
            std::env::var("ADOM_HOST").ok().as_deref(),
            home.as_deref().map(|h| h.join(".adom").join("host")).as_deref(),
            Path::new("/var/run/adom/api-key"),
            os_name(),
        )
    })
}

fn os_name() -> &'static str {
    match std::env::consts::OS {
        "macos" => "macos",
        "windows" => "windows",
        _ => "linux",
    }
}

fn detect(env: Option<&str>, host_file: Option<&Path>, cloud_key: &Path, os: &str) -> String {
    if let Some(v) = env.map(clean).filter(|v| !v.is_empty()) {
        return v;
    }
    if let Some(v) = host_file
        .and_then(|p| std::fs::read_to_string(p).ok())
        .and_then(|s| s.lines().next().map(clean))
        .filter(|v| !v.is_empty())
    {
        return v;
    }
    if cloud_key.exists() {
        return "cloud".into();
    }
    os.into()
}

/// Keep `[A-Za-z0-9._+/ -]`, trimmed, at most 80 characters.
fn clean(s: &str) -> String {
    let kept: String = s
        .trim()
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '/' | ' ' | '-'))
        .take(MAX_LEN)
        .collect();
    kept.trim().to_string()
}

/// X-Adom-Run: `background` when ADOM_RUN=background (a scheduled or hook
/// run, such as adom/hook's cron), so the wiki counts it as background traffic
/// rather than a person. A normal run sends nothing.
pub const RUN_HEADER: &str = "X-Adom-Run";

pub fn run_background() -> bool {
    is_background(std::env::var("ADOM_RUN").ok().as_deref())
}

/// Both headers on one ureq request.
pub fn tag(req: ureq::Request) -> ureq::Request {
    let req = req.set(HEADER, value());
    if run_background() { req.set(RUN_HEADER, "background") } else { req }
}

fn is_background(v: Option<&str>) -> bool {
    v.map(|s| s.trim().eq_ignore_ascii_case("background")).unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn dir(tag: &str) -> std::path::PathBuf {
        let d = std::env::temp_dir().join(format!("partssearch-host-{}-{tag}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn the_first_matching_rule_wins() {
        let d = dir("rules");
        let file = d.join("host");
        let key = d.join("api-key");
        // nothing present: the OS
        assert_eq!(detect(None, Some(&file), &key, "macos"), "macos");
        // a cloud container
        std::fs::write(&key, "k").unwrap();
        assert_eq!(detect(None, Some(&file), &key, "linux"), "cloud");
        // Hydrogen's file beats the cloud key; only the first line, trimmed
        std::fs::write(&file, "  hydrogen-desktop/1.0.780  \nsecond line\n").unwrap();
        assert_eq!(detect(None, Some(&file), &key, "linux"), "hydrogen-desktop/1.0.780");
        // ADOM_HOST beats everything; an empty one is ignored
        assert_eq!(detect(Some("adom-bridge/2.1.208"), Some(&file), &key, "linux"), "adom-bridge/2.1.208");
        assert_eq!(detect(Some("  "), Some(&file), &key, "linux"), "hydrogen-desktop/1.0.780");
        // an empty file falls through
        std::fs::write(&file, "\n").unwrap();
        assert_eq!(detect(None, Some(&file), &key, "linux"), "cloud");
    }

    #[test]
    fn values_are_cleaned_and_capped() {
        assert_eq!(clean("Claude Desktop/1.2 (C:\\Users\\me)"), "Claude Desktop/1.2 CUsersme");
        assert_eq!(clean("a\r\nb\u{e9}c"), "abc");
        assert_eq!(clean(&"x".repeat(200)).len(), 80);
    }

    #[test]
    fn only_adom_run_background_marks_the_run() {
        assert!(is_background(Some("background")));
        assert!(is_background(Some(" Background ")));
        assert!(!is_background(Some("")));
        assert!(!is_background(Some("foreground")));
        assert!(!is_background(None));
    }
}