kernable-sdk 0.2.2

Write event-sourced business logic in Rust; the kernable kernel does the rest.
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
//! The account commands: each type with its handler.

use kernable::{Aggregate, NewEvent, Rejected, command};
use serde_json::Value;

use super::aggregates::{Account, Session, SessionStatus, Sso, SsoStatus};
use super::{
    AccountStatus, AccountSuspensionReason, FailureReason, SecondFactor, SessionEnd, TokenPurpose,
    events::*, own,
};
use crate::shared::constants::{
    DAY, HOUR, MAIL_COOLDOWN_MINUTES, MINUTE, RESET_MINUTES, SESSION_IDLE_DAYS, SESSION_MAX_DAYS,
    VERIFICATION_HOURS,
};
use crate::shared::passkeys;
use crate::shared::secrets::{
    check_password, email_domain, equal_secrets, has_space, hash_password, normal_email,
    parse_token, random_secret, sha256, totp_step, trim_space, valid_email, valid_password,
};

type Events = Result<Vec<NewEvent>, Rejected>;

fn rejected(message: &str, code: &str) -> Rejected {
    Rejected::new(message).code(code)
}

fn gone(s: &Account) -> bool {
    matches!(s.status, AccountStatus::None | AccountStatus::Deleted)
}

fn active(s: &Account) -> Result<(), Rejected> {
    if s.status == AccountStatus::Active {
        Ok(())
    } else {
        Err(rejected("The account is not active", "invalid_state"))
    }
}

// --- Registration and verification ---------------------------------------------------------------------

#[command("account", aggregate = "account", personal(fields = [email, name], subject = own), secret = [password])]
pub struct RegisterAccount {
    pub email: String,
    pub name: String,
    pub password: Option<String>,
    /// Set by the API when an accepted invitation proved the email: active at once.
    pub verified: Option<bool>,
}

/// A new verification token, kept in the vault under its own subject until used.
fn verification_requested(email: Option<String>, at: i64) -> NewEvent {
    VerificationRequested {
        token_id: random_secret(9),
        token: Some(random_secret(32)),
        email,
        expires_at: at + VERIFICATION_HOURS * HOUR,
    }
    .into()
}

#[command("account", aggregate = "account")]
pub struct RequestVerification {}

/// The open token of `purpose` that `value` proves: its ID, or why not.
fn proven(
    s: &Account,
    purpose: TokenPurpose,
    value: &str,
    aggregate_id: &str,
    now: i64,
) -> Result<String, Rejected> {
    let invalid = || rejected("The link is not valid", "invalid_token");
    let (account, token_id, secret) = parse_token(value).ok_or_else(invalid)?;
    let open = s
        .open_tokens
        .iter()
        .find(|t| t.purpose == purpose && t.token_id == token_id)
        .ok_or_else(invalid)?;
    if account != aggregate_id
        || !open
            .token
            .as_deref()
            .is_some_and(|t| equal_secrets(t, &secret))
    {
        return Err(invalid());
    }
    if now > open.expires_at {
        return Err(rejected("The link has expired", "expired_token"));
    }
    Ok(open.token_id.clone())
}

/// Public: the token from the mail is the proof.
#[command("account", aggregate = "account", secret = [token])]
pub struct VerifyEmail {
    pub token: String,
}

// --- Signing in -------------------------------------------------------------------------------------------

fn refresh_ok(refresh_token: &str, session_id: &str) -> Result<(), Rejected> {
    match parse_token(refresh_token) {
        Some((session, generation, _)) if session == session_id && generation == "1" => Ok(()),
        _ => Err(rejected("A malformed refresh token", "invalid_token")),
    }
}

/// Public: the password is the proof. The IP and user agent stay with the events (personal).
#[command("account", aggregate = "account", secret = [password, refresh_token, ip, user_agent])]
pub struct SignIn {
    pub session_id: String,
    pub password: String,
    /// `<sessionId>.1.<secret>`, generated by the API; the account keeps its hash only.
    pub refresh_token: String,
    pub ip: Option<String>,
    pub user_agent: Option<String>,
}

fn failed(method: &str, reason: FailureReason, ip: Option<String>, at: i64) -> Events {
    Ok(vec![
        SignInFailed {
            method: method.to_owned(),
            reason,
            ip,
            at,
        }
        .into(),
    ])
}

// --- Sessions -----------------------------------------------------------------------------------------------

/// Internal: the sessions reactor opens it after SignedIn.
#[command("account", aggregate = "session", secret = [ip, user_agent])]
pub struct OpenSession {
    pub account_id: String,
    pub method: String,
    pub factors: Vec<String>,
    pub refresh_token_hash: String,
    pub ip: Option<String>,
    pub user_agent: Option<String>,
    pub at: i64,
}

/// Public: the refresh token is the proof. It names its session and generation; one of the
/// session's older tokens is a reuse and ends the session. Any other token is refused, so knowing
/// a session's ID is not enough to end it.
#[command("account", aggregate = "session", secret = [refresh_token, new_refresh_token, ip])]
pub struct RefreshSession {
    pub refresh_token: String,
    /// `<sessionId>.<generation + 1>.<secret>`, generated by the API.
    pub new_refresh_token: String,
    pub ip: Option<String>,
}

