Skip to content

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

7.9 KB
Raw Blame
//! Discord sometimes answers a message with "captcha required" (hCaptcha). This shows
//! that challenge for the person to solve: hCaptcha's own widget in an embedded webview
//! (WebView2), locked down like the login page. RustCord never solves anything itself;
//! it only carries the widget's answer back to Discord with the message.
//!
//! The page is incognito and never sees the account's token: it is Discord's
//! `robots.txt` (so the widget runs on discord.com, the host the site key belongs to)
//! with its content replaced by the widget.

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};

/// What Discord's "captcha required" reply asks for.
#[derive(Clone, Debug, PartialEq)]
pub struct Challenge {
    pub sitekey: String,
    pub rqdata: Option<String>,
    pub rqtoken: Option<String>,
    pub session_id: Option<String>,
}

impl Challenge {
    /// Read the challenge out of a failed request's error text (Discord's JSON reply
    /// follows the status). `None` unless it is an hCaptcha challenge.
    pub fn from_error(error: &str) -> Option<Self> {
        let json = &error[error.find('{')?..];
        let v: serde_json::Value = serde_json::from_str(json).ok()?;
        if v["captcha_service"].as_str().is_some_and(|s| s != "hcaptcha") {
            return None;
        }
        let sitekey = v["captcha_sitekey"].as_str()?.to_string();
        // A site key goes into the page's script: only the characters one is made of.
        if sitekey.is_empty() || sitekey.len() > 64 || !sitekey.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return None;
        }
        let text = |k: &str| v[k].as_str().map(String::from);
        Some(Self { sitekey, rqdata: text("captcha_rqdata"), rqtoken: text("captcha_rqtoken"), session_id: text("captcha_session_id") })
    }
}

pub struct CaptchaView {
    view: WebView,
    answers: Receiver<String>,
}

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

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",
    }
}

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(),
    }
}

/// The page script: once Discord's (text) page is there, replace it with hCaptcha's
/// widget and post the widget's answer back under this session's random prefix.
fn script(challenge: &Challenge, capability: &str) -> String {
    let rqdata = serde_json::to_string(&challenge.rqdata).unwrap_or_else(|_| "null".into());
    format!(
        r#"(function () {{
  if (window.top !== window || location.hostname !== "discord.com") return;
  var start = function () {{
    document.documentElement.innerHTML = "<head><meta name='viewport' content='width=device-width'></head><body style='margin:0;background:#2b2d31;display:flex;align-items:center;justify-content:center;min-height:100vh'><div id='c'></div></body>";
    window.__rustcordCaptcha = function () {{
      var id = hcaptcha.render("c", {{
        sitekey: "{sitekey}",
        theme: "dark",
        callback: function (token) {{ window.ipc.postMessage("{capability}" + token); }}
      }});
      var rqdata = {rqdata};
      if (rqdata) hcaptcha.setData(id, {{ rqdata: rqdata }});
    }};
    var s = document.createElement("script");
    s.src = "https://js.hcaptcha.com/1/api.js?render=explicit&onload=__rustcordCaptcha";
    s.onerror = function () {{ window.ipc.postMessage("{capability}!blocked"); }};
    document.head.appendChild(s);
  }};
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", start); else start();
}})();"#,
        sitekey = challenge.sitekey,
        capability = capability,
        rqdata = rqdata,
    )
}

impl CaptchaView {
    pub fn open(parent: &impl HasWindowHandle, challenge: &Challenge, rect: egui::Rect, pixels_per_point: f32) -> Result<Self, String> {
        #[cfg(target_os = "linux")]
        crate::linux::web_pages_available()?;
        let (send, answers) = sync_channel(1);
        let capability: String = (0..32).map(|_| format!("{:02x}", rand::random::<u8>())).collect::<String>() + ":";
        let prefix = capability.clone();
        let view = WebViewBuilder::new()
            .with_url("https://discord.com/robots.txt")
            .with_user_agent(discord::fingerprint::user_agent())
            .with_incognito(true)
            .with_devtools(false)
            .with_initialization_script(script(challenge, &capability))
            .with_navigation_handler(|url| {
                let ok = allowed_navigation(&url);
                if !ok {
                    log::warn!("captcha page: blocked navigation to {}", crate::login_view::short(&url));
                }
                ok
            })
            .with_new_window_req_handler(|_, _| wry::NewWindowResponse::Deny)
            .with_download_started_handler(|_, _| false)
            .with_ipc_handler(move |request| {
                // Only the top page on discord.com, and nothing absurdly long.
                if https_host(&request.uri().to_string()).as_deref() != Some("discord.com") || request.body().len() > 32_768 {
                    return;
                }
                if let Some(answer) = request.body().strip_prefix(&prefix) {
                    let _ = send.try_send(answer.to_string());
                }
            })
            .with_bounds(bounds(rect, pixels_per_point))
            .build_as_child(parent)
            .map_err(|e| format!("Couldn't open the captcha: {e}"))?;
        Ok(Self { view, answers })
    }

    /// The solved captcha's answer, once the person has completed it. `Err` if the
    /// widget could not load.
    pub fn answer(&self) -> Option<Result<String, &'static str>> {
        let answer = self.answers.try_recv().ok()?;
        Some(if answer == "!blocked" { Err("hCaptcha's script could not be loaded") } else { Ok(answer) })
    }

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

    pub fn hide(&self) {
        let _ = self.view.set_visible(false);
    }
}

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

    #[test]
    fn challenges_are_read_from_discords_reply_and_nothing_else() {
        let error = r#"Discord returned 400: {"captcha_key":["captcha-required"],"captcha_sitekey":"a9b5fb07-92ff-493f-86fe-352a2803b3df","captcha_service":"hcaptcha","captcha_session_id":"sess","captcha_rqdata":"data","captcha_rqtoken":"tok"}"#;
        let c = Challenge::from_error(error).unwrap();
        assert_eq!(c.sitekey, "a9b5fb07-92ff-493f-86fe-352a2803b3df");
        assert_eq!((c.rqdata.as_deref(), c.rqtoken.as_deref(), c.session_id.as_deref()), (Some("data"), Some("tok"), Some("sess")));
        assert!(Challenge::from_error("Discord returned 403: Missing Permissions").is_none());
        assert!(Challenge::from_error(r#"x {"captcha_sitekey":"a\"; alert(1); \""}"#).is_none());
        assert!(Challenge::from_error(r#"x {"captcha_sitekey":"abc","captcha_service":"recaptcha"}"#).is_none());
        // The script carries the site key and the request data as a JSON string.
        let page = script(&c, "cap:");
        assert!(page.contains(r#"sitekey: "a9b5fb07-92ff-493f-86fe-352a2803b3df""#) && page.contains(r#"var rqdata = "data";"#));
        assert!(allowed_navigation("https://newassets.hcaptcha.com/x") && !allowed_navigation("https://example.com/"));
    }
}