Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

10.6 KB
Raw Blame
//! The RustCord user registry: who uses RustCord, since when, and whether
//! they're on it right now. It's what the RustCord badge on profiles reads.
//!
//! A small service (see `server/` at the repository root) keeps one row per
//! user in a private database: a key, the day they first showed up, and when
//! they were last seen. The key is a SHA-256 of the Discord user ID: the
//! service stores no ID, though anyone who already has an ID can work out its
//! key (that is how lookups work). Its rows can't be listed: a client can
//! only ask about users whose IDs it already has.
//!
//! While you're logged in, RustCord says hello every few minutes (that both
//! registers you and marks you as online). When a profile is drawn it asks
//! whether that user is on RustCord (`lookup`), and remembers the answer for
//! a few minutes. With "Show that I use RustCord" off it asks the service to
//! hide your row instead of saying hello.

use crate::backend::{Emitter, Event};
use discord::model::Id;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::Duration;

/// The service's address, given when RustCord is built: the
/// `RUSTCORD_REGISTRY_URL` environment variable (`server/README.md`). A build
/// without one has no registry, and nobody gets a badge in it.
const BUILT_IN_URL: Option<&str> = option_env!("RUSTCORD_REGISTRY_URL");

/// How often RustCord says hello, and how long after the last hello someone still
/// counts as "using RustCord right now" (two missed hellos).
const HELLO_EVERY: Duration = Duration::from_secs(300);
pub const ONLINE_FOR_SECS: u64 = 660;
/// How long an answer about someone is kept before asking again.
pub const ANSWER_FRESH_FOR: Duration = Duration::from_secs(300);
/// Most users one lookup asks about (the service's limit).
pub const MAX_LOOKUP: usize = 50;

/// Where the registry lives: `RUSTCORD_REGISTRY_URL` when running (to try a
/// registry of your own), else the address RustCord was built with. None =
/// off. Only https, or http on this PC (`node server/dev.mjs`).
pub fn url() -> Option<String> {
    let url = std::env::var("RUSTCORD_REGISTRY_URL").ok().or_else(|| BUILT_IN_URL.map(String::from))?;
    let url = url.trim().trim_end_matches('/');
    allowed(url).then(|| url.to_string())
}

/// Whether `url` may be the registry: https, or http only when the host is
/// exactly this PC, and never with a user name or password in it
/// (`http://127.0.0.1:[email protected]` goes to host.example).
fn allowed(url: &str) -> bool {
    let Ok(u) = url::Url::parse(url) else { return false };
    if !u.username().is_empty() || u.password().is_some() {
        return false;
    }
    match u.scheme() {
        "https" => u.host().is_some(),
        "http" => matches!(u.host_str(), Some("127.0.0.1" | "localhost")),
        _ => false,
    }
}

/// A user's row key: the hex SHA-256 of "rustcord-user:<id>".
pub fn key(user: Id) -> String {
    let digest = Sha256::digest(format!("rustcord-user:{user}").as_bytes());
    digest.iter().map(|b| format!("{b:02x}")).collect()
}

/// The service's answer about some users.
#[derive(Clone, Debug, Default)]
pub struct Answer {
    /// The service's clock when it answered (Unix seconds).
    pub now: u64,
    /// Everyone asked about: Some((joined, last seen)) for RustCord users.
    pub users: Vec<(Id, Option<(u64, u64)>)>,
}

impl Answer {
    /// Read the service's reply for the users it was asked about.
    pub fn parse(v: &Value, asked: &[Id]) -> Option<Answer> {
        let rows: HashMap<&str, (u64, u64)> =
            v["users"].as_object()?.iter().filter_map(|(k, e)| Some((k.as_str(), (e.get(0)?.as_u64()?, e.get(1)?.as_u64()?)))).collect();
        let users = asked.iter().map(|id| (*id, rows.get(key(*id).as_str()).copied())).collect();
        Some(Answer { now: v["now"].as_u64()?, users })
    }
}

/// What a profile shows for one user.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Membership {
    /// Unix seconds.
    pub joined: u64,
    pub online: bool,
}

/// The longest answer that is read. 50 keys answer in about 5 KB, so anything
/// near this isn't the registry's.
const MAX_ANSWER: usize = 64 * 1024;

fn client() -> Result<reqwest::Client, String> {
    // The registry never redirects; following one could send the request to
    // another host, or over plain http.
    reqwest::Client::builder()
        .timeout(Duration::from_secs(20))
        .user_agent("RustCord")
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .map_err(|e| e.to_string())
}

async fn post(client: &reqwest::Client, url: String, body: Value, asked: &[Id]) -> Result<Answer, String> {
    let mut resp = client.post(url).json(&body).send().await.map_err(|e| e.to_string())?;
    if !resp.status().is_success() {
        return Err(format!("the registry answered {}", resp.status()));
    }
    let too_long = || "the registry's answer is too long".to_string();
    if resp.content_length().is_some_and(|n| n > MAX_ANSWER as u64) {
        return Err(too_long());
    }
    let mut bytes = Vec::new();
    while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
        if bytes.len() + chunk.len() > MAX_ANSWER {
            return Err(too_long());
        }
        bytes.extend_from_slice(&chunk);
    }
    let v: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
    Answer::parse(&v, asked).ok_or_else(|| "the registry sent something unreadable".to_string())
}

