Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurisrchandoff.rs

1.4.2Released Nov 21, 2026

handoff.rs

226 lines10.2 KBRust
//! Discord sign-in in the default browser, handed back to the app (the site's side: src/lib/app-handoff.ts).//!//! The site's "Sign in with Discord" leads to /api/auth/discord/login. In the app that navigation is cancelled//! and the same sign-in opens in the default browser instead, where Discord usually knows the member already,//! with `app=<challenge>`: base64url SHA-256 of a random verifier only this process holds. Once signed in, the//! browser opens juicewrld://signin?code=<one-time code>, and the app claims the code in its own window with the//! verifier (/api/auth/app/claim?code=&v=). The code alone is useless to anyone who catches it.//!//! Any page can open a juicewrld:// link, so a link counts only while a sign-in started here is waiting for it: any//! other is ignored and the page stays as it is (the music too). The verifier stays until a claim lands signed in,//! so a stray or forged code, which the site refuses, can't use up the sign-in under way either.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine;use sha2::{Digest, Sha256};use std::sync::{Mutex, MutexGuard};use std::time::{Duration, Instant};use url::Url;/// A sign-in has this long to come back (the site's OAuth state lasts as long).const LIFETIME: Duration = Duration::from_secs(10 * 60);const LOGIN_PATH: &str = "/api/auth/discord/login";const CLAIM_PATH: &str = "/api/auth/app/claim";#[derive(Default)]pub struct Handoff {    /// The verifier of the sign-in under way, and when it started.    verifier: Mutex<Option<(String, Instant)>>,    /// The claim the app is about to open: the only one the site webview may navigate to.    claiming: Mutex<Option<String>>,    /// A claim was opened and its page hasn't finished loading: where it lands says whether it signed in.    landing: Mutex<bool>,}fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {    m.lock().unwrap_or_else(|e| e.into_inner())}fn b64(bytes: &[u8]) -> String {    URL_SAFE_NO_PAD.encode(bytes)}/// The challenge the site keeps for a verifier (lib/app-handoff.ts challengeOfVerifier).pub fn challenge(verifier: &str) -> String {    b64(&Sha256::digest(verifier.as_bytes()))}fn random_token() -> String {    let mut bytes = [0u8; 32];    getrandom::fill(&mut bytes).expect("the system's random source");    b64(&bytes)}/// 43 base64url characters: a code or a verifier (32 bytes).fn is_token(s: &str) -> bool {    s.len() == 43 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')}fn is_site(url: &Url) -> bool {    url.scheme() == "https" && url.host_str() == Some("juicewrld.io")}/// A navigation to the claim route, which the site webview takes only from the app itself.pub fn is_claim(url: &Url) -> bool {    is_site(url) && url.path() == CLAIM_PATH}/// The code in a juicewrld://signin?code= link, when it is one.pub fn signin_code(link: &Url) -> Option<String> {    if link.scheme() != "juicewrld" || link.host_str() != Some("signin") {        return None;    }    link.query_pairs().find(|(k, _)| k == "code").map(|(_, v)| v.into_owned()).filter(|c| is_token(c))}impl Handoff {    /// For an in-app navigation to the Discord sign-in: the same sign-in for the default browser, carrying the    /// app's challenge. A sign-in already under way keeps its verifier, so pressing twice still comes back.    pub fn browser_signin(&self, url: &Url) -> Option<Url> {        if !is_site(url) || url.path() != LOGIN_PATH {            return None;        }        let next = url.query_pairs().find(|(k, _)| k == "next").map(|(_, v)| v.into_owned()).unwrap_or_else(|| "/".into());        let verifier = {            let mut slot = lock(&self.verifier);            match &*slot {                Some((v, at)) if at.elapsed() < LIFETIME => v.clone(),                _ => {                    let v = random_token();                    *slot = Some((v.clone(), Instant::now()));                    v                }            }        };        let mut out = Url::parse("https://juicewrld.io").expect("site url");        out.set_path(LOGIN_PATH);        out.query_pairs_mut().append_pair("next", &next).append_pair("app", &challenge(&verifier));        Some(out)    }    /// Where the site webview goes for a sign-in link's code: the claim, with the verifier, while a sign-in started    /// here is waiting. None otherwise: the link is ignored.    pub fn claim(&self, code: &str) -> Option<Url> {        let verifier = lock(&self.verifier).as_ref().filter(|(_, at)| at.elapsed() < LIFETIME).map(|(v, _)| v.clone())?;        if !is_token(code) {            return None;        }        let mut url = Url::parse("https://juicewrld.io").expect("site url");        url.set_path(CLAIM_PATH);        url.query_pairs_mut().append_pair("code", code).append_pair("v", &verifier);        *lock(&self.claiming) = Some(url.to_string());        Some(url)    }    /// Whether the site webview may open this claim: only the one `claim` just made, once.    pub fn allow_claim(&self, url: &Url) -> bool {        let mut expected = lock(&self.claiming);        if expected.as_deref() == Some(url.as_str()) {            *expected = None;            *lock(&self.landing) = true;            return true;        }        false    }    /// A page finished loading in the site webview. After a claim, the site's refusal (/login?signin_error=, or the    /// claim itself when the site didn't answer) keeps the sign-in waiting for its own link; any other page is the    /// signed-in one, and the sign-in is over.    pub fn landed(&self, url: &Url) {        if !std::mem::take(&mut *lock(&self.landing)) {            return;        }        let refused = is_claim(url) || (is_site(url) && url.path() == "/login" && url.query_pairs().any(|(k, _)| k == "signin_error"));        if !refused {            *lock(&self.verifier) = None;        }    }}#[cfg(test)]mod tests {    use super::*;    fn url(s: &str) -> Url {        Url::parse(s).unwrap()    }    #[test]    fn challenge_is_pkce_s256() {        // RFC 7636 appendix B.        assert_eq!(challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");        assert!(is_token(&random_token()));    }    #[test]    fn only_the_discord_sign_in_goes_to_the_browser() {        let h = Handoff::default();        let out = h.browser_signin(&url("https://juicewrld.io/api/auth/discord/login?next=%2Flogin%3Fnext%3D%252Fsong%252Fx")).unwrap();        let pairs: Vec<(String, String)> = out.query_pairs().map(|(k, v)| (k.into(), v.into())).collect();        assert_eq!(out.path(), LOGIN_PATH);        assert_eq!(pairs[0], ("next".into(), "/login?next=%2Fsong%2Fx".into()));        assert_eq!(pairs[1].0, "app");        assert!(is_token(&pairs[1].1));        // The same verifier while one is under way.        let again = h.browser_signin(&url("https://juicewrld.io/api/auth/discord/login")).unwrap();        assert_eq!(again.query_pairs().find(|(k, _)| k == "app").unwrap().1, pairs[1].1);        assert_eq!(again.query_pairs().find(|(k, _)| k == "next").unwrap().1, "/");        for other in [            "https://juicewrld.io/login",            "https://juicewrld.io/api/auth/discord/callback?code=x",            "https://discord.com/api/auth/discord/login",            "http://juicewrld.io/api/auth/discord/login",        ] {            assert!(h.browser_signin(&url(other)).is_none(), "{other}");        }    }    #[test]    fn a_sign_in_link_claims_with_the_verifier_until_one_signs_in() {        let h = Handoff::default();        let started = h.browser_signin(&url("https://juicewrld.io/api/auth/discord/login?next=%2F")).unwrap();        let sent = started.query_pairs().find(|(k, _)| k == "app").unwrap().1.into_owned();        let code = random_token();        let claim = h.claim(&code).expect("a sign-in is waiting");        assert!(is_claim(&claim));        let v = claim.query_pairs().find(|(k, _)| k == "v").unwrap().1.into_owned();        assert_eq!(challenge(&v), sent);        assert_eq!(claim.query_pairs().find(|(k, _)| k == "code").unwrap().1, code.as_str());        // The site webview takes exactly that claim, once; any other claim never.        assert!(!h.allow_claim(&url(&format!("https://juicewrld.io/api/auth/app/claim?code={code}&v=x"))));        assert!(h.allow_claim(&claim));        assert!(!h.allow_claim(&claim));        // A forged code the site refuses (or a claim it never answered) leaves the sign-in waiting for its own link.        h.landed(&url("https://juicewrld.io/login?signin_error=app_failed"));        let again = h.claim(&random_token()).expect("still waiting");        assert!(h.allow_claim(&again));        h.landed(&again);        let real = h.claim(&random_token()).expect("still waiting");        assert!(h.allow_claim(&real));        // A page that isn't a refusal lands signed in: the sign-in is over, and later links are ignored.        h.landed(&url("https://juicewrld.io/"));        assert_eq!(h.claim(&random_token()), None);        // Pages that load with no claim in flight say nothing.        let h = Handoff::default();        h.browser_signin(&url("https://juicewrld.io/api/auth/discord/login")).unwrap();        h.landed(&url("https://juicewrld.io/"));        assert!(h.claim(&random_token()).is_some());    }    #[test]    fn links_are_read_strictly() {        let code = random_token();        assert_eq!(signin_code(&url(&format!("juicewrld://signin?code={code}"))), Some(code.clone()));        assert_eq!(signin_code(&url(&format!("juicewrld://signin/?code={code}"))), Some(code.clone()));        assert_eq!(signin_code(&url("juicewrld://signin?code=short")), None);        assert_eq!(signin_code(&url(&format!("juicewrld://other?code={code}"))), None);        assert_eq!(signin_code(&url(&format!("https://signin?code={code}"))), None);        // No sign-in under way: the link is ignored, and no claim is ever let through.        let h = Handoff::default();        assert_eq!(h.claim(&code), None);        assert!(!h.allow_claim(&url(&format!("https://juicewrld.io/api/auth/app/claim?code={code}&v={code}"))));        // Under way, a code that isn't one is ignored too.        h.browser_signin(&url("https://juicewrld.io/api/auth/discord/login")).unwrap();        assert_eq!(h.claim("short"), None);    }}