concord 2.4.0

A terminal user interface client for Discord
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::{sync::mpsc, task::JoinHandle};

use super::{DiscordAuthSession, auth_http::discord_login_headers};

const LOGIN_URL: &str = "https://discord.com/api/v9/auth/login";
const MFA_VERIFY_URL: &str = "https://discord.com/api/v9/auth/mfa";
const MFA_SMS_SEND_URL: &str = "https://discord.com/api/v9/auth/mfa/sms/send";

#[derive(Clone, Debug)]
pub enum PasswordAuthEvent {
    Status(String),
    MfaRequired(MfaChallenge),
    SmsSent { phone: Option<String> },
    Token(String),
    Failed(String),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MfaMethod {
    Totp,
    Sms,
}

impl MfaMethod {
    fn endpoint_name(self) -> &'static str {
        match self {
            Self::Totp => "totp",
            Self::Sms => "sms",
        }
    }
}

#[derive(Clone, Debug)]
pub struct MfaChallenge {
    pub ticket: String,
    pub login_instance_id: String,
    pub methods: Vec<MfaMethod>,
}

pub fn spawn_login(
    login: String,
    password: String,
    events_tx: mpsc::Sender<PasswordAuthEvent>,
) -> JoinHandle<()> {
    spawn_login_with_auth_session(login, password, DiscordAuthSession::fallback(), events_tx)
}

pub(crate) fn spawn_login_with_auth_session(
    login: String,
    password: String,
    auth_session: DiscordAuthSession,
    events_tx: mpsc::Sender<PasswordAuthEvent>,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let _ = events_tx
            .send(PasswordAuthEvent::Status(
                "Authenticating with Discord...".to_string(),
            ))
            .await;

        match login_with_password(&login, &password, &auth_session).await {
            Ok(LoginOutcome::Token(token)) => {
                let _ = events_tx.send(PasswordAuthEvent::Token(token)).await;
            }
            Ok(LoginOutcome::MfaRequired(challenge)) => {
                let _ = events_tx
                    .send(PasswordAuthEvent::MfaRequired(challenge))
                    .await;
            }
            Err(error) => {
                let _ = events_tx.send(PasswordAuthEvent::Failed(error)).await;
            }
        }
    })
}

pub fn spawn_mfa_verify(
    method: MfaMethod,
    code: String,
    ticket: String,
    login_instance_id: String,
    events_tx: mpsc::Sender<PasswordAuthEvent>,
) -> JoinHandle<()> {
    spawn_mfa_verify_with_auth_session(
        method,
        code,
        ticket,
        login_instance_id,
        DiscordAuthSession::fallback(),
        events_tx,
    )
}

pub(crate) fn spawn_mfa_verify_with_auth_session(
    method: MfaMethod,
    code: String,
    ticket: String,
    login_instance_id: String,
    auth_session: DiscordAuthSession,
    events_tx: mpsc::Sender<PasswordAuthEvent>,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let _ = events_tx
            .send(PasswordAuthEvent::Status(
                "Verifying multi-factor authentication...".to_string(),
            ))
            .await;

        match verify_mfa(method, &code, &ticket, &login_instance_id, &auth_session).await {
            Ok(token) => {
                let _ = events_tx.send(PasswordAuthEvent::Token(token)).await;
            }
            Err(error) => {
                let _ = events_tx.send(PasswordAuthEvent::Failed(error)).await;
            }
        }
    })
}

pub fn spawn_sms_send(
    ticket: String,
    events_tx: mpsc::Sender<PasswordAuthEvent>,
) -> JoinHandle<()> {
    spawn_sms_send_with_auth_session(ticket, DiscordAuthSession::fallback(), events_tx)
}

pub(crate) fn spawn_sms_send_with_auth_session(
    ticket: String,
    auth_session: DiscordAuthSession,
    events_tx: mpsc::Sender<PasswordAuthEvent>,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let _ = events_tx
            .send(PasswordAuthEvent::Status(
                "Requesting Discord SMS code...".to_string(),
            ))
            .await;

        match send_mfa_sms(&ticket, &auth_session).await {
            Ok(phone) => {
                let _ = events_tx.send(PasswordAuthEvent::SmsSent { phone }).await;
            }
            Err(error) => {
                let _ = events_tx.send(PasswordAuthEvent::Failed(error)).await;
            }
        }
    })
}