/// Internal: after a second factor was proved on the account.
#[command("account", aggregate = "session")]
pub struct AddSessionFactor {
    pub factor: String,
    /// The account that proved it: only its own session gains the factor.
    pub account_id: String,
}

#[command("account", aggregate = "session")]
pub struct EndSession {
    pub reason: Option<SessionEnd>,
}

// --- The account's lifecycle -----------------------------------------------------------------------------------

/// The platform's; the person itself with `owner_requested`. Ends every session (a reactor).
#[command("account", aggregate = "account")]
pub struct SuspendAccount {
    pub reason: AccountSuspensionReason,
}

#[command("account", aggregate = "account")]
pub struct ReactivateAccount {}

/// Final, only from suspended: erases the account's personal data; its identities go too (a reactor).
#[command("account", aggregate = "account")]
pub struct DeleteAccount {}

// --- Password and email ----------------------------------------------------------------------------------------

/// The account's own. Needs the current password if it has one; ends the other sessions (a reactor).
#[command("account", aggregate = "account", secret = [current, new])]
pub struct ChangePassword {
    pub current: Option<String>,
    pub new: String,
    /// The session the change comes from: it stays.
    pub keep_session_id: Option<String>,
}

/// The API's: asked for by email, without saying whether the account exists. While the open reset
/// token is younger than `MAIL_COOLDOWN_MINUTES`, nothing new is sent (no events): asking again and
/// again mails the person once per cooldown.
#[command("account", aggregate = "account")]
pub struct RequestPasswordReset {}

/// Public: the emailed token is the proof. Ends every session (a reactor).
#[command("account", aggregate = "account", secret = [token, new])]
pub struct ResetPassword {
    pub token: String,
    pub new: String,
}

/// The account's own: the new address gets a token and holds nothing until confirmed.
#[command("account", aggregate = "account", personal(fields = [email], subject = own))]
pub struct RequestEmailChange {
    pub email: String,
}

/// Public: the token sent to the new address is the proof. The kernel refuses a taken address (the key).
#[command("account", aggregate = "account", secret = [token])]
pub struct ConfirmEmailChange {
    pub token: String,
}

/// The API's, when someone registers with this account's address: the account gets a mail, at
/// most one per `MAIL_COOLDOWN_MINUTES` (within it, no events).
#[command("account", aggregate = "account")]
pub struct NoteRegistrationAttempt {}

// --- TOTP and recovery codes --------------------------------------------------------------------------------------

/// The account's own: the secret the API generated and showed (as a QR code), personal data.
#[command("account", aggregate = "account", personal(fields = [secret], subject = own))]
pub struct StartTotp {
    pub secret: String,
}

/// The first code turns TOTP on, with recovery codes.
#[command("account", aggregate = "account", secret = [code, recovery_codes])]
pub struct ConfirmTotp {
    pub code: String,
    pub recovery_codes: Vec<String>,
}

#[command("account", aggregate = "account", secret = [code])]
pub struct DisableTotp {
    pub code: String,
}

#[command("account", aggregate = "account", secret = [code, recovery_codes])]
pub struct RegenerateRecoveryCodes {
    pub code: String,
    pub recovery_codes: Vec<String>,
}

/// Public: the code is the proof. A failure is an event and counts toward the lockout.
#[command("account", aggregate = "account", secret = [code])]
pub struct ProveSecondFactor {
    pub session_id: String,
    pub code: String,
}

fn recovery_hashes(codes: &[String]) -> Result<Vec<String>, Rejected> {
    if codes.len() < 8 || codes.iter().any(|c| c.chars().count() < 10) {
        return Err(rejected(
            "At least 8 recovery codes of 10 characters",
            "invalid_recovery_codes",
        ));
    }
    Ok(codes.iter().map(|c| sha256(c)).collect())
}

/// What a TOTP code (once) or an unused recovery code proves.
struct Proof {
    method: SecondFactor,
    step: Option<i64>,
    recovery_code_hash: Option<String>,
}

fn second_factor(s: &Account, code: &str, now: i64) -> Option<Proof> {
    let totp = s.totp.as_ref().filter(|t| t.confirmed)?;
    let secret = totp.secret.as_deref()?;
    if let Some(step) = totp_step(secret, code, now) {
        return (step > totp.last_step).then_some(Proof {
            method: SecondFactor::Totp,
            step: Some(step),
            recovery_code_hash: None,
        });
    }
    let digest = sha256(code);
    s.recovery_codes.contains(&digest).then_some(Proof {
        method: SecondFactor::Recovery,
        step: None,
        recovery_code_hash: Some(digest),
    })
}

// --- Passkeys ---------------------------------------------------------------------------------------------------

