Skip to content

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

12.6 KB
Raw Blame
// Adapted from Serein (crates/platform/src/login-handoff.js), MIT OR Apache-2.0.
// Runs only in RustCord's own, freshly created (incognito) login webview.
// 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, 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__";
  let delivered = false;
  // Set when Discord answers the login with a suspended account's token: that
  // one only opens Discord's appeal pages, so it is never handed over.
  let suspended = false;

  // Every login page starts signed out. The pages one RustCord run opens share
  // the engine's private storage, so a page would otherwise sign in by itself
  // with the login an earlier page left there, even one Discord has ended.
  // (A new page has empty sessionStorage; the page's own reloads keep it.)
  try {
    if (sessionStorage.getItem("rustcord-login") === null) {
      localStorage.clear();
      sessionStorage.setItem("rustcord-login", "1");
    }
  } catch {}
  const apiPath = value => {
    try {
      const url = new URL(value, location.href);
      return url.origin === "https://discord.com" && /^\/api\/v\d+\//.test(url.pathname) ? url.pathname : null;
    } catch { return null; }
  };
  const allowed = value => apiPath(value) !== null;
  // Login endpoints (password, passkey/WebAuthn, MFA, QR ticket) answer with the token.
  const isAuth = value => /^\/api\/v\d+\/(auth\/|users\/@me\/remote-auth\/login)/.test(apiPath(value) || "");

  // Discord's page reports what you do on it: its "science" events, metrics
  // and error reports. RustCord sends none of that anywhere else, and not from
  // this page either. Those requests end the way they do behind a content
  // blocker (a failed request, which the page is built to shrug off); nothing
  // leaves the PC. Signing in itself is untouched.
  const isTracking = value => {
    try {
      const url = new URL(value, location.href);
      return url.origin === "https://discord.com" && /^\/(api\/v\d+\/(science|metrics)|error-reporting-proxy)(\/|$)/.test(url.pathname);
    } catch { return false; }
  };
  const failLocally = xhr => setTimeout(() => {
    try {
      Object.defineProperty(xhr, "readyState", { value: 4, configurable: true });
      Object.defineProperty(xhr, "status", { value: 0, configurable: true });
      for (const type of ["readystatechange", "error", "loadend"]) xhr.dispatchEvent(new ProgressEvent(type));
    } catch {}
  }, 0);

  // Status lines for RustCord: `diag` goes to its log, `note` is also shown
  // above the page. Never credential data.
  const post = kind => message => { try { window.ipc.postMessage(kind + capability + String(message).slice(0, 300)); } catch {} };
  const diag = post("diag:");
  const note = post("note:");

  // For logins Discord ends at once (#75, #37), the log says what the page did
  // with the login after handing it over, and which login each step used. A
  // login is only ever named by a tag: the first 8 hex digits of its SHA-256,
  // as RustCord's own log names it. Never the token itself.
  const started = performance.now();
  const since = () => Math.round(performance.now() - started) + " ms";
  const tags = new Set();
  const sawLogin = (value, where) => {
    if (typeof value !== "string" || value.length < 16) return;
    crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)).then(d => {
      const tag = Array.from(new Uint8Array(d).slice(0, 4), b => b.toString(16).padStart(2, "0")).join("");
      if (!tags.has(tag)) {
        tags.add(tag);
        diag("page used login " + tag + " (" + where + ", " + since() + ")");
      }
    }).catch(() => {});
  };
  let traced = 0;
  const shape = url => { try { return new URL(url, location.href).pathname.replace(/\/\d{7,}/g, "/:id"); } catch { return "?"; } };
  const trace = (method, url) => {
    if (!delivered || traced >= 25) return false;
    traced++;
    diag("page request after sign-in: " + String(method || "GET").toUpperCase() + " " + shape(url) + " (" + since() + ")");
    return true;
  };
  diag("page loaded: " + location.pathname);
  // How the page presents itself to Discord (and to its captcha): the browser
  // the user agent names, and the one the client hints name. Nothing personal.
  try {
    const hints = navigator.userAgentData ? navigator.userAgentData.brands.map(b => b.brand + " " + b.version).join(", ") : "none";
    diag("page identity: " + (navigator.userAgent.match(/(Chrome|Edg|Firefox|Version)\/\d+/g) || []).join(" ") + "; client hints: " + hints);
  } catch {}

  // `how`: from the login answer, or from a request the page made with it.
  const deliver = (value, how) => {
    if (delivered || suspended || typeof value !== "string" || value.length < 16 || value.length > 2048 || /\s/.test(value)) return;
    delivered = true;
    diag("signed in (" + how + ", " + since() + ")");
    sawLogin(value, how);
    window.ipc.postMessage(capability + value);
  };
  // Look at a login response: token → done; otherwise say what Discord wants.
  const inspectAuth = (status, text) => {
    let data = null;
    try { data = JSON.parse(text); } catch { return; }
    if (!data || typeof data !== "object") return;
    if (typeof data.token === "string") {
      // What Discord wants done before the account is used normally (such as
      // UPDATE_PASSWORD, which web asks for once connected): names only.
      const actions = Array.isArray(data.required_actions) ? data.required_actions.filter(a => /^[A-Z_]{1,48}$/.test(a)) : [];
      if (actions.length) diag("Discord's login answer lists required actions: " + actions.join(", "));
      return deliver(data.token, "login answer");
    }
    if (typeof data.suspended_user_token === "string") {
      suspended = true;
      return note("Discord has suspended this account. Log in on discord.com to see why and to appeal.");
    }
    if (data.mfa === true) return diag("Discord asked for a 2FA code");
    if (data.captcha_key) return diag("Discord asked for a captcha");
    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 = 0;
  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");
      sawLogin(payload.d.token, "gateway op " + payload.op);
    }
    if (heldBack++ < 6) diag("kept the page from connecting to Discord: held back op " + (payload ? payload.op : "?") + " (" + since() + ")");
  };

  // XMLHttpRequest (Discord's page mostly uses this).
  const urls = new WeakMap();
  const methods = new WeakMap();
  const open = XMLHttpRequest.prototype.open;
  const send = XMLHttpRequest.prototype.send;
  const setHeader = XMLHttpRequest.prototype.setRequestHeader;
  XMLHttpRequest.prototype.open = function(method, url, ...rest) {
    urls.set(this, String(url));
    methods.set(this, method);
    return open.call(this, method, url, ...rest);
  };
  XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
    if (allowed(urls.get(this)) && String(name).toLowerCase() === "authorization") {
      deliver(value, "page request");
      sawLogin(value, "page request");
    }
    return setHeader.call(this, name, value);
  };
  XMLHttpRequest.prototype.send = function(...args) {
    if (isTracking(urls.get(this))) { failLocally(this); return; }
    if (allowed(urls.get(this)) && trace(methods.get(this), urls.get(this))) {
      const where = shape(urls.get(this));
      this.addEventListener("loadend", () => { if (this.status >= 400) diag("Discord answered " + this.status + " to the page's " + where); });
    }
    if (isAuth(urls.get(this))) {
      this.addEventListener("load", () => {
        try { inspectAuth(this.status, typeof this.response === "string" ? this.response : this.responseText); } catch {}
      });
    }
    return send.apply(this, args);
  };

  // fetch.
  const originalFetch = window.fetch;
  window.fetch = function(input, init) {
    const url = input instanceof Request ? input.url : input;
    if (isTracking(url)) return Promise.reject(new TypeError("Failed to fetch"));
    if (allowed(url)) {
      const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
      deliver(headers.get("authorization"), "page request");
      sawLogin(headers.get("authorization"), "page request");
      trace(init?.method ?? (input instanceof Request ? input.method : "GET"), url);
    }
    const result = originalFetch.apply(this, arguments);
    if (isAuth(url)) {
      result.then(resp => resp.clone().text().then(text => inspectAuth(resp.status, text))).catch(() => {});
    }
    return result;
  };

  // (Beacons are how a page reports on its way out. A refused one is `false`.)
  if (navigator.sendBeacon) {
    const beacon = navigator.sendBeacon.bind(navigator);
    navigator.sendBeacon = (url, data) => isTracking(url) ? false : beacon(url, data);
  }

  // Passkeys. In this embedded engine, passkey *autofill* ("conditional mediation")
  // doesn't wait for you to pick a passkey: it answers immediately, Discord rejects
  // that ("Credential not discoverable or invalid") and the page's passkey sign-in
  // gets stuck. So tell the page autofill isn't available; the "sign in with a
  // passkey" link (a normal Windows Hello prompt) still works.
  if (window.PublicKeyCredential) {
    try { PublicKeyCredential.isConditionalMediationAvailable = () => Promise.resolve(false); } catch {}
    const caps = PublicKeyCredential.getClientCapabilities;
    if (typeof caps === "function") {
      try {
        PublicKeyCredential.getClientCapabilities = () =>
          caps.call(PublicKeyCredential).then(c => Object.assign({}, c, { conditionalGet: false }));
      } catch {}
    }
  }
  if (navigator.credentials && navigator.credentials.get) {
    const get = navigator.credentials.get.bind(navigator.credentials);
    navigator.credentials.get = function(options) {
      const passkey = !!(options && options.publicKey);
      // "conditional" = the page's silent autofill request; "modal" = the passkey link.
      const auto = !!(options && options.mediation === "conditional");
      if (passkey && auto) {
        // Decline autofill the way a browser does when you dismiss it, so the
        // page moves on (and keeps the passkey link enabled).
        return Promise.reject(new DOMException("Passkey autofill isn't available.", "NotAllowedError"));
      }
      if (passkey) diag("passkey: waiting for Windows Hello");
      return get(options).then(result => {
        if (passkey) diag(result ? "passkey accepted" : "passkey: Windows returned no passkey");
        return result;
      }, error => {
        const name = error && error.name;
        if (passkey) {
          // Closing the Windows Hello prompt is a NotAllowedError: nothing to report.
          const report = name === "NotAllowedError" || name === "AbortError" ? diag : note;
          report("Passkey sign-in failed: " + name + " " + (error && error.message || ""));
        }
        throw error;
      });
    };
  }
  addEventListener("DOMContentLoaded", () => {
    if (typeof PublicKeyCredential === "undefined") note("Passkeys aren't available here. Log in with the QR code or your email and password.");
  });
})();