enum LoginOutcome {
    Token(String),
    MfaRequired(MfaChallenge),
}

async fn login_with_password(
    login: &str,
    password: &str,
    auth_session: &DiscordAuthSession,
) -> Result<LoginOutcome, String> {
    let response = auth_session
        .http()
        .post(LOGIN_URL)
        .headers(discord_login_headers(auth_session.fingerprint()))
        .json(&json!({
            "login": normalize_login_identifier(login),
            "password": password,
        }))
        .send()
        .await
        .map_err(|error| format!("Discord password login request failed: {error}"))?;

    let status = response.status();
    let body = response
        .text()
        .await
        .map_err(|error| format!("read Discord password login response failed: {error}"))?;

    if status.is_success() {
        parse_login_success(&body)
    } else {
        Err(format_login_error(status, &body))
    }
}

async fn send_mfa_sms(
    ticket: &str,
    auth_session: &DiscordAuthSession,
) -> Result<Option<String>, String> {
    #[derive(Deserialize)]
    struct SmsResponse {
        phone: Option<String>,
    }

    let response = auth_session
        .http()
        .post(MFA_SMS_SEND_URL)
        .headers(discord_login_headers(auth_session.fingerprint()))
        .json(&json!({ "ticket": ticket }))
        .send()
        .await
        .map_err(|error| format!("Discord SMS request failed: {error}"))?;

    let status = response.status();
    let body = response
        .text()
        .await
        .map_err(|error| format!("read Discord SMS response failed: {error}"))?;

    if status.is_success() {
        let response: SmsResponse = serde_json::from_str(&body)
            .map_err(|error| format!("decode Discord SMS response failed: {error}"))?;
        Ok(response.phone)
    } else {
        Err(format_login_error(status, &body))
    }
}

async fn verify_mfa(
    method: MfaMethod,
    code: &str,
    ticket: &str,
    login_instance_id: &str,
    auth_session: &DiscordAuthSession,
) -> Result<String, String> {
    let url = format!("{MFA_VERIFY_URL}/{}", method.endpoint_name());
    let response = auth_session
        .http()
        .post(url)
        .headers(discord_login_headers(auth_session.fingerprint()))
        .json(&json!({
            "code": code.trim(),
            "login_instance_id": login_instance_id,
            "ticket": ticket,
        }))
        .send()
        .await
        .map_err(|error| format!("Discord MFA request failed: {error}"))?;

    let status = response.status();
    let body = response
        .text()
        .await
        .map_err(|error| format!("read Discord MFA response failed: {error}"))?;

    if status.is_success() {
        mfa_token_from_body(&body)
    } else {
        Err(format_login_error(status, &body))
    }
}

fn parse_login_success(body: &str) -> Result<LoginOutcome, String> {
    #[derive(Deserialize)]
    struct LoginResponse {
        token: Option<String>,
        mfa: Option<bool>,
        sms: Option<bool>,
        totp: Option<bool>,
        ticket: Option<String>,
        login_instance_id: Option<String>,
        suspended_user_token: Option<String>,
    }

    let response: LoginResponse = serde_json::from_str(body)
        .map_err(|error| format!("decode Discord password login response failed: {error}"))?;
    if let Some(token) = response.token {
        return Ok(LoginOutcome::Token(token));
    }
    if response.mfa == Some(true) {
        let ticket = response
            .ticket
            .ok_or("Discord MFA response did not include a ticket")?;
        let login_instance_id = response
            .login_instance_id
            .ok_or("Discord MFA response did not include a login instance id")?;
        let mut methods = Vec::new();
        if response.totp == Some(true) {
            methods.push(MfaMethod::Totp);
        }
        if response.sms == Some(true) {
            methods.push(MfaMethod::Sms);
        }
        if methods.is_empty() {
            return Err(
                "Discord requires MFA, but this terminal supports only TOTP and SMS".into(),
            );
        }
        return Ok(LoginOutcome::MfaRequired(MfaChallenge {
            ticket,
            login_instance_id,
            methods,
        }));
    }
    if response.suspended_user_token.is_some() {
        return Err("Discord account is suspended".into());
    }
    Err("Discord password login response did not include a token".into())
}