/// The account's own: a passkey registered against a challenge the API issued.
#[command("account", aggregate = "account", personal(fields = [label], subject = own))]
pub struct AddPasskey {
    pub challenge: String,
    pub response: Value,
    pub label: Option<String>,
}

#[command("account", aggregate = "account")]
pub struct RemovePasskey {
    pub credential_id: String,
}

/// The API's (it issued the challenge): a passwordless sign-in, counting as two factors.
#[command("account", aggregate = "account", secret = [refresh_token, ip, user_agent])]
pub struct SignInWithPasskey {
    pub session_id: String,
    pub challenge: String,
    pub response: Value,
    pub refresh_token: String,
    pub ip: Option<String>,
    pub user_agent: Option<String>,
}

/// The API's: a passkey as the second factor after a password.
#[command("account", aggregate = "account")]
pub struct ProvePasskey {
    pub session_id: String,
    pub challenge: String,
    pub response: Value,
}

/// Whether the account keeps another way to sign in (never remove the last one).
fn another_method(s: &Account, passkey: Option<&str>, link: Option<(&str, &str)>) -> bool {
    s.password.is_some()
        || s.passkeys
            .iter()
            .any(|p| p.credential_id.as_deref() != passkey)
        || s.links.iter().any(|x| {
            link.is_none_or(|(p, sub)| !(x.provider == p && x.subject.as_deref() == Some(sub)))
        })
}

/// The passkey a sign-in answer proves, with its new counter.
fn asserted(s: &Account, challenge: &str, response: &Value) -> Option<PasskeyUsed> {
    let id = response["id"].as_str()?;
    let passkey = s
        .passkeys
        .iter()
        .find(|p| p.credential_id.as_deref() == Some(id))?;
    let counter =
        passkeys::verify_authentication(response, challenge, &passkey.public_key, passkey.counter)
            .ok()?;
    Some(PasskeyUsed {
        credential_id: passkey.credential_id.clone(),
        counter,
    })
}

// --- OAuth/OIDC and SSO ---------------------------------------------------------------------------------------

fn provider(value: &str) -> Result<String, Rejected> {
    let name_char = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
    let ok = match value.strip_prefix("sso:") {
        Some(id) => !id.is_empty() && id.chars().all(name_char),
        None => {
            (2..=41).contains(&value.len())
                && value.starts_with(|c: char| c.is_ascii_lowercase())
                && value.chars().all(name_char)
        }
    };
    if ok {
        Ok(value.to_owned())
    } else {
        Err(rejected(
            "A provider is a name, or sso:<id>",
            "invalid_provider",
        ))
    }
}

/// The API's: it did the OAuth/OIDC exchange and checked the ID token. A linked login signs in;
/// an unlinked one is linked first only for a tenant's SSO (`auto_link`, which the API sets), the
/// same verified email, and an email in one of the domains the tenant verified for that SSO
/// (`domains`, which the API read): else a tenant's provider could take over any account by
/// answering with its email (`email_not_in_domain`). Otherwise `not_linked`.
#[command("account", aggregate = "account", secret = [refresh_token, ip, user_agent, subject, email])]
pub struct SignInWithProvider {
    pub session_id: String,
    pub provider: String,
    pub subject: String,
    pub email: Option<String>,
    pub email_verified: Option<bool>,
    pub auto_link: Option<bool>,
    /// For an `sso:` provider: the domains its tenant verified.
    pub domains: Option<Vec<String>>,
    pub refresh_token: String,
    pub ip: Option<String>,
    pub user_agent: Option<String>,
}

/// The account's own, through the API (it checked the provider's answer).
#[command("account", aggregate = "account", secret = [subject, email])]
pub struct LinkProvider {
    pub provider: String,
    pub subject: String,
    pub email: Option<String>,
}

#[command("account", aggregate = "account", secret = [subject])]
pub struct UnlinkProvider {
    pub provider: String,
    pub subject: String,
}

/// An issuer URL without its trailing slashes: `https://` and a host, no space characters (the
/// kits' set). Plain `http://` only for `localhost` and `127.0.0.1` (development and tests).
fn issuer(value: &str) -> Result<String, Rejected> {
    let v = if has_space(value) {
        ""
    } else {
        value.trim_end_matches('/')
    };
    let secure = v
        .strip_prefix("https://")
        .is_some_and(|r| !r.is_empty() && !r.starts_with('/'));
    let local = v
        .strip_prefix("http://")
        .and_then(|r| {
            r.strip_prefix("localhost")
                .or_else(|| r.strip_prefix("127.0.0.1"))
        })
        .is_some_and(|r| {
            let r = match r.strip_prefix(':') {
                Some(p) => {
                    let digits = p.bytes().take_while(u8::is_ascii_digit).count();
                    if digits == 0 {
                        return false;
                    }
                    &p[digits..]
                }
                None => r,
            };
            r.is_empty() || r.starts_with('/')
        });
    if secure || local {
        Ok(v.to_owned())
    } else {
        Err(rejected("An https:// issuer URL", "invalid_issuer"))
    }
}

