Skip to content

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

8.7 KB
Raw Blame
//! Saved accounts, for switching between them as Discord's "Switch Accounts" does.
//!
//! Each account's token is kept in the OS credential store (Windows Credential
//! Manager) under its user ID. `accounts.json` in the config folder holds only
//! what the switcher shows (ID, names, avatar) and which account is active.
//! Each account has its own folder for what belongs to it alone: its place in
//! the app and last status (config), and its account snapshot and cached
//! messages (cache, see `cache.rs`).

use base64::Engine;
use discord::model::{Id, User};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Discord's own limit on accounts to switch between.
pub const MAX: usize = 5;

const SERVICE: &str = "RustCord";
/// The one credential versions before account switching kept.
const LEGACY_ENTRY: &str = "discord-token";
const FILE: &str = "accounts.json";

/// What the switcher shows of a saved account.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Account {
    pub id: Id,
    pub username: String,
    pub global_name: Option<String>,
    pub avatar: Option<String>,
}

impl Account {
    /// As a `User`, for the shared avatar and name helpers.
    pub fn user(&self) -> User {
        User { id: self.id, username: self.username.clone(), global_name: self.global_name.clone(), avatar: self.avatar.clone(), ..Default::default() }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Saved {
    /// In the order they were added (the switcher's order).
    pub list: Vec<Account>,
    pub active: Option<Id>,
}

pub fn config_dir() -> Option<PathBuf> {
    directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.config_dir().to_path_buf())
}

/// The account's own config folder (its place in the app, its last status).
pub fn config_folder(id: Id) -> Option<PathBuf> {
    config_dir().map(|d| d.join("accounts").join(id.to_string()))
}

/// `rustcord.exe --logout-all` (the uninstaller, when deleting the saved
/// login): log every saved account out at Discord, so its token stops
/// working, then forget it here. Gives each 10 seconds; offline, the logins
/// are still deleted from this PC.
pub fn log_out_all() {
    let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else { return };
    let mut saved = Saved::load();
    for (id, token) in saved.all_logins() {
        let http = discord::Http::new(Some(token));
        let _ = rt.block_on(async { tokio::time::timeout(std::time::Duration::from_secs(10), http.logout()).await });
        match id {
            Some(id) => saved.forget(id),
            None => {
                if let Some(e) = entry(LEGACY_ENTRY) {
                    let _ = e.delete_credential();
                }
            }
        }
    }
}

fn entry(name: &str) -> Option<keyring::Entry> {
    keyring::Entry::new(SERVICE, name).ok()
}

fn entry_name(id: Id) -> String {
    format!("{LEGACY_ENTRY}:{id}")
}

/// The saved token of this account.
pub fn token(id: Id) -> Option<String> {
    entry(&entry_name(id))?.get_password().ok()
}

fn store_token(id: Id, token: &str) {
    if let Err(e) = entry(&entry_name(id)).ok_or(keyring::Error::NoEntry).and_then(|e| e.set_password(token)) {
        log::warn!("accounts: couldn't keep the login in the OS credential store: {e}");
    }
}

/// How the log names a login: the first 8 hex digits of its SHA-256 (the
/// login page names the logins it sees the same way). Tells two logins apart
/// without the token being anywhere in the log.
pub fn token_tag(token: &str) -> String {
    use sha2::{Digest, Sha256};
    Sha256::digest(token.as_bytes())[..4].iter().map(|b| format!("{b:02x}")).collect()
}

/// Whose a token is: Discord's user tokens start with the account's ID in base64.
pub fn token_user(token: &str) -> Option<Id> {
    let first = token.split('.').next()?;
    let engines = [base64::engine::general_purpose::STANDARD_NO_PAD, base64::engine::general_purpose::URL_SAFE_NO_PAD];
    let bytes = engines.iter().find_map(|e| e.decode(first.trim_end_matches('=')).ok())?;
    std::str::from_utf8(&bytes).ok()?.parse().ok().map(Id)
}

impl Saved {
    /// The saved accounts. The first run after an update from a version with a
    /// single login takes that login over (see [`Saved::adopt_legacy`]).
    pub fn load() -> Self {
        let Some(dir) = config_dir() else { return Self::default() };
        match std::fs::read(dir.join(FILE)) {
            Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
            Err(_) => Self::adopt_legacy(),
        }
    }