fn mfa_token_from_body(body: &str) -> Result<String, String> {
    #[derive(Deserialize)]
    struct MfaVerifyResponse {
        token: Option<String>,
    }

    let response: MfaVerifyResponse = serde_json::from_str(body)
        .map_err(|error| format!("decode Discord MFA response failed: {error}"))?;
    response
        .token
        .ok_or_else(|| "Discord MFA response did not include a token".to_owned())
}

fn format_login_error(status: reqwest::StatusCode, body: &str) -> String {
    #[derive(Deserialize)]
    struct DiscordError {
        code: Option<i64>,
        message: Option<String>,
        captcha_key: Option<Value>,
    }

    let Ok(error) = serde_json::from_str::<DiscordError>(body) else {
        return format!("Discord login failed with HTTP {status}");
    };
    if error.captcha_key.is_some() {
        return "Discord requires captcha verification, so email/password login cannot continue in this terminal. Log in with a token instead.".to_string();
    }
    match error.code {
        Some(50035) => "Discord rejected the email/phone number or password".to_string(),
        Some(20013) | Some(20011) => {
            "Discord account is disabled or marked for deletion".to_string()
        }
        Some(70007) => "Discord requires phone verification before login can continue".to_string(),
        Some(70009) => "Discord requires email verification before login can continue".to_string(),
        _ => error
            .message
            .unwrap_or_else(|| format!("Discord login failed with HTTP {status}")),
    }
}

fn normalize_login_identifier(login: &str) -> String {
    let trimmed = login.trim();
    if trimmed.starts_with('+') {
        trimmed.replace([' ', '-'], "")
    } else {
        trimmed.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::{
        LoginOutcome, MfaMethod, format_login_error, normalize_login_identifier,
        parse_login_success,
    };
    use reqwest::StatusCode;

    #[test]
    fn parse_login_success_returns_token() {
        let outcome = parse_login_success(r#"{"token":"abc"}"#).expect("token should parse");

        assert!(matches!(outcome, LoginOutcome::Token(token) if token == "abc"));
    }

    #[test]
    fn parse_login_success_returns_supported_mfa_methods() {
        let outcome = parse_login_success(
            r#"{"mfa":true,"sms":true,"totp":true,"ticket":"ticket","login_instance_id":"login"}"#,
        )
        .expect("mfa should parse");

        let LoginOutcome::MfaRequired(challenge) = outcome else {
            panic!("expected MFA challenge");
        };
        assert_eq!(challenge.ticket, "ticket");
        assert_eq!(challenge.login_instance_id, "login");
        assert_eq!(challenge.methods, vec![MfaMethod::Totp, MfaMethod::Sms]);
    }

    #[test]
    fn phone_login_identifier_removes_common_separators() {
        assert_eq!(normalize_login_identifier("+1 234-567"), "+1234567");
    }

    #[test]
    fn login_errors_are_clear_without_raw_sensitive_body() {
        let cases = [
            (
                StatusCode::BAD_REQUEST,
                r#"{"captcha_key":["captcha-required"],"captcha_rqtoken":"secret"}"#,
                "captcha",
            ),
            (
                StatusCode::TOO_MANY_REQUESTS,
                "not json secret",
                "Discord login failed with HTTP 429 Too Many Requests",
            ),
        ];

        for (status, body, expected) in cases {
            let message = format_login_error(status, body);
            assert!(message.contains(expected));
            assert!(!message.contains("secret"));
        }
        assert_eq!(
            format_login_error(StatusCode::TOO_MANY_REQUESTS, "not json secret"),
            "Discord login failed with HTTP 429 Too Many Requests"
        );
    }
}