fn sso_domain(value: &str) -> Result<String, Rejected> {
    let d = trim_space(value).to_lowercase();
    let labels: Vec<&str> = d.split('.').collect();
    let label_ok = |l: &&str| {
        !l.is_empty()
            && l.bytes()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
            && !l.starts_with('-')
            && !l.ends_with('-')
            && !l.contains("--")
    };
    let tld_ok = labels
        .last()
        .is_some_and(|t| t.len() >= 2 && t.bytes().all(|c| c.is_ascii_lowercase()));
    if labels.len() >= 2 && labels.iter().all(label_ok) && tld_ok {
        Ok(d)
    } else {
        Err(rejected("A domain name", "invalid_domain"))
    }
}

/// The tenant's owners: an OIDC provider for the tenant's people.
#[command("account", aggregate = "sso", secret = [client_secret])]
pub struct CreateSso {
    pub issuer: String,
    pub client_id: String,
    pub client_secret: String,
}

#[command("account", aggregate = "sso", secret = [client_secret])]
pub struct UpdateSso {
    pub issuer: String,
    pub client_id: String,
    pub client_secret: String,
}

#[command("account", aggregate = "sso")]
pub struct AddSsoDomain {
    pub domain: String,
}

/// The API's: it found the TXT record at `_kernable-sso.<domain>`.
#[command("account", aggregate = "sso")]
pub struct VerifySsoDomain {
    pub domain: String,
    pub found: Vec<String>,
}

#[command("account", aggregate = "sso")]
pub struct RemoveSsoDomain {
    pub domain: String,
}

#[command("account", aggregate = "sso")]
pub struct EnforceSso {
    pub enforced: bool,
}

#[command("account", aggregate = "sso")]
pub struct DisableSso {}

#[command("account", aggregate = "sso")]
pub struct EnableSso {}

/// Erases the client secret.
#[command("account", aggregate = "sso")]
pub struct DeleteSso {}

fn sso_exists(s: &Sso) -> Result<(), Rejected> {
    if matches!(s.status, SsoStatus::Active | SsoStatus::Disabled) {
        Ok(())
    } else {
        Err(rejected("No such SSO", "not_found"))
    }
}

