Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
Keep the login page from starting a second session (#75, #37)
VRonGitHub3255b7a1c647
diff --git a/apps/rustcord/src/backend.rs b/apps/rustcord/src/backend.rsindex 1a7d15d..e5447a7 100644--- a/apps/rustcord/src/backend.rs+++ b/apps/rustcord/src/backend.rs@@ -872,7 +872,7 @@ async fn run(mut rx: UnboundedReceiver<Command>, base: Emitter) {});gateway = Some(gtx);}- Command::Token(token) => http = http.with_token(token),+ Command::Token(token) => http.set_token(token),Command::SetStatus { status, custom } => {if let Some(g) = &gateway {let p = gateway::presence_payload(&status, custom.as_ref());diff --git a/apps/rustcord/src/login-handoff.js b/apps/rustcord/src/login-handoff.jsindex d8ce32d..e6c71eb 100644--- a/apps/rustcord/src/login-handoff.js+++ b/apps/rustcord/src/login-handoff.js@@ -3,7 +3,9 @@// Discord performs the entire login / 2FA / captcha / passkey / QR flow itself.// This only picks up the session token Discord gives its own page (from the// login response, or the Authorization header the page then sends to Discord's-// API) and hands it to RustCord over the webview's private IPC channel.+// API, or the IDENTIFY it would send on the gateway) and hands it to RustCord+// over the webview's private IPC channel. The page itself never connects as a+// client: RustCord is the only one using the login.(() => {if (window !== window.top || location.origin !== "https://discord.com") return;const capability = "__RUSTCORD_LOGIN_CAPABILITY__";@@ -85,6 +87,34 @@if (status >= 400) diag("Discord answered " + status + " " + (data.message || ""));};+ // The page is a login form and nothing more: once signed in, Discord's page+ // starts its app and connects as a client of its own, with the login+ // RustCord has just been handed. Discord can answer that second session+ // with a replacement token, and the one RustCord holds stops working a+ // second later (#75). So no session starts here: what the page sends on+ // Discord's gateway is held back, and its IDENTIFY (or RESUME) only hands+ // RustCord the token, which is how a QR code login, whose token the page+ // decrypts itself, gets through too. The QR code's own connection+ // (remote-auth-gateway) is left alone. (Discord web speaks JSON there.)+ const isGateway = value => {+ try {+ const host = new URL(value).hostname;+ return host.endsWith(".discord.gg") && host !== "remote-auth-gateway.discord.gg";+ } catch { return false; }+ };+ let heldBack = false;+ const wsSend = WebSocket.prototype.send;+ WebSocket.prototype.send = function(data) {+ if (!isGateway(this.url)) return wsSend.call(this, data);+ let payload = null;+ try { payload = typeof data === "string" ? JSON.parse(data) : null; } catch {}+ if (payload && (payload.op === 2 || payload.op === 6) && payload.d) deliver(payload.d.token, "gateway");+ if (!heldBack) {+ heldBack = true;+ diag("kept the page from connecting to Discord");+ }+ };+// XMLHttpRequest (Discord's page mostly uses this).const urls = new WeakMap();const open = XMLHttpRequest.prototype.open;diff --git a/crates/discord/src/http.rs b/crates/discord/src/http.rsindex 18cf7ae..c95d622 100644--- a/crates/discord/src/http.rs+++ b/crates/discord/src/http.rs@@ -48,7 +48,10 @@ pub struct Http {client: Client,/// Plain client for everything else (CDN downloads, themes): no Discord headers.plain: Client,- token: Option<String>,+ /// The login token, shared by every copy of this client: when Discord+ /// replaces it (READY's `auth_token`), the copies that tasks already hold+ /// send the new one too, never the one Discord has just retired.+ token: std::sync::Arc<std::sync::RwLock<Option<String>>>,/// Discord's token for your Spotify connection, kept a while (see `spotify`).pub(crate) spotify: std::sync::Arc<crate::spotify::TokenCache>,}@@ -379,13 +382,17 @@ impl Http {.redirect(https_only_redirects()).build().expect("failed to build HTTP client");- Self { client, plain, token, spotify: Default::default() }+ Self { client, plain, token: std::sync::Arc::new(std::sync::RwLock::new(token)), spotify: Default::default() }}- /// This client with another login token (Discord replaced it: see the- /// gateway's `TokenRefreshed`).- pub fn with_token(&self, token: String) -> Self {- Self { token: Some(token), ..self.clone() }+ /// Discord replaced the login token (see the gateway's `TokenRefreshed`):+ /// this client and every copy of it send the new one from now on.+ pub fn set_token(&self, token: String) {+ *self.token.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(token);+ }++ fn token(&self) -> Option<String> {+ self.token.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()}/// Client for non-Discord requests (themes, CDN files). Sends no token@@ -417,7 +424,7 @@ impl Http {let mut trace = Sent::start(&method, path, held + waiting.elapsed());held = Duration::ZERO;let mut req = self.client.request(method.clone(), &url);- if let Some(token) = &self.token {+ if let Some(token) = self.token() {req = req.header("Authorization", token);}if let Some(locale) = account_locale() {@@ -511,7 +518,7 @@ impl Http {let (name, bytes, mime) = &file;form = form.part("file", Part::bytes(bytes.clone()).file_name(name.clone()).mime_str(mime)?);let mut req = self.client.post(&url).multipart(form).timeout(Duration::from_secs(120));- if let Some(token) = &self.token {+ if let Some(token) = self.token() {req = req.header("Authorization", token);}let (status, text) = match answer(req, &route, &mut trace).await? {@@ -537,7 +544,7 @@ impl Http {/// For account changes, where a 401 can be "verify it's you first".pub async fn request_raw(&self, method: Method, path: &str, body: Option<Value>, extra: &[(&str, String)]) -> Result<(u16, Value)> {let mut req = self.client.request(method.clone(), format!("{API_BASE}{path}"));- if let Some(token) = &self.token {+ if let Some(token) = self.token() {req = req.header("Authorization", token);}if let Some(locale) = account_locale() {@@ -1085,7 +1092,7 @@ impl Http {/// End this session at Discord, the way its own client logs out: the token/// stops working everywhere. Nothing to do without a token.pub async fn logout(&self) -> Result<()> {- if self.token.is_none() {+ if self.token().is_none() {return Ok(());}self.request(Method::POST, "/auth/logout", Some(json!({ "provider": null, "voip_provider": null }))).await?;@@ -1097,6 +1104,17 @@ impl Http {mod tests {use super::*;+ /// A token Discord replaced reaches the copies tasks already hold.+ #[test]+ fn replaced_token_reaches_every_copy() {+ let http = Http::new(Some("old".into()));+ let held = http.clone();+ http.set_token("new".into());+ assert_eq!(held.token().as_deref(), Some("new"));+ // Another session's client keeps its own.+ assert_eq!(Http::new(Some("other".into())).token().as_deref(), Some("other"));+ }+/// The request Discord web made for `hello has:forward has:sound/// before:2026-12-01 after:2026-11-01 during:2026-11-15 pinned:false/// authorType:bot` (2026-12-04).