cbwaw 0.5.50

Auth for Ordinary
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use blake2::{
    Blake2bVar,
    digest::{Update, VariableOutput},
};
use bytes::{BufMut, Bytes, BytesMut};
use chacha20poly1305::{
    XChaCha20Poly1305, XNonce,
    aead::{Aead, AeadCore, KeyInit, OsRng},
};
use qrcodegen::QrCode;
use x25519_dalek::{PublicKey, StaticSecret};

use totp_rs::{Algorithm, Secret, TOTP};

use std::error::Error;
use std::fmt::Write;

pub struct AuthClient {}

impl AuthClient {
    /// `account_len.account.client_start`
    /// (`client_state`, payload)
    pub fn registration_start_req(
        account: &[u8],
        password: &[u8],
        invite_token: Option<Bytes>,
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        let (client_state, client_start) = crate::registration::client_start(password)?;

        let account_len = account.len();
        if account_len > crate::MAX_ACCOUNT_LEN as usize {
            return Err("account is too long".into());
        }

        let mut buf = BytesMut::with_capacity(1 + account_len + 32);

        buf.put_u8(u8::try_from(account_len)?);
        buf.put(account);
        buf.put(&client_start[..]);

        if let Some(token) = invite_token {
            buf.put(token);
        }

        Ok((client_state, buf.into()))
    }

    /// `account_len.account.client_finish`
    /// payload
    pub fn registration_finish_req(
        account: &[u8],
        password: &[u8],
        client_state: &[u8],
        server_message: &[u8],
    ) -> Result<([u8; 32], Bytes), Box<dyn Error>> {
        let client_finish =
            crate::registration::client_finish(password, client_state, server_message)?;

        let account_len = account.len();
        if account_len > crate::MAX_ACCOUNT_LEN as usize {
            return Err("account is too long".into());
        }

        let static_secret = StaticSecret::random_from_rng(OsRng);
        let public_key = PublicKey::from(&static_secret);

        let private_key = *static_secret.as_bytes();

        let mut buf = BytesMut::with_capacity(1 + account_len + client_finish.len());

        buf.put_u8(u8::try_from(account_len)?);
        buf.put(account);
        buf.put(&public_key.as_bytes()[..]);
        buf.put(&client_finish[..]);

        Ok((private_key, buf.into()))
    }

    pub fn decrypt_totp_mfa(
        response: &Bytes,
        private_key: [u8; 32],
        app_name: String,
        account: String,
    ) -> Result<(TOTP, String), Box<dyn Error>> {
        let static_secret = StaticSecret::from(private_key);
        let public_key_bytes: [u8; 32] = response[115..147].try_into()?;
        let public_key = PublicKey::from(public_key_bytes);

        let shared_secret = static_secret.diffie_hellman(&public_key);

        let cipher = XChaCha20Poly1305::new(shared_secret.as_bytes().into());

        let nonce = XNonce::from_slice(&response[91..115]);
        let (secret, codes) = match cipher.decrypt(nonce, &response[0..91]) {
            Ok(secret_and_codes) => (
                secret_and_codes[0..20].to_vec(),
                std::str::from_utf8(&secret_and_codes[20..])?.to_string(),
            ),
            Err(err) => return Err(err.to_string().into()),
        };

        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Raw(secret).to_bytes()?,
            Some(app_name),
            account,
        )?;

        Ok((totp, codes))
    }

    pub fn decrypt_totp_mfa_code(
        response: &Bytes,
        private_key: [u8; 32],
        app_name: String,
        account: String,
    ) -> Result<(String, String), Box<dyn Error>> {
        let (totp, recovery_codes) =
            Self::decrypt_totp_mfa(response, private_key, app_name, account)?;
        let mfa_code = totp.generate_current()?;
        Ok((mfa_code, recovery_codes))
    }

    pub fn decrypt_totp_mfa_to_qr_svg(
        response: &Bytes,
        private_key: [u8; 32],
        app_name: String,
        account: String,
    ) -> Result<(String, String), Box<dyn Error>> {
        let (totp, recovery_codes) =
            Self::decrypt_totp_mfa(response, private_key, app_name, account)?;
        let qr: QrCode = QrCode::encode_text(&totp.get_url(), qrcodegen::QrCodeEcc::Medium)?;

        let svg = to_svg_string(&qr, 4)?;
        Ok((svg, recovery_codes))
    }

    /// `account_len.account.client_start`
    /// (`client_state`, payload)
    pub fn login_start_req(
        account: &[u8],
        password: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        let (client_state, client_start) = crate::login::client_start(password)?;

        let account_len = account.len();
        if account_len > crate::MAX_ACCOUNT_LEN as usize {
            return Err("account is too long".into());
        }

        let mut buf = BytesMut::with_capacity(1 + account_len + client_start.len());

        buf.put_u8(u8::try_from(account_len)?);
        buf.put(account);
        buf.put(&client_start[..]);

        Ok((client_state, buf.into()))
    }

    /// `account_len.account.client_finish`
    /// payload
    pub fn login_finish_req(
        account: &[u8],
        password: &[u8],
        mfa_hash: &[u8],
        client_state: &[u8],
        server_message: &[u8],
        client_verifier: Option<&[u8]>,
    ) -> Result<(Bytes, Vec<u8>), Box<dyn Error>> {
        let (client_finish, session_key) =
            crate::login::client_finish(password, client_state, server_message)?;

        let account_len = account.len();
        if account_len > crate::MAX_ACCOUNT_LEN as usize {
            return Err("account is too long".into());
        }

        let mut buf = BytesMut::with_capacity(1 + account_len + 32 + 32 + 16 + 24 + 64);

        buf.put_u8(u8::try_from(account_len)?);
        buf.put(account);

        let mut key = [0u8; 32];

        let mut hasher = match Blake2bVar::new(32) {
            Ok(h) => h,
            Err(err) => return Err(err.to_string().into()),
        };
        hasher.update(&session_key[..]);
        if let Err(err) = hasher.finalize_variable(&mut key) {
            return Err(err.to_string().into());
        }

        let cipher = XChaCha20Poly1305::new(&key.into());

        let mut mfa_hash_verifier_and_verifier_pub_key = BytesMut::with_capacity(64);
        mfa_hash_verifier_and_verifier_pub_key.put(mfa_hash);

        if let Some(client_verifier) = client_verifier {
            mfa_hash_verifier_and_verifier_pub_key.put(client_verifier);
        }

        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let mut encrypted_mfa_hash =
            match cipher.encrypt(&nonce, &mfa_hash_verifier_and_verifier_pub_key[..]) {
                Ok(e) => e,
                Err(err) => return Err(err.to_string().into()),
            };
        encrypted_mfa_hash.extend_from_slice(&nonce);

        buf.put(&encrypted_mfa_hash[..]);
        buf.put(&client_finish[..]);

        Ok((buf.into(), session_key))
    }

    pub fn decrypt_token(response: &Bytes, session_key: &[u8]) -> Result<Bytes, Box<dyn Error>> {
        crate::login::decrypt_token(response, session_key)
    }

    pub fn reset_password_login_start_req(
        account: &[u8],
        password: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        Self::login_start_req(account, password)
    }

    pub fn reset_password_login_finish_req(
        account: &[u8],
        password: &[u8],
        mfa_hash: &[u8],
        client_state: &[u8],
        server_message: &[u8],
        client_verifier: Option<&[u8]>,
    ) -> Result<(Bytes, Vec<u8>), Box<dyn Error>> {
        Self::login_finish_req(
            account,
            password,
            mfa_hash,
            client_state,
            server_message,
            client_verifier,
        )
    }

    pub fn password_reset_registration_start_req(
        account: &[u8],
        password: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        Self::registration_start_req(account, password, None)
    }

    pub fn password_reset_registration_finish_req(
        account: &[u8],
        password: &[u8],
        client_state: &[u8],
        server_message: &[u8],
    ) -> Result<Bytes, Box<dyn Error>> {
        let (_, req) =
            Self::registration_finish_req(account, password, client_state, server_message)?;

        Ok(req)
    }

    pub fn forgot_password_start_req(
        account: &[u8],
        new_password: &[u8],
        recovery_code: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        let (state, payload) = Self::registration_start_req(account, new_password, None)?;

        let mut payload: BytesMut = payload.into();
        payload.extend_from_slice(recovery_code);

        Ok((state, payload.into()))
    }

    pub fn forgot_password_finish_req(
        account: &[u8],
        new_password: &[u8],
        client_state: &[u8],
        server_message: &[u8],
        recovery_code: &[u8],
    ) -> Result<Bytes, Box<dyn Error>> {
        let (_, payload) =
            Self::registration_finish_req(account, new_password, client_state, server_message)?;

        let mut payload: BytesMut = payload.into();
        payload.extend_from_slice(recovery_code);

        Ok(payload.into())
    }

    pub fn reset_totp_mfa_start_req(
        account: &[u8],
        password: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        Self::login_start_req(account, password)
    }

    pub fn reset_totp_mfa_finish_req(
        account: &[u8],
        password: &[u8],
        mfa_hash: &[u8],
        client_state: &[u8],
        server_message: &[u8],
    ) -> Result<(Bytes, Vec<u8>), Box<dyn Error>> {
        Self::login_finish_req(
            account,
            password,
            mfa_hash,
            client_state,
            server_message,
            None,
        )
    }

    pub fn decrypt_reset_totp_mfa(
        response: &Bytes,
        session_key: &[u8],
    ) -> Result<Bytes, Box<dyn Error>> {
        crate::login::decrypt_token(response, session_key)
    }

    pub fn decrypt_reset_totp_mfa_code(
        response: &Bytes,
        session_key: &[u8],
        app_name: String,
        account: String,
    ) -> Result<String, Box<dyn Error>> {
        let secret = Self::decrypt_reset_totp_mfa(response, session_key)?;

        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Raw(secret.to_vec()).to_bytes()?,
            Some(app_name),
            account,
        )?;

        let mfa_code = totp.generate_current()?;

        Ok(mfa_code)
    }

    pub fn decrypt_reset_totp_mfa_to_qr_svg(
        response: &Bytes,
        session_key: &[u8],
        app_name: String,
        account: String,
    ) -> Result<String, Box<dyn Error>> {
        let secret = Self::decrypt_reset_totp_mfa(response, session_key)?;

        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Raw(secret.to_vec()).to_bytes()?,
            Some(app_name),
            account,
        )?;

        let qr: QrCode = QrCode::encode_text(&totp.get_url(), qrcodegen::QrCodeEcc::Medium)?;
        let svg = to_svg_string(&qr, 4)?;

        Ok(svg)
    }

    pub fn lost_totp_mfa_start_req(
        account: &[u8],
        password: &[u8],
        recovery_code: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        let (state, payload) = Self::login_start_req(account, password)?;

        let mut payload: BytesMut = payload.into();
        payload.extend_from_slice(recovery_code);

        Ok((state, payload.into()))
    }

    pub fn lost_totp_mfa_finish_req(
        account: &[u8],
        password: &[u8],
        client_state: &[u8],
        server_message: &[u8],
        recovery_code: &[u8],
    ) -> Result<(Bytes, Vec<u8>), Box<dyn Error>> {
        let (payload, session_key) = Self::login_finish_req(
            account,
            password,
            &[0u8; 32][..],
            client_state,
            server_message,
            None,
        )?;

        let mut payload: BytesMut = payload.into();
        payload.extend_from_slice(recovery_code);

        Ok((payload.into(), session_key))
    }

    pub fn decrypt_lost_totp_mfa(
        response: &Bytes,
        session_key: &[u8],
    ) -> Result<Bytes, Box<dyn Error>> {
        Self::decrypt_reset_totp_mfa(response, session_key)
    }

    pub fn decrypt_lost_totp_mfa_code(
        response: &Bytes,
        session_key: &[u8],
        app_name: String,
        account: String,
    ) -> Result<String, Box<dyn Error>> {
        Self::decrypt_reset_totp_mfa_code(response, session_key, app_name, account)
    }

    pub fn decrypt_lost_totp_mfa_to_qr_svg(
        response: &Bytes,
        session_key: &[u8],
        app_name: String,
        account: String,
    ) -> Result<String, Box<dyn Error>> {
        Self::decrypt_reset_totp_mfa_to_qr_svg(response, session_key, app_name, account)
    }

    pub fn reset_recovery_codes_start_req(
        account: &[u8],
        password: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        Self::login_start_req(account, password)
    }

    pub fn reset_recovery_codes_finish_req(
        account: &[u8],
        password: &[u8],
        mfa_hash: &[u8],
        client_state: &[u8],
        server_message: &[u8],
    ) -> Result<(Bytes, Vec<u8>), Box<dyn Error>> {
        Self::login_finish_req(
            account,
            password,
            mfa_hash,
            client_state,
            server_message,
            None,
        )
    }

    pub fn decrypt_reset_recovery_codes(
        response: &Bytes,
        session_key: &[u8],
    ) -> Result<String, Box<dyn Error>> {
        let codes = crate::login::decrypt_token(response, session_key)?;
        let codes_str = std::str::from_utf8(&codes)?.to_string();

        Ok(codes_str)
    }

    /// `refresh_token`
    #[must_use]
    pub fn access_get_req(refresh_token: &[u8]) -> Bytes {
        Bytes::copy_from_slice(refresh_token)
    }

    pub fn delete_account_start_req(
        account: &[u8],
        password: &[u8],
    ) -> Result<(Vec<u8>, Bytes), Box<dyn Error>> {
        Self::login_start_req(account, password)
    }

    pub fn delete_account_finish_req(
        account: &[u8],
        password: &[u8],
        mfa_hash: &[u8],
        client_state: &[u8],
        server_message: &[u8],
    ) -> Result<Bytes, Box<dyn Error>> {
        let (req, _) = Self::login_finish_req(
            account,
            password,
            mfa_hash,
            client_state,
            server_message,
            None,
        )?;

        Ok(req)
    }
}

// copied from qrcodegen examples https://github.com/nayuki/QR-Code-generator/blob/2c9044de6b049ca25cb3cd1649ed7e27aa055138/rust/examples/qrcodegen-demo.rs#L169
fn to_svg_string(qr: &QrCode, border: u8) -> Result<String, Box<dyn Error>> {
    let border: i32 = border.into();
    let mut result = String::new();
    // result += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    // result += "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";

    if let Some(border) = border.checked_mul(2)
        && let Some(dimension) = qr.size().checked_add(border)
    {
        writeln!(
            result,
            "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {dimension} {dimension}\" stroke=\"none\">"
        )?;
        result += "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n";
        result += "\t<path d=\"";
        for y in 0..qr.size() {
            for x in 0..qr.size() {
                if qr.get_module(x, y) {
                    if x != 0 || y != 0 {
                        result += " ";
                    }
                    write!(result, "M{},{}h1v1h-1z", x + border, y + border)?;
                }
            }
        }
        result += "\" fill=\"#000000\"/>\n";
        result += "</svg>\n";
    }

    Ok(result)
}