pub fn handle(account: &Aggregate<Account>, session: &Aggregate<Session>, sso: &Aggregate<Sso>) {
    account.command(RegisterAccount, |s, d, _, ctx| {
        let at = ctx.now().millis();
        // A registration whose verification expired unverified is taken over by a new one of the same address.
        let expired = s.status == AccountStatus::Pending
            && !s
                .open_tokens
                .iter()
                .any(|t| t.purpose == TokenPurpose::Verify && t.expires_at > at);
        if s.status != AccountStatus::None && !expired {
            return Err(rejected("The account exists", "exists"));
        }
        let email = normal_email(&d.email);
        if expired && Some(&email) != s.email.as_ref() {
            return Err(rejected(
                "Only the same address takes over a registration",
                "exists",
            ));
        }
        if !valid_email(&email) {
            return Err(rejected("Not an email address", "invalid_email"));
        }
        if trim_space(&d.name).is_empty() || d.name.chars().count() > 200 {
            return Err(rejected("A name is needed", "invalid_name"));
        }
        if d.password.as_deref().is_some_and(|p| !valid_password(p)) {
            return Err(rejected(
                "A password has 10 to 1024 characters",
                "weak_password",
            ));
        }
        let verified = d.verified == Some(true);
        let registered = AccountRegistered {
            email: Some(email.clone()),
            name: Some(trim_space(&d.name).to_owned()),
            password_hash: d.password.as_deref().map(hash_password),
            verified,
            at,
        };
        Ok(if verified {
            vec![registered.into()]
        } else {
            vec![registered.into(), verification_requested(Some(email), at)]
        })
    });

    account.command(RequestVerification, |s, _, _, ctx| {
        if s.status != AccountStatus::Pending {
            return Err(rejected(
                "Only a pending account is verified",
                "invalid_state",
            ));
        }
        Ok(vec![verification_requested(
            s.email.clone(),
            ctx.now().millis(),
        )])
    });

    account.command(VerifyEmail, |s, d, cmd, ctx| {
        Ok(vec![
            EmailVerified {
                token_id: proven(
                    s,
                    TokenPurpose::Verify,
                    &d.token,
                    &cmd.aggregate_id,
                    ctx.now().millis(),
                )?,
            }
            .into(),
        ])
    });

    account.command(SignIn, |s, d, _, ctx| {
        let at = ctx.now().millis();
        if gone(s) {
            return Err(rejected("No such account", "not_found"));
        }
        refresh_ok(&d.refresh_token, &d.session_id)?;
        // The password is checked even while the account is locked, so a locked account answers
        // as slowly as any other.
        let right = check_password(
            s.password.as_ref().and_then(|p| p.hash.as_deref()),
            &d.password,
        );
        if at < s.locked_until() {
            return failed("password", FailureReason::Locked, d.ip, at);
        }
        if !right {
            return failed("password", FailureReason::WrongPassword, d.ip, at);
        }
        match s.status {
            AccountStatus::Pending => {
                return failed("password", FailureReason::NotVerified, d.ip, at);
            }
            AccountStatus::Active => {}
            _ => return failed("password", FailureReason::NotActive, d.ip, at),
        }
        Ok(vec![
            SignedIn {
                session_id: d.session_id,
                method: "password".into(),
                factors: vec!["password".into()],
                refresh_token_hash: sha256(&d.refresh_token),
                ip: d.ip,
                user_agent: d.user_agent,
                mfa: s.mfa(),
                at,
            }
            .into(),
        ])
    });

    session.command(OpenSession, |s, d, _, _| {
        if s.status != SessionStatus::None {
            return Err(rejected("The session exists", "exists"));
        }
        Ok(vec![
            SessionOpened {
                account_id: d.account_id,
                method: d.method,
                factors: d.factors,
                refresh_token_hash: d.refresh_token_hash,
                ip: d.ip,
                user_agent: d.user_agent,
                at: d.at,
            }
            .into(),
        ])
    });

    session.command(RefreshSession, |s, d, cmd, ctx| {
        let at = ctx.now().millis();
        let invalid = || rejected("Not a valid session", "invalid_token");
        let parts = parse_token(&d.refresh_token).filter(|p| p.0 == cmd.aggregate_id);
        let Some((_, generation, _)) = parts.filter(|_| s.status == SessionStatus::Active) else {
            return Err(invalid());
        };
        if !generation.bytes().all(|b| b.is_ascii_digit()) {
            return Err(invalid());
        }
        let hash = sha256(&d.refresh_token);
        if s.previous_token_hashes
            .iter()
            .any(|h| equal_secrets(h, &hash))
        {
            return Ok(vec![
                SessionEnded {
                    reason: SessionEnd::Reuse,
                }
                .into(),
            ]);
        }
        if generation.parse::<u64>().ok() != Some(s.generation)
            || !equal_secrets(&hash, &s.refresh_token_hash)
        {
            return Err(invalid());
        }
        if at > s.last_refresh_at + SESSION_IDLE_DAYS * DAY {
            return Ok(vec![
                SessionEnded {
                    reason: SessionEnd::Idle,
                }
                .into(),
            ]);
        }
        if at > s.opened_at + SESSION_MAX_DAYS * DAY {
            return Ok(vec![
                SessionEnded {
                    reason: SessionEnd::Expired,
                }
                .into(),
            ]);
        }
        let next = parse_token(&d.new_refresh_token);
        if !next.is_some_and(|n| n.0 == cmd.aggregate_id && n.1 == (s.generation + 1).to_string()) {
            return Err(rejected("A malformed refresh token", "invalid_token"));
        }
        Ok(vec![
            SessionRefreshed {
                generation: s.generation + 1,
                refresh_token_hash: sha256(&d.new_refresh_token),
                ip: d.ip,
                account_id: s.account_id.clone(),
                factors: s.factors.clone(),
                at,
            }
            .into(),
        ])
    });

    session.command(AddSessionFactor, |s, d, _, _| {
        if s.status != SessionStatus::Active {
            return Err(rejected("The session has ended", "invalid_state"));
        }
        if d.account_id != s.account_id {
            return Err(rejected("Another account's session", "invalid_session"));
        }
        Ok(if s.factors.contains(&d.factor) {
            vec![]
        } else {
            vec![SessionFactorAdded { factor: d.factor }.into()]
        })
    });

    session.command(EndSession, |s, d, _, _| {
        if s.status != SessionStatus::Active {
            return Err(rejected("The session has ended", "invalid_state"));
        }
        Ok(vec![
            SessionEnded {
                reason: d.reason.unwrap_or(SessionEnd::SignedOut),
            }
            .into(),
        ])
    });

    account.command(SuspendAccount, |s, d, _, ctx| {
        if !matches!(s.status, AccountStatus::Pending | AccountStatus::Active) {
            return Err(rejected("Cannot suspend this account", "invalid_state"));
        }
        Ok(vec![
            AccountSuspended {
                reason: d.reason,
                at: ctx.now().millis(),
            }
            .into(),
        ])
    });

    account.command(ReactivateAccount, |s, _, _, _| {
        if s.status != AccountStatus::Suspended {
            return Err(rejected(
                "Only a suspended account is reactivated",
                "invalid_state",
            ));
        }
        Ok(vec![AccountReactivated {}.into()])
    });

    account.command(DeleteAccount, |s, _, _, _| {
        if s.status != AccountStatus::Suspended {
            return Err(rejected(
                "Only a suspended account is deleted",
                "invalid_state",
            ));
        }
        Ok(vec![AccountDeleted {}.into()])
    });

    account.command(ChangePassword, |s, d, _, ctx| {
        active(s)?;
        if let Some(password) = &s.password
            && !check_password(
                password.hash.as_deref(),
                d.current.as_deref().unwrap_or_default(),
            )
        {
            return Err(rejected("The current password is wrong", "wrong_password"));
        }
        if !valid_password(&d.new) {
            return Err(rejected(
                "A password has 10 to 1024 characters",
                "weak_password",
            ));
        }
        Ok(vec![
            PasswordChanged {
                hash: Some(hash_password(&d.new)),
                keep_session_id: d.keep_session_id,
                at: ctx.now().millis(),
            }
            .into(),
        ])
    });

    account.command(RequestPasswordReset, |s, _, _, ctx| {
        active(s)?;
        let now = ctx.now().millis();
        // An open token was requested RESET_MINUTES before it expires.
        if s.open_tokens.iter().any(|t| {
            t.purpose == TokenPurpose::Reset
                && now < t.expires_at - (RESET_MINUTES - MAIL_COOLDOWN_MINUTES) * MINUTE
        }) {
            return Ok(vec![]);
        }
        Ok(vec![
            PasswordResetRequested {
                token_id: random_secret(9),
                token: Some(random_secret(32)),
                email: s.email.clone(),
                expires_at: now + RESET_MINUTES * MINUTE,
            }
            .into(),
        ])
    });

    account.command(ResetPassword, |s, d, cmd, ctx| {
        let token_id = proven(
            s,
            TokenPurpose::Reset,
            &d.token,
            &cmd.aggregate_id,
            ctx.now().millis(),
        )?;
        if !valid_password(&d.new) {
            return Err(rejected(
                "A password has 10 to 1024 characters",
                "weak_password",
            ));
        }
        Ok(vec![
            PasswordReset {
                token_id,
                hash: Some(hash_password(&d.new)),
                at: ctx.now().millis(),
            }
            .into(),
        ])
    });

    account.command(RequestEmailChange, |s, d, _, ctx| {
        active(s)?;
        let email = normal_email(&d.email);
        if !valid_email(&email) {
            return Err(rejected("Not an email address", "invalid_email"));
        }
        if Some(&email) == s.email.as_ref() {
            return Err(rejected("That is the address already", "unchanged"));
        }
        Ok(vec![
            EmailChangeRequested {
                token_id: random_secret(9),
                token: Some(random_secret(32)),
                email: Some(email),
                expires_at: ctx.now().millis() + VERIFICATION_HOURS * HOUR,
            }
            .into(),
        ])
    });

    account.command(ConfirmEmailChange, |s, d, cmd, ctx| {
        let token_id = proven(
            s,
            TokenPurpose::EmailChange,
            &d.token,
            &cmd.aggregate_id,
            ctx.now().millis(),
        )?;
        Ok(vec![
            EmailChanged {
                token_id,
                email: s.pending_email.clone(),
            }
            .into(),
        ])
    });

    account.command(NoteRegistrationAttempt, |s, _, _, ctx| {
        if !matches!(s.status, AccountStatus::Active | AccountStatus::Suspended) {
            return Err(rejected("No account to tell", "invalid_state"));
        }
        let now = ctx.now().millis();
        if s.attempt_noted_at != 0 && now < s.attempt_noted_at + MAIL_COOLDOWN_MINUTES * MINUTE {
            return Ok(vec![]);
        }
        Ok(vec![
            RegistrationAttempted {
                email: s.email.clone(),
                at: now,
            }
            .into(),
        ])
    });

    account.command(StartTotp, |s, d, _, _| {
        active(s)?;
        if s.mfa() {
            return Err(rejected("TOTP is on already", "exists"));
        }
        let base32 = (16..=64).contains(&d.secret.len())
            && d.secret
                .bytes()
                .all(|c| c.is_ascii_uppercase() || (b'2'..=b'7').contains(&c));
        if !base32 {
            return Err(rejected("A base32 secret", "invalid_secret"));
        }
        Ok(vec![
            TotpStarted {
                secret: Some(d.secret),
            }
            .into(),
        ])
    });

    account.command(ConfirmTotp, |s, d, _, ctx| {
        let Some(secret) = s
            .totp
            .as_ref()
            .filter(|t| !t.confirmed)
            .and_then(|t| t.secret.as_deref())
        else {
            return Err(rejected("Start TOTP first", "invalid_state"));
        };
        let now = ctx.now().millis();
        let step = totp_step(secret, &d.code, now)
            .ok_or_else(|| rejected("The code is not right", "wrong_code"))?;
        Ok(vec![
            TotpConfirmed { step, at: now }.into(),
            RecoveryCodesGenerated {
                hashes: recovery_hashes(&d.recovery_codes)?,
            }
            .into(),
        ])
    });

    account.command(DisableTotp, |s, d, _, ctx| {
        second_factor(s, &d.code, ctx.now().millis())
            .ok_or_else(|| rejected("The code is not right", "wrong_code"))?;
        Ok(vec![TotpDisabled {}.into()])
    });

    account.command(RegenerateRecoveryCodes, |s, d, _, ctx| {
        second_factor(s, &d.code, ctx.now().millis())
            .ok_or_else(|| rejected("The code is not right", "wrong_code"))?;
        Ok(vec![
            RecoveryCodesGenerated {
                hashes: recovery_hashes(&d.recovery_codes)?,
            }
            .into(),
        ])
    });

    account.command(ProveSecondFactor, |s, d, _, ctx| {
        let now = ctx.now().millis();
        if s.status != AccountStatus::Active || !s.mfa() {
            return Err(rejected("No second factor to prove", "invalid_state"));
        }
        let proof = if now < s.locked_until() {
            None
        } else {
            second_factor(s, &d.code, now)
        };
        Ok(vec![match proof {
            None => SecondFactorFailed {
                session_id: d.session_id,
                at: now,
            }
            .into(),
            Some(p) => SecondFactorProved {
                session_id: d.session_id,
                method: p.method,
                step: p.step,
                recovery_code_hash: p.recovery_code_hash,
            }
            .into(),
        }])
    });

    account.command(AddPasskey, |s, d, _, ctx| {
        active(s)?;
        let registered = passkeys::verify_registration(&d.response, &d.challenge)
            .map_err(|e| rejected(&format!("Not a valid passkey: {e}"), "invalid_passkey"))?;
        if s.passkeys
            .iter()
            .any(|p| p.credential_id.as_deref() == Some(&registered.credential_id))
        {
            return Err(rejected("The passkey is added already", "exists"));
        }
        Ok(vec![
            PasskeyAdded {
                credential_id: Some(registered.credential_id),
                public_key: registered.public_key,
                counter: registered.counter,
                label: d.label,
                at: ctx.now().millis(),
            }
            .into(),
        ])
    });

    account.command(RemovePasskey, |s, d, _, _| {
        if !s
            .passkeys
            .iter()
            .any(|p| p.credential_id.as_deref() == Some(&d.credential_id))
        {
            return Err(rejected("No such passkey", "not_found"));
        }
        if !another_method(s, Some(&d.credential_id), None) {
            return Err(rejected("The last way to sign in stays", "last_method"));
        }
        Ok(vec![
            PasskeyRemoved {
                credential_id: Some(d.credential_id),
            }
            .into(),
        ])
    });

    account.command(SignInWithPasskey, |s, d, _, ctx| {
        let at = ctx.now().millis();
        if gone(s) {
            return Err(rejected("No such account", "not_found"));
        }
        refresh_ok(&d.refresh_token, &d.session_id)?;
        if at < s.locked_until() {
            return failed("passkey", FailureReason::Locked, d.ip, at);
        }
        let Some(used) = asserted(s, &d.challenge, &d.response) else {
            return failed("passkey", FailureReason::WrongPassword, d.ip, at);
        };
        if s.status != AccountStatus::Active {
            return failed("passkey", FailureReason::NotActive, d.ip, at);
        }
        Ok(vec![
            used.into(),
            SignedIn {
                session_id: d.session_id,
                method: "passkey".into(),
                factors: vec!["passkey".into()],
                refresh_token_hash: sha256(&d.refresh_token),
                ip: d.ip,
                user_agent: d.user_agent,
                mfa: false,
                at,
            }
            .into(),
        ])
    });

    account.command(ProvePasskey, |s, d, _, ctx| {
        active(s)?;
        Ok(match asserted(s, &d.challenge, &d.response) {
            None => vec![
                SecondFactorFailed {
                    session_id: d.session_id,
                    at: ctx.now().millis(),
                }
                .into(),
            ],
            Some(used) => vec![
                used.into(),
                SecondFactorProved {
                    session_id: d.session_id,
                    method: SecondFactor::Passkey,
                    step: None,
                    recovery_code_hash: None,
                }
                .into(),
            ],
        })
    });

    account.command(SignInWithProvider, |s, d, _, ctx| {
        let at = ctx.now().millis();
        let p = provider(&d.provider)?;
        if gone(s) {
            return Err(rejected("No such account", "not_found"));
        }
        refresh_ok(&d.refresh_token, &d.session_id)?;
        if d.subject.is_empty() {
            return Err(rejected("Which subject?", "invalid_subject"));
        }
        if s.status != AccountStatus::Active {
            return failed(&p, FailureReason::NotActive, d.ip, at);
        }
        let email = normal_email(d.email.as_deref().unwrap_or_default());
        let sso = p.starts_with("sso:");
        let linked = s
            .links
            .iter()
            .any(|x| x.provider == p && x.subject.as_deref() == Some(&d.subject));
        let auto = !linked
            && sso
            && d.auto_link == Some(true)
            && d.email_verified == Some(true)
            && s.email.as_deref() == Some(email.as_str());
        let domain = email_domain(&email);
        if auto
            && !d
                .domains
                .iter()
                .flatten()
                .any(|x| x.to_lowercase() == domain)
        {
            return Err(rejected(
                "The email is not in a domain of this single sign-on",
                "email_not_in_domain",
            ));
        }
        if !linked && !auto {
            return failed(&p, FailureReason::NotLinked, d.ip, at);
        }
        let signed = SignedIn {
            session_id: d.session_id,
            factors: vec![if sso { "sso" } else { "provider" }.into()],
            method: p.clone(),
            refresh_token_hash: sha256(&d.refresh_token),
            ip: d.ip,
            user_agent: d.user_agent,
            mfa: s.mfa(),
            at,
        };
        Ok(if auto {
            vec![
                ProviderLinked {
                    provider: p,
                    subject: Some(d.subject),
                    email: Some(email),
                    at,
                }
                .into(),
                signed.into(),
            ]
        } else {
            vec![signed.into()]
        })
    });

    account.command(LinkProvider, |s, d, _, ctx| {
        active(s)?;
        let p = provider(&d.provider)?;
        if d.subject.is_empty() {
            return Err(rejected("Which subject?", "invalid_subject"));
        }
        if s.links
            .iter()
            .any(|x| x.provider == p && x.subject.as_deref() == Some(&d.subject))
        {
            return Err(rejected("Linked already", "exists"));
        }
        let email = d.email.filter(|e| !e.is_empty()).map(|e| normal_email(&e));
        Ok(vec![
            ProviderLinked {
                provider: p,
                subject: Some(d.subject),
                email,
                at: ctx.now().millis(),
            }
            .into(),
        ])
    });

    account.command(UnlinkProvider, |s, d, _, _| {
        if !s
            .links
            .iter()
            .any(|x| x.provider == d.provider && x.subject.as_deref() == Some(&d.subject))
        {
            return Err(rejected("Not linked", "not_found"));
        }
        if !another_method(s, None, Some((&d.provider, &d.subject))) {
            return Err(rejected("The last way to sign in stays", "last_method"));
        }
        Ok(vec![
            ProviderUnlinked {
                provider: d.provider,
                subject: Some(d.subject),
            }
            .into(),
        ])
    });

    sso.command(CreateSso, |s, d, _, _| {
        if s.status != SsoStatus::None {
            return Err(rejected("The SSO exists", "exists"));
        }
        if d.client_id.is_empty() || d.client_secret.is_empty() {
            return Err(rejected("A client ID and secret", "invalid_client"));
        }
        Ok(vec![
            SsoCreated {
                issuer: issuer(&d.issuer)?,
                client_id: d.client_id,
                client_secret: Some(d.client_secret),
            }
            .into(),
        ])
    });

    sso.command(UpdateSso, |s, d, _, _| {
        sso_exists(s)?;
        Ok(vec![
            SsoUpdated {
                issuer: issuer(&d.issuer)?,
                client_id: d.client_id,
                client_secret: Some(d.client_secret),
            }
            .into(),
        ])
    });

    sso.command(AddSsoDomain, |s, d, _, _| {
        sso_exists(s)?;
        let domain = sso_domain(&d.domain)?;
        if s.domains.iter().any(|x| x.domain == domain) {
            return Err(rejected("Added already", "exists"));
        }
        Ok(vec![
            SsoDomainAdded {
                domain,
                txt: format!("kernable-sso={}", random_secret(18)),
            }
            .into(),
        ])
    });

    sso.command(VerifySsoDomain, |s, d, _, _| {
        let x = s
            .domains
            .iter()
            .find(|y| y.domain == d.domain)
            .ok_or_else(|| rejected("No such domain", "not_found"))?;
        if x.verified {
            return Ok(vec![]);
        }
        if !d.found.contains(&x.txt) {
            return Err(rejected("The TXT record is not there", "not_verified"));
        }
        Ok(vec![
            SsoDomainVerified {
                domain: x.domain.clone(),
            }
            .into(),
        ])
    });

    sso.command(RemoveSsoDomain, |s, d, _, _| {
        if !s.domains.iter().any(|y| y.domain == d.domain) {
            return Err(rejected("No such domain", "not_found"));
        }
        Ok(vec![SsoDomainRemoved { domain: d.domain }.into()])
    });

    sso.command(EnforceSso, |s, d, _, _| {
        if s.status != SsoStatus::Active {
            return Err(rejected("Only an active SSO is enforced", "invalid_state"));
        }
        Ok(vec![
            SsoEnforcementChanged {
                enforced: d.enforced,
            }
            .into(),
        ])
    });

    sso.command(DisableSso, |s, _, _, _| {
        if s.status != SsoStatus::Active {
            return Err(rejected("Only an active SSO is disabled", "invalid_state"));
        }
        let mut events: Vec<NewEvent> = vec![];
        if s.enforced {
            events.push(SsoEnforcementChanged { enforced: false }.into());
        }
        events.push(SsoDisabled {}.into());
        Ok(events)
    });

    sso.command(EnableSso, |s, _, _, _| {
        if s.status != SsoStatus::Disabled {
            return Err(rejected("Only a disabled SSO is enabled", "invalid_state"));
        }
        Ok(vec![SsoEnabled {}.into()])
    });

    sso.command(DeleteSso, |s, _, _, _| {
        if matches!(s.status, SsoStatus::None | SsoStatus::Deleted) {
            return Err(rejected("No such SSO", "not_found"));
        }
        Ok(vec![SsoDeleted {}.into()])
    });
}