ordinary-api 0.6.0-pre.14

API server 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

use axum::body::Bytes;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum_extra::extract::Query;
use hyper::HeaderMap;
use std::fs::create_dir_all;

use crate::server::{ADMIN, AUTHENTICATION, OrdinaryApiServerState, ROOT};
use ordinary_auth::{validate_account, validate_domain};

use base64::{Engine as B64Engine, engine::general_purpose::URL_SAFE_NO_PAD as b64};
use flexbuffers::VectorReader;
use ordinary_utils::get_bearer_token_as_bytes;
use serde::Deserialize;
use std::sync::Arc;
use utoipa::IntoParams;

// todo: make this a wasm ordinary action
#[allow(clippy::unnecessary_wraps)]
fn invite_claims_validator(account: &str, claims: &VectorReader<&[u8]>) -> anyhow::Result<bool> {
    let claims_account = claims.idx(1).as_str();

    if claims_account != account {
        return Ok(false);
    }

    Ok(true)
}

#[derive(Deserialize, IntoParams)]
pub struct InviteParams {
    /// domain name for the invited user
    d: String,
    /// account name for the invited user
    a: String,
    /// permission set for the invited user
    #[serde(default)]
    p: Vec<u8>,
}

#[utoipa::path(
        get,
        path = "/accounts/invite",
        tags = [AUTHENTICATION],
        params(Params),
        responses(
            (status = 401, description = "unauthorized for operation"),
            (status = 409, description = "account or domain already registered"),
            (status = 200, description = "invite token as bytes", body = [u8]),
        ),
        security(
            ("access" = []),
        ),
)]
pub async fn invite(
    State(state): State<Arc<OrdinaryApiServerState>>,
    Query(InviteParams { d, a, p }): Query<InviteParams>,
    headers: HeaderMap,
) -> impl IntoResponse {
    let span = tracing::info_span!("api");
    let span = span.in_scope(|| tracing::info_span!("accounts"));
    let span = span.in_scope(|| tracing::info_span!("invite"));

    span.in_scope(|| {
        if !validate_domain(&state.app_domains, d.as_str())
            && !state.privileged_domains.contains(&d)
        {
            tracing::error!("invalid domain");
            return StatusCode::BAD_REQUEST.into_response();
        }

        let invited_domain = d;

        let inviter_account =
            match crate::server::check_ordinary_auth(&state, &headers, 0, &invited_domain) {
                Ok(account) => account,
                Err(code) => return code.into_response(),
            };

        let domain_exists = state.apps_dir.join(&invited_domain).exists();
        if domain_exists {
            tracing::warn!(domain = %invited_domain, "exists");
            return StatusCode::CONFLICT.into_response();
        }

        let Ok(invited_account) = validate_account(&a) else {
            tracing::error!("invalid account");
            return StatusCode::BAD_REQUEST.into_response();
        };

        match state.auth.account_exists(&invited_account) {
            Ok(exists) => {
                if exists {
                    tracing::warn!(account = %invited_account, "exists");
                    return StatusCode::CONFLICT.into_response();
                }
            }
            Err(err) => {
                tracing::error!(%err);
                return StatusCode::INTERNAL_SERVER_ERROR.into_response();
            }
        }

        tracing::info!("inviting");

        let Some(invite_config) = &state.auth.config.invite else {
            return StatusCode::INTERNAL_SERVER_ERROR.into_response();
        };

        if invite_config.claims.is_none() {
            return StatusCode::INTERNAL_SERVER_ERROR.into_response();
        }

        let mut builder = flexbuffers::Builder::new(&flexbuffers::BuilderOptions::SHARE_NONE);
        let mut builder_vec = builder.start_vector();

        // gap for system claims
        builder_vec.push(());

        builder_vec.push(invited_account.as_str());
        builder_vec.push(invited_domain.as_str());

        let mut perms_vec = builder_vec.start_vector();

        for perm in &p {
            perms_vec.push(*perm);
        }

        perms_vec.end_vector();

        builder_vec.end_vector();

        let inviter_domain = if inviter_account == "root" {
            state.domain.clone()
        } else {
            invited_domain
        };

        match state.auth.api_invite_get(
            &inviter_domain,
            &inviter_account,
            Some(Bytes::copy_from_slice(builder.view())),
        ) {
            Ok(v) => (StatusCode::OK, v).into_response(),
            Err(err) => {
                tracing::error!(%err);
                StatusCode::INTERNAL_SERVER_ERROR.into_response()
            }
        }
    })
}