    /// Bring a single-login version's login, place and caches under its
    /// account. The old credential is left for that version to find again
    /// (it is removed when the account logs out).
    fn adopt_legacy() -> Self {
        let mut saved = Self::default();
        let Some(token) = entry(LEGACY_ENTRY).and_then(|e| e.get_password().ok()) else { return saved };
        let Some(id) = token_user(&token) else {
            log::warn!("accounts: the saved login isn't in a known form; log in again");
            return saved;
        };
        store_token(id, &token);
        if let (Some(old), Some(new)) = (config_dir(), config_folder(id)) {
            let _ = std::fs::create_dir_all(&new);
            for name in ["nav.json", "presence.json"] {
                let _ = std::fs::copy(old.join(name), new.join(name));
            }
        }
        crate::cache::adopt_legacy(id);
        saved.list.push(Account { id, ..Default::default() });
        saved.active = Some(id);
        saved.save();
        log::info!("accounts: took over the saved login");
        saved
    }

    pub fn save(&self) {
        let Some(dir) = config_dir() else { return };
        let _ = std::fs::create_dir_all(&dir);
        if let Ok(json) = serde_json::to_vec_pretty(self) {
            let tmp = dir.join("accounts.json.tmp");
            if std::fs::write(&tmp, json).is_ok() {
                let _ = std::fs::rename(&tmp, dir.join(FILE));
            }
        }
    }

    pub fn get(&self, id: Id) -> Option<&Account> {
        self.list.iter().find(|a| a.id == id)
    }

    pub fn is_full(&self) -> bool {
        self.list.len() >= MAX
    }

    /// A login for `id` (new or renewed) becomes the active account.
    pub fn add(&mut self, id: Id, token: &str) {
        store_token(id, token);
        if self.get(id).is_none() {
            self.list.push(Account { id, ..Default::default() });
        }
        self.active = Some(id);
        self.save();
    }

    pub fn set_active(&mut self, id: Id) {
        if self.active != Some(id) {
            self.active = Some(id);
            self.save();
        }
    }

    /// Keep the switcher's names and avatar as READY has them now.
    pub fn update(&mut self, me: &User) {
        let Some(a) = self.list.iter_mut().find(|a| a.id == me.id) else { return };
        if a.username != me.username || a.global_name != me.global_name || a.avatar != me.avatar {
            a.username = me.username.clone();
            a.global_name = me.global_name.clone();
            a.avatar = me.avatar.clone();
            self.save();
        }
    }

    /// Every saved account, plus a single-login version's login if one is left.
    fn all_logins(&self) -> Vec<(Option<Id>, String)> {
        let mut out: Vec<(Option<Id>, String)> = self.list.iter().filter_map(|a| token(a.id).map(|t| (Some(a.id), t))).collect();
        if let Some(t) = entry(LEGACY_ENTRY).and_then(|e| e.get_password().ok()) {
            out.push((None, t));
        }
        out
    }

    /// Forget an account: its login, and everything kept for it here.
    pub fn forget(&mut self, id: Id) {
        if let Some(e) = entry(&entry_name(id)) {
            let _ = e.delete_credential();
        }
        // A single-login version's credential for the same account goes too.
        if let Some(e) = entry(LEGACY_ENTRY) {
            if e.get_password().ok().as_deref().and_then(token_user) == Some(id) {
                let _ = e.delete_credential();
            }
        }
        if let Some(dir) = config_folder(id) {
            crate::cache::remove_tree(&dir);
        }
        crate::cache::forget_account(id);
        self.list.retain(|a| a.id != id);
        if self.active == Some(id) {
            self.active = None;
        }
        self.save();
    }
}

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

    #[test]
    fn a_token_names_its_account() {
        let id = "123456789012345678";
        let first = base64::engine::general_purpose::STANDARD_NO_PAD.encode(id);
        assert_eq!(token_user(&format!("{first}.Gx1y2z.signature")), Some(Id(123456789012345678)));
        assert_eq!(token_user("not-a-token"), None);
        assert_eq!(token_user(""), None);
    }
}