Skip to content

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

7.5 KB
Raw Blame
//! The login screen: Discord's real login page in an embedded webview
//! (WebView2 on Windows). Adapted from Serein's `LoginView`
//! (crates/platform/src/lib.rs), MIT OR Apache-2.0.
//!
//! The page is incognito (nothing persists), navigation is locked to
//! discord.com and hCaptcha, links that lead elsewhere open in the browser,
//! downloads are refused, and the token only comes back over IPC messages
//! carrying a random per-session prefix.

use eframe::egui;
use std::sync::mpsc::{sync_channel, Receiver};
use wry::dpi::{PhysicalPosition, PhysicalSize};
use wry::raw_window_handle::HasWindowHandle;
use wry::{WebView, WebViewBuilder};

pub struct LoginView {
    view: WebView,
    tokens: Receiver<String>,
    /// Problems the page reports that need the person's attention.
    notes: Receiver<String>,
    /// Links on the page that lead away from Discord: for the browser.
    links: Receiver<String>,
}

fn https_host(value: &str) -> Option<String> {
    let url = url::Url::parse(value).ok()?;
    (url.scheme() == "https" && url.username().is_empty() && url.password().is_none())
        .then(|| url.host_str().map(str::to_ascii_lowercase))
        .flatten()
}

fn discord_origin(value: &str) -> bool {
    https_host(value).as_deref() == Some("discord.com")
}

fn allowed_navigation(value: &str) -> bool {
    match https_host(value) {
        Some(h) => h == "discord.com" || h == "hcaptcha.com" || h.ends_with(".hcaptcha.com"),
        None => value == "about:blank",
    }
}

/// Scheme + host + path, without query strings or fragments (which can carry
/// secrets): the only form of a page's address that goes to the log or the screen.
pub fn short(url: &str) -> String {
    match url::Url::parse(url) {
        Ok(u) => format!("{}://{}{}", u.scheme(), u.host_str().unwrap_or(""), u.path()).chars().take(120).collect(),
        Err(_) => url.split(['?', '#']).next().unwrap_or("").chars().take(60).collect(),
    }
}

fn bounds(rect: egui::Rect, pixels_per_point: f32) -> wry::Rect {
    wry::Rect {
        position: PhysicalPosition::new((rect.left() * pixels_per_point) as i32, (rect.top() * pixels_per_point) as i32).into(),
        size: PhysicalSize::new((rect.width() * pixels_per_point) as u32, (rect.height() * pixels_per_point) as u32).into(),
    }
}

impl LoginView {
    /// `background` shows until the page draws (no white flash). Anything the
    /// page sends wakes `ctx`, so a login is picked up at once.
    pub fn open(parent: &impl HasWindowHandle, ctx: &egui::Context, rect: egui::Rect, pixels_per_point: f32, background: egui::Color32) -> Result<Self, String> {
        #[cfg(target_os = "linux")]
        crate::linux::web_pages_available()?;
        let (send, tokens) = sync_channel(1);
        let (send_note, notes) = sync_channel(16);
        let (send_link, links) = sync_channel(8);
        let capability: String = (0..32).map(|_| format!("{:02x}", rand::random::<u8>())).collect::<String>() + ":";
        let (diag_prefix, note_prefix) = (format!("diag:{capability}"), format!("note:{capability}"));
        let script = include_str!("login-handoff.js").replace("__RUSTCORD_LOGIN_CAPABILITY__", &capability);
        let nav_link = send_link.clone();
        let (nav_ctx, popup_ctx, ipc_ctx) = (ctx.clone(), ctx.clone(), ctx.clone());
        let view = WebViewBuilder::new()
            .with_url("https://discord.com/login")
            .with_user_agent(discord::fingerprint::user_agent())
            .with_incognito(true)
            .with_devtools(false)
            .with_background_color((background.r(), background.g(), background.b(), 255))
            .with_initialization_script(script)
            .with_navigation_handler(move |url| {
                if allowed_navigation(&url) {
                    return true;
                }
                // A link off Discord (help pages, terms): the browser opens it.
                if crate::embed_view::is_web(&url) {
                    log::info!("login page: opening {} in the browser", short(&url));
                    let _ = nav_link.try_send(url);
                    nav_ctx.request_repaint();
                } else {
                    log::warn!("login page: blocked navigation to {}", short(&url));
                }
                false
            })
            .with_new_window_req_handler(move |url, _| {
                if crate::embed_view::is_web(&url) {
                    log::info!("login page: opening {} in the browser", short(&url));
                    let _ = send_link.try_send(url);
                    popup_ctx.request_repaint();
                } else {
                    log::warn!("login page: blocked popup {}", short(&url));
                }
                wry::NewWindowResponse::Deny
            })
            .with_download_started_handler(|_, _| false)
            .with_ipc_handler(move |request| {
                if !discord_origin(&request.uri().to_string()) || request.body().len() > 2200 {
                    return;
                }
                let body = request.body();
                if let Some(message) = body.strip_prefix(&diag_prefix) {
                    log::info!("login page: {message}");
                } else if let Some(message) = body.strip_prefix(&note_prefix) {
                    log::warn!("login page: {message}");
                    let _ = send_note.try_send(message.to_string());
                    ipc_ctx.request_repaint();
                } else if let Some(token) = body.strip_prefix(&capability) {
                    let _ = send.try_send(token.to_string());
                    ipc_ctx.request_repaint();
                }
            })
            .with_bounds(bounds(rect, pixels_per_point))
            .build_as_child(parent)
            .map_err(|e| format!("Couldn't open Discord's login page: {e}"))?;
        Ok(Self { view, tokens, notes, links })
    }

    /// Hide the page and empty it, so Discord's app doesn't go on loading
    /// behind RustCord. Dropping the view afterwards ends its WebView2 processes.
    pub fn retire(&self) {
        let _ = self.view.set_visible(false);
        let _ = self.view.load_url("about:blank");
    }

    pub fn token(&self) -> Option<String> {
        self.tokens.try_recv().ok()
    }

    /// Latest problem the page reported, if any arrived.
    pub fn note(&self) -> Option<String> {
        self.notes.try_iter().last()
    }

    /// Links clicked on the page that lead away from Discord.
    pub fn links(&self) -> Vec<String> {
        self.links.try_iter().collect()
    }

    pub fn set_bounds(&self, rect: egui::Rect, pixels_per_point: f32) {
        let _ = self.view.set_bounds(bounds(rect, pixels_per_point));
    }
}

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

    #[test]
    fn logged_addresses_carry_no_query_or_fragment() {
        assert_eq!(short("https://example.com/cb?code=secret&state=x#token=abc"), "https://example.com/cb");
        assert_eq!(short("not a url?token=abc"), "not a url");
        assert!(short(&format!("https://example.com/{}", "a".repeat(500))).len() <= 120);
    }

    #[test]
    fn only_discord_and_hcaptcha_may_load() {
        assert!(allowed_navigation("https://discord.com/login") && allowed_navigation("https://newassets.hcaptcha.com/x") && allowed_navigation("about:blank"));
        for other in ["http://discord.com/login", "https://discord.com.example.com/", "https://[email protected]/", "https://examplehcaptcha.com/", "file:///C:/x"] {
            assert!(!allowed_navigation(other), "{other}");
        }
        assert!(discord_origin("https://discord.com/api/v9/auth/login") && !discord_origin("https://canary.discord.com.example.com/"));
    }
}