#[utoipa::path(
    post,
    path = "/accounts/registration/start",
    tag = AUTHENTICATION,
    description = "
Extended [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/) Registration Start

request body:
- 1.....`body[0]`: account name length
- <=255.`body[1..=body[0]]`: account name
- 32....`body[body[0] + 1..=body[0] + 32]`: client registration start for [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/)
",
    request_body(
        content = [u8],
        content_type = "application/octet-stream",
    ),
    responses(
        (status = 500, description = "registration start error"),
        (
            status = 200,
            body = [u8],
            description = "
response body:
- 64 `body[0..=64]`: server registration start for [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/)
            ",
        ),
    ),
    security(
        ("invite" = []),
    ),
)]
pub async fn registration_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    headers: HeaderMap,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| {
        let Ok(invite_token) = get_bearer_token_as_bytes(&headers) else {
            return StatusCode::UNAUTHORIZED.into_response();
        };

        let Ok(checked_claims) = state.auth.invite_check(invite_token.as_ref()) else {
            return StatusCode::UNAUTHORIZED.into_response();
        };

        let invited_domain = checked_claims.0.idx(2).as_str();

        let domain_exists = state.apps_dir.join(invited_domain).exists();
        if domain_exists {
            tracing::warn!(domain = %invited_domain, "exists");
            return StatusCode::CONFLICT.into_response();
        }

        match state.auth.registration_start(
            body,
            None,
            Some(invite_claims_validator),
            Some(checked_claims),
        ) {
            Ok(v) => (StatusCode::OK, v).into_response(),
            Err(err) => {
                tracing::error!(%err);
                StatusCode::INTERNAL_SERVER_ERROR.into_response()
            }
        }
    })
}

#[utoipa::path(
    post,
    path = "/accounts/registration/finish",
    tag = AUTHENTICATION,
    description = "
Extended [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/) Registration Finish

request body:
- 1.....`body[0]`: account name length
- <=255.`body[1..=body[0]]`: account name
- 32....`body[body[0] + 1..=body[0] + 32]`: ephemeral client public `X25519` key (for encrypting MFA secret and recovery codes)
- 192...`body[body[0] + 1 + 32..]`: client registration finish for [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/)
    ",
    request_body(
        content = [u8],
        content_type = "application/octet-stream",
    ),
    responses(
        (status = 500, description = "registration finish error"),
        (
            status = 200,
            body = [u8],
            description = "
TOTP MFA secret and recovery codes encrypted, together, using
`XChaCha20Poly1305` with an ephemeral `X25519` shared secret.

---
response body:
- 20 `body[0..<20]`: (encrypted) TOTP MFA secret
- 55 `body[20..<75]`: (encrypted) recovery codes (5 codes each 11 chars)
- 16 `body[75..<91]`: `Poly1305` MAC
- 24 `body[91..<115]`: extended 192 bit nonce
- 32 `body[115..<147]`: ephemeral server public `X25519` key
            ",
        ),
    ),
)]
pub async fn registration_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| {
        match state.auth.registration_finish(body, None) {
            Ok((v, account_bytes, invite_claims)) => {
                if let Some(invite_claims) = invite_claims {
                    let mut builder =
                        flexbuffers::Builder::new(&flexbuffers::BuilderOptions::SHARE_NONE);
                    let mut builder_vec = builder.start_vector();

                    let system_claims_gap = builder_vec.start_vector();
                    system_claims_gap.end_vector();

                    if let Ok(invite_claims_root) =
                        flexbuffers::Reader::get_root(&invite_claims[..])
                    {
                        let invite_claims_vec = invite_claims_root.as_vector();

                        for claim in &state.auth.config.access_token.claims {
                            if claim.idx == 1 {
                                let domain = invite_claims_vec.idx(2).as_str();
                                let app_dir = state.apps_dir.join(domain);

                                // reserves the app dir so that future registrations with that domain fail
                                if let Err(err) = create_dir_all(app_dir) {
                                    tracing::error!(%err);
                                }

                                builder_vec.push(domain);
                            } else if claim.idx == 2
                                && let Err(err) = claim.kind.copy_to(
                                    &invite_claims_vec.idx(3),
                                    &mut builder_vec,
                                    None,
                                )
                            {
                                tracing::error!(%err);
                            }
                        }

                        builder_vec.end_vector();

                        if let Err(err) = state.auth.set_claims(&account_bytes, builder.view()) {
                            tracing::error!(%err);
                        }
                    }
                }

                (StatusCode::OK, v)
            }
            Err(err) => {
                tracing::error!(%err);
                (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
            }
        }
    })
}