/// Say hello (`share`) or ask to be hidden; the answer is about you.
async fn hello(client: &reqwest::Client, base: &str, me: Id, share: bool) -> Result<Answer, String> {
    let path = if share { "hello" } else { "bye" };
    post(client, format!("{base}/v1/{path}"), json!({ "key": key(me) }), &[me]).await
}

/// Ask whether these users are on RustCord.
async fn lookup(client: &reqwest::Client, base: &str, users: &[Id]) -> Result<Answer, String> {
    let mut answer = Answer::default();
    for chunk in users.chunks(MAX_LOOKUP) {
        let keys: Vec<String> = chunk.iter().map(|u| key(*u)).collect();
        let part = post(client, format!("{base}/v1/lookup"), json!({ "keys": keys }), chunk).await?;
        answer.now = part.now;
        answer.users.extend(part.users);
    }
    Ok(answer)
}

/// Runs for as long as you're logged in (the backend aborts it on logout or
/// when the setting changes).
pub async fn run(em: Emitter, me: Id, share: bool) {
    let Some(base) = url() else { return };
    let client = match client() {
        Ok(c) => c,
        Err(e) => {
            log::warn!("registry: no HTTP client: {e}");
            return;
        }
    };
    let mut failures = 0u32;
    loop {
        match hello(&client, &base, me, share).await {
            Ok(a) => {
                failures = 0;
                em.emit(Event::Registry(a));
            }
            Err(e) => {
                failures += 1;
                // Once per outage is enough in the log.
                if failures == 1 {
                    log::warn!("registry: {e}");
                }
            }
        }
        // With the setting off there's nothing to keep fresh.
        if !share && failures == 0 {
            return;
        }
        // A failed hello is retried sooner, but never hammered.
        let wait = if failures == 0 { HELLO_EVERY } else { Duration::from_secs(60).saturating_mul(failures.min(10)) };
        tokio::time::sleep(wait).await;
    }
}

/// One lookup for the profiles being drawn. A failure answers nothing, so
/// they're asked about again once the app's own wait is over.
pub async fn ask(em: Emitter, users: Vec<Id>) {
    let Some(base) = url() else { return };
    let result = match client() {
        Ok(c) => lookup(&c, &base, &users).await,
        Err(e) => Err(e),
    };
    match result {
        Ok(a) => em.emit(Event::Registry(a)),
        Err(e) => log::warn!("registry: lookup failed: {e}"),
    }
}

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

    #[test]
    fn keys_hide_the_id_and_stay_stable() {
        let k = key(Id(1000));
        assert_eq!(k.len(), 64);
        assert!(!k.contains("1000"));
        assert_eq!(k, key(Id(1000)));
        assert_ne!(k, key(Id(1001)));
        assert!(k.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
    }

    #[test]
    fn only_https_or_http_on_this_pc() {
        for ok in ["https://registry.example", "http://127.0.0.1:8787", "http://localhost:8787"] {
            assert!(allowed(ok), "{ok}");
        }
        for bad in [
            "http://127.0.0.1:[email protected]",
            "http://localhost.evil.example",
            "http://example.com",
            "https://user:[email protected]",
            "ftp://registry.example",
        ] {
            assert!(!allowed(bad), "{bad}");
        }
    }

    /// Against a running registry (`node server/dev.mjs`, then
    /// `RUSTCORD_REGISTRY_URL=http://127.0.0.1:8787 cargo test -- --ignored registry`).
    #[tokio::test]
    #[ignore]
    async fn talks_to_a_running_registry() {
        let base = url().expect("set RUSTCORD_REGISTRY_URL");
        let client = client().unwrap();
        // Fresh IDs each run, so a registry that keeps its rows works too.
        let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64;
        let (a, b, nobody) = (Id(seed), Id(seed + 1), Id(seed + 2));
        let first = hello(&client, &base, a, true).await.unwrap();
        let joined = first.users[0].1.expect("hello answers about yourself").0;
        assert!(joined <= first.now);
        hello(&client, &base, b, true).await.unwrap();
        // Asking about three people answers about exactly those three.
        let seen = lookup(&client, &base, &[a, b, nobody]).await.unwrap();
        assert_eq!(seen.users.len(), 3);
        assert_eq!(seen.users[0].1.map(|r| r.0), Some(joined));
        assert!(seen.users[1].1.is_some());
        assert_eq!(seen.users[2], (nobody, None));
        // The setting off: hidden for everyone.
        assert_eq!(hello(&client, &base, a, false).await.unwrap().users[0].1, None);
        assert_eq!(lookup(&client, &base, &[a]).await.unwrap().users[0].1, None);
        // And back on, with the same join date.
        assert_eq!(hello(&client, &base, a, true).await.unwrap().users[0].1.map(|r| r.0), Some(joined));
    }

    #[test]
    fn answers_cover_everyone_asked() {
        let (a, b) = (Id(1), Id(2));
        let v = json!({ "now": 1_800_000_000u64, "users": { key(a): [1_700_000_000u64, 1_799_999_900u64], "junk": ["x"] } });
        let s = Answer::parse(&v, &[a, b]).unwrap();
        assert_eq!(s.now, 1_800_000_000);
        assert_eq!(s.users, vec![(a, Some((1_700_000_000, 1_799_999_900))), (b, None)]);
    }
}