#[utoipa::path(
    post,
    path = "/accounts/login/start",
    tag = AUTHENTICATION,
    description = "
Extended [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/) Login Start

request body:
- 1.....`body[0]`: account name length
- <=255.`body[1..=body[0]]`: account name
- 96....`body[body[0] + 1..=body[0] + 32]`: client login start for [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/)
",
    request_body(
        content = [u8],
        content_type = "application/octet-stream",
    ),
    responses(
        (status = 500, description = "login start error"),
        (
            status = 200,
            body = [u8],
            description = "
response body:
- 320 `body[0..=320]`: server login start for [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/)
            ",
        ),
    ),
)]
pub async fn login_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.login_start(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
    post,
    path = "/accounts/login/finish",
    tag = AUTHENTICATION,
    description = "
Extended [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/) Login Finish

`Ed25519` client verifying key and `SHA-256` hashed TOTP MFA code, encrypted, together,
using `XChaCha20Poly1305` with the `OPAQUE` session key, in order to bind
those components to the successful OPAQUE result.

request body:
- 1.....`body[0]`: account name length
- <=255.`body[1..=body[0]]`: account name
- 32....`body[body[0] + 1..=body[0] + 32]`: (encrypted) client `Ed25519` verifying key
- 32....`body[body[0] + 1 + 32..=body[0] + 64]`: (encrypted) `SHA-256` hash of the TOTP MFA code
- 16....`body[body[0] + 1 + 64..=body[0] + 80]`: `Ploy1305` MAC
- 24....`body[body[0] + 1 + 80..=body[0] + 104]`: extended 192 bit nonce
- 64...`body[body[0] + 1 + 104..=body[0] + 172]`: client login finish for [OPAQUE Key Exchange](https://datatracker.ietf.org/doc/rfc9807/)
    ",
    request_body(
        content = [u8],
        content_type = "application/octet-stream",
    ),
    responses(
        (status = 500, description = "login finish error"),
        (
            status = 200,
            body = [u8],
            description = "
encrypted using `XChaCha20Poly1305` with the `OPAQUE` session key, to ensure
the token can only be accessed by the client that successfully generated the
OPAQUE session key.

---
response body:
- n..`body[..-40]`: refresh token bytes
- 16.`body[n..<n + 16]`: `Ploy1305` MAC
- 24.`body[n + 16..<n + 40]`: extended 192 bit nonce
            ",
        ),
    ),
)]
pub async fn login_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.login_finish(body, true) {
        Ok((v, _, _)) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
    get,
    path = "/accounts/access",
    tag = AUTHENTICATION,
    description = "get an `access_token` with a `refresh_token`",
    responses(
        (status = 500, description = "access token generation error"),
        (status = 401, description = "invalid refresh token"),
        (
            status = 200,
            body = [u8],
            description = "valid access token",
        ),
    ),
    security(
        ("refresh" = []),
    ),
)]
pub async fn access_get(
    State(state): State<Arc<OrdinaryApiServerState>>,
    headers: HeaderMap,
) -> impl IntoResponse {
    let Ok(refresh_token) = get_bearer_token_as_bytes(&headers) else {
        return StatusCode::UNAUTHORIZED.into_response();
    };

    match state.auth.access_get(&refresh_token.into()) {
        Ok(v) => (StatusCode::OK, v).into_response(),
        Err(err) => {
            tracing::error!(%err);
            StatusCode::INTERNAL_SERVER_ERROR.into_response()
        }
    }
}

pub async fn logout(
    State(_state): State<Arc<OrdinaryApiServerState>>,
    _body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| {
        // todo: add refresh token to block set
        (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
    })
}

#[utoipa::path(
        post,
        path = "/accounts/password/reset/login/start",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "password reset login start error"),
            (status = 200, description = "login start", body = [u8]),
        ),
)]
pub async fn password_reset_login_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.reset_password_login_start(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/password/reset/login/finish",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "password reset login finish error"),
            (status = 200, description = "encrypted password reset token", body = [u8]),
        ),
)]
pub async fn password_reset_login_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.reset_password_login_finish(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/password/reset/registration/start",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "password reset registration start error"),
            (status = 200, description = "registration start", body = [u8]),
        ),
)]
pub async fn password_reset_registration_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    headers: HeaderMap,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| {
        let mut token: Vec<u8> = vec![];

        if let Some(val) = headers.get("authorization")
            && let Ok(str_val) = val.to_str()
            && let Some(b64_token) = str_val.strip_prefix("Bearer ")
            && let Ok(t) = b64.decode(b64_token)
        {
            token = t;
        }

        if token.is_empty() {
            return (StatusCode::UNAUTHORIZED, Bytes::new());
        }

        match state.auth.reset_password_registration_start(body, &token) {
            Ok(v) => (StatusCode::OK, v),
            Err(err) => {
                tracing::error!(%err);
                (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
            }
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/password/reset/registration/finish",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "password reset registration finish error"),
            (status = 200, description = "success"),
        ),
)]
pub async fn password_reset_registration_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    headers: HeaderMap,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| {
        let mut token: Vec<u8> = vec![];

        if let Some(val) = headers.get("authorization")
            && let Ok(str_val) = val.to_str()
            && let Some(b64_token) = str_val.strip_prefix("Bearer ")
            && let Ok(t) = b64.decode(b64_token)
        {
            token = t;
        }

        if token.is_empty() {
            return StatusCode::UNAUTHORIZED;
        }

        match state.auth.reset_password_registration_finish(body, &token) {
            Ok(()) => StatusCode::OK,
            Err(err) => {
                tracing::error!(%err);
                StatusCode::INTERNAL_SERVER_ERROR
            }
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/password/forgot/start",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "password forgot start error"),
            (status = 200, description = "registration start", body = [u8]),
        ),
)]
pub async fn password_forgot_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.forgot_password_start(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/password/forgot/finish",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "password forgot finish error"),
            (status = 200, description = "success"),
        ),
)]
pub async fn password_forgot_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.forgot_password_finish(body) {
        Ok(()) => StatusCode::OK,
        Err(err) => {
            tracing::error!(%err);
            StatusCode::INTERNAL_SERVER_ERROR
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/mfa/totp/reset/start",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "MFA TOTP reset start error"),
            (status = 200, description = "login start", body = [u8]),
        ),
)]
pub async fn mfa_reset_totp_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.reset_totp_mfa_start(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/mfa/totp/reset/finish",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "MFA TOTP reset finish error"),
            (status = 200, description = "encrypted MFA secret", body = [u8]),
        ),
)]
pub async fn mfa_reset_totp_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.reset_totp_mfa_finish(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/mfa/totp/lost/start",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "MFA TOTP lost start error"),
            (status = 200, description = "login start", body = [u8]),
        ),
)]
pub async fn mfa_lost_totp_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.lost_totp_mfa_start(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/mfa/totp/lost/finish",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "MFA TOTP lost finish error"),
            (status = 200, description = "encrypted MFA TOTP secret", body = [u8]),
        ),
)]
pub async fn mfa_lost_totp_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.lost_totp_mfa_finish(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/recovery-codes/reset/start",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "recovery codes reset start error"),
            (status = 200, description = "login start", body = [u8]),
        ),
)]
pub async fn recovery_reset_codes_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.reset_recovery_codes_start(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/recovery-codes/reset/finish",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "recovery codes reset finish error"),
            (status = 200, description = "encrypted recovery codes", body = [u8]),
        ),
)]
pub async fn recovery_reset_codes_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| match state.auth.reset_recovery_codes_finish(body) {
        Ok(v) => (StatusCode::OK, v),
        Err(err) => {
            tracing::error!(%err);
            (StatusCode::INTERNAL_SERVER_ERROR, Bytes::new())
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/delete/start",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "delete start error"),
            (status = 200, description = "login start", body = [u8]),
        ),
)]
pub async fn account_delete_start(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| {
        if body.len() > 4 {
            let account_len = body[0] as usize;
            let raw_account = &body[1..=account_len];
            if let Ok(raw_account_str) = std::str::from_utf8(raw_account)
                && raw_account_str == "root"
            {
                tracing::error!("cannot delete root user");
                return (StatusCode::FORBIDDEN, "cannot delete root user").into_response();
            }
        }

        match state.auth.delete_account_start(body) {
            Ok(v) => (StatusCode::OK, v).into_response(),
            Err(err) => {
                tracing::error!(%err);
                StatusCode::INTERNAL_SERVER_ERROR.into_response()
            }
        }
    })
}

#[utoipa::path(
        post,
        path = "/accounts/delete/finish",
        tags = [AUTHENTICATION],
        request_body(
            content = [u8],
            content_type = "application/octet-stream",
        ),
        responses(
            (status = 500, description = "delete finish error"),
            (status = 200, description = "success", body = [u8]),
        ),
)]
pub async fn account_delete_finish(
    State(state): State<Arc<OrdinaryApiServerState>>,
    body: Bytes,
) -> impl IntoResponse {
    let span = tracing::info_span!("auth");

    span.in_scope(|| {
        if body.len() > 4 {
            let account_len = body[0] as usize;
            let raw_account = &body[1..=account_len];
            if let Ok(raw_account_str) = std::str::from_utf8(raw_account)
                && raw_account_str == "root"
            {
                tracing::error!("cannot delete root user");
                return (StatusCode::FORBIDDEN, "cannot delete root user").into_response();
            }
        }

        match state.auth.delete_account_finish(body) {
            Ok(()) => StatusCode::OK.into_response(),
            Err(err) => {
                tracing::error!(%err);
                StatusCode::INTERNAL_SERVER_ERROR.into_response()
            }
        }
    })
}

#[derive(Deserialize, IntoParams)]
pub struct Params {
    d: String,
}

#[utoipa::path(
        get,
        path = "/accounts",
        tags = [ADMIN, ROOT],
        params(Params),
        request_body(content = [u8], content_type = "application/octet-stream"),
        responses(
            (status = 401, description = "unauthorized for operation"),
            (status = 200, description = "accounts list as flexbuffer bytes", body = [u8]),
        ),
        security(
            ("access" = []),
        ),
)]
pub async fn list(
    State(state): State<Arc<OrdinaryApiServerState>>,
    Query(Params { d }): Query<Params>,
    headers: HeaderMap,
    _body: Bytes,
) -> impl IntoResponse {
    let domain = d;

    let span = tracing::info_span!("admin");
    let span = span.in_scope(|| tracing::info_span!("accounts"));
    let span = span.in_scope(|| tracing::info_span!("list"));

    span.in_scope(|| {
        tracing::info!("listing");

        let _account = match crate::server::check_ordinary_auth(&state, &headers, 1, &domain) {
            Ok(account) => account,
            Err(code) => return code.into_response(),
        };

        // todo: list all API accounts

        (StatusCode::OK, Bytes::new()).into_response()
    })
}

#[utoipa::path(
    delete,
    path = "/accounts",
    tags = [ADMIN, ROOT],
    params(Params),
    request_body(content = [u8], content_type = "application/octet-stream"),
    responses(
        (status = 401, description = "unauthorized for operation"),
        (status = 200, description = "successfully deleted account"),
    ),
    security(
        ("access" = []),
    ),
)]
pub async fn delete(
    State(state): State<Arc<OrdinaryApiServerState>>,
    Query(Params { d }): Query<Params>,
    headers: HeaderMap,
    _body: Bytes,
) -> impl IntoResponse {
    let domain = d;

    let span = tracing::info_span!("admin");
    let span = span.in_scope(|| tracing::info_span!("accounts"));
    let span = span.in_scope(|| tracing::info_span!("delete"));

    span.in_scope(|| {
        tracing::info!("deleting");

        let _account = match crate::server::check_ordinary_auth(&state, &headers, 0, &domain) {
            Ok(account) => account,
            Err(code) => return code.into_response(),
        };

        // todo: delete API account

        StatusCode::OK.into_response()
    })
}