allowthem-core 0.0.9

Core types, database, and auth logic for allowthem
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
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
use std::sync::Arc;

use chrono::{DateTime, Duration, Utc};
use sqlx::SqlitePool;

use crate::db::Db;
use crate::email::{EmailMessage, EmailSender, EmailTemplate, NoopEmailSender, fallback_username};
use crate::error::AuthError;
use crate::event_sink::{AuthEvent, EventSink, NoopEventSink};
use crate::sessions::{self, SessionConfig};
use crate::types::{Email, SessionToken, User, UserId};

/// Callback type for active authentication events.
///
/// Invoked after every active auth event (successful login, OAuth callback
/// completion, MFA/TOTP completion, OIDC access token issuance). Passive
/// events (session validation, token refresh) do **not** fire this.
///
/// The callback must not block. Use a channel-send if heavy work is needed.
/// Panics are caught and logged; they never propagate to the caller.
pub type OnUserActive = Arc<dyn Fn(UserId, DateTime<Utc>) + Send + Sync>;

/// Outcome of a successful login or session creation.
pub struct LoginOutcome {
    pub user: User,
    pub token: SessionToken,
    /// Value for the `Set-Cookie` response header.
    pub set_cookie: String,
}

/// Error type for builder construction and validation failures.
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    /// Database connection or migration failure.
    #[error("database error: {0}")]
    Database(#[from] AuthError),

    /// Invalid builder configuration.
    /// Reserved for future validation; not currently produced.
    #[error("invalid configuration: {0}")]
    InvalidConfig(&'static str),
}

enum PoolSource {
    Url(String),
    Pool(SqlitePool),
}

/// Builder for constructing a configured [`AllowThem`] handle.
pub struct AllowThemBuilder {
    pool_source: PoolSource,
    session_ttl: Option<Duration>,
    cookie_name: Option<&'static str>,
    cookie_secure: Option<bool>,
    cookie_domain: String,
    mfa_key: Option<[u8; 32]>,
    signing_key: Option<[u8; 32]>,
    csrf_key: Option<[u8; 32]>,
    base_url: Option<String>,
    on_user_active: Option<OnUserActive>,
    email_sender: Option<Box<dyn EmailSender>>,
    event_sink: Option<Box<dyn EventSink>>,
}

impl AllowThemBuilder {
    /// Start building from a database URL.
    ///
    /// At build time, calls `Db::connect(url)` which creates the pool,
    /// sets pragmas (foreign_keys, WAL, busy_timeout), and runs migrations.
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            pool_source: PoolSource::Url(url.into()),
            session_ttl: None,
            cookie_name: None,
            cookie_secure: None,
            cookie_domain: String::new(),
            mfa_key: None,
            signing_key: None,
            csrf_key: None,
            base_url: None,
            on_user_active: None,
            email_sender: None,
            event_sink: None,
        }
    }

    /// Start building from an existing pool.
    ///
    /// At build time, calls `Db::new(pool)` which runs migrations.
    /// The caller is responsible for pragma configuration on their pool.
    pub fn with_pool(pool: SqlitePool) -> Self {
        Self {
            pool_source: PoolSource::Pool(pool),
            session_ttl: None,
            cookie_name: None,
            cookie_secure: None,
            cookie_domain: String::new(),
            mfa_key: None,
            signing_key: None,
            csrf_key: None,
            base_url: None,
            on_user_active: None,
            email_sender: None,
            event_sink: None,
        }
    }

    /// Override session TTL. Default: 24 hours.
    pub fn session_ttl(mut self, ttl: Duration) -> Self {
        self.session_ttl = Some(ttl);
        self
    }

    /// Override session cookie name. Default: `"allowthem_session"`.
    pub fn cookie_name(mut self, name: &'static str) -> Self {
        self.cookie_name = Some(name);
        self
    }

    /// Set the Secure attribute on session cookies.
    ///
    /// Default: `true`. Set to `false` for local development over HTTP.
    pub fn cookie_secure(mut self, secure: bool) -> Self {
        self.cookie_secure = Some(secure);
        self
    }

    /// Set the Domain attribute on session cookies.
    ///
    /// Default: empty (omitted). When set, the cookie is sent to the domain
    /// and all its subdomains.
    pub fn cookie_domain(mut self, domain: impl Into<String>) -> Self {
        self.cookie_domain = domain.into();
        self
    }

    /// Set the AES-256-GCM encryption key for MFA secrets.
    ///
    /// When not set, all MFA operations return `AuthError::MfaNotConfigured`.
    /// This keeps MFA opt-in for embedded integrators who don't need it.
    pub fn mfa_key(mut self, key: [u8; 32]) -> Self {
        self.mfa_key = Some(key);
        self
    }

    /// Set the AES-256-GCM encryption key for RS256 signing key storage.
    ///
    /// Required for OIDC/standalone mode. When not set, all signing key
    /// operations return `AuthError::SigningKeyNotConfigured`.
    pub fn signing_key(mut self, key: [u8; 32]) -> Self {
        self.signing_key = Some(key);
        self
    }

    /// Set the base URL (issuer) for the OIDC provider.
    ///
    /// Required for standalone mode. Used as the `iss` claim in tokens
    /// and for issuer validation on incoming access tokens.
    /// When not set, OIDC operations return `AuthError::BaseUrlNotConfigured`.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set the HMAC key for session-bound CSRF token derivation.
    ///
    /// Required for `csrf_middleware` in `crates/server`. If not set,
    /// `csrf_middleware` returns 500. Use 32 random bytes distinct from
    /// `mfa_key` and `signing_key`.
    pub fn csrf_key(mut self, key: [u8; 32]) -> Self {
        self.csrf_key = Some(key);
        self
    }

    /// Register a callback invoked after every active authentication event.
    ///
    /// "Active" means: successful password login, OAuth callback completion,
    /// MFA/TOTP completion, and OIDC access token issuance (authorization code
    /// exchange). Session validation, token refresh, and API token checks do
    /// **not** fire the callback.
    ///
    /// The callback must not block. Use a channel-send if heavy work is needed.
    /// Panics inside the callback are caught, logged via `tracing::error!`, and
    /// never propagated to the caller.
    ///
    /// Primarily used by the SaaS binary to record MAU into the control plane.
    pub fn on_user_active(mut self, callback: OnUserActive) -> Self {
        self.on_user_active = Some(callback);
        self
    }

    /// Register the email sender used by every email-bearing flow
    /// (password reset, email verification, invitations, MFA recovery).
    ///
    /// Default is [`NoopEmailSender`], which silently drops messages — call
    /// this method for any production deployment. A `tracing::warn!` is
    /// emitted at build time if the default is left in place.
    ///
    /// Email flows that compose URLs (`send_password_reset_email`,
    /// `send_verification_email`) also require [`base_url`] to be set.
    ///
    /// [`base_url`]: AllowThemBuilder::base_url
    pub fn email_sender(mut self, sender: Box<dyn EmailSender>) -> Self {
        self.email_sender = Some(sender);
        self
    }

    /// Register the event sink that fires for every state-changing auth
    /// operation.
    ///
    /// Default is [`NoopEventSink`] (silent). The SaaS binary will register a
    /// sink that writes rows to `webhook_deliveries` for outbound HTTP delivery
    /// (epic 7xw.2). Embedded integrators that do not need webhook delivery can
    /// leave this unset.
    pub fn event_sink(mut self, sink: Box<dyn EventSink>) -> Self {
        self.event_sink = Some(sink);
        self
    }

    /// Construct the [`AllowThem`] handle.
    ///
    /// Connects to (or wraps) the database, runs migrations, and assembles
    /// the session configuration from overrides plus defaults.
    pub async fn build(self) -> Result<AllowThem, BuildError> {
        let db = match self.pool_source {
            PoolSource::Url(url) => Db::connect(&url).await?,
            PoolSource::Pool(pool) => Db::new(pool).await?,
        };

        let defaults = SessionConfig::default();
        let session_config = SessionConfig {
            ttl: self.session_ttl.unwrap_or(defaults.ttl),
            cookie_name: self.cookie_name.unwrap_or(defaults.cookie_name),
            secure: self.cookie_secure.unwrap_or(defaults.secure),
        };

        let email_sender = self.email_sender.unwrap_or_else(|| {
            tracing::warn!(
                "no email_sender configured; defaulting to NoopEmailSender — \
                 outgoing emails (password reset, verification, invitation, \
                 MFA recovery) will be silently dropped",
            );
            Box::new(NoopEmailSender)
        });

        let event_sink = self.event_sink.unwrap_or_else(|| Box::new(NoopEventSink));

        Ok(AllowThem {
            inner: Arc::new(Inner {
                db,
                session_config,
                cookie_domain: self.cookie_domain,
                mfa_key: self.mfa_key,
                signing_key: self.signing_key,
                csrf_key: self.csrf_key,
                base_url: self.base_url,
                on_user_active: self.on_user_active,
                email_sender,
                event_sink,
            }),
        })
    }
}

struct Inner {
    db: Db,
    session_config: SessionConfig,
    cookie_domain: String,
    mfa_key: Option<[u8; 32]>,
    signing_key: Option<[u8; 32]>,
    csrf_key: Option<[u8; 32]>,
    base_url: Option<String>,
    on_user_active: Option<OnUserActive>,
    email_sender: Box<dyn EmailSender>,
    event_sink: Box<dyn EventSink>,
}

/// Configured allowthem handle.
///
/// Bundles a `Db`, `SessionConfig`, and cookie domain into a single value
/// that is cheaply cloneable and safe to share across Axum handlers via
/// `State<AllowThem>` or `Extension<AllowThem>`.
#[derive(Clone)]
pub struct AllowThem {
    inner: Arc<Inner>,
}

impl AllowThem {
    /// Access the underlying database handle.
    ///
    /// Escape hatch for callers who need direct `Db` access for operations
    /// not yet wrapped by `AllowThem` methods (e.g., user CRUD, role management).
    pub fn db(&self) -> &Db {
        &self.inner.db
    }

    /// Access the session configuration.
    pub fn session_config(&self) -> &SessionConfig {
        &self.inner.session_config
    }

    /// Build a `Set-Cookie` header value for the given session token.
    ///
    /// Uses the stored `SessionConfig` and cookie domain. Delegates to
    /// `sessions::session_cookie()`.
    pub fn session_cookie(&self, token: &SessionToken) -> String {
        sessions::session_cookie(token, &self.inner.session_config, &self.inner.cookie_domain)
    }

    /// Returns the MFA encryption key, or `Err(MfaNotConfigured)` if not set.
    pub(crate) fn mfa_key(&self) -> Result<&[u8; 32], AuthError> {
        self.inner
            .mfa_key
            .as_ref()
            .ok_or(AuthError::MfaNotConfigured)
    }

    /// Returns the signing key encryption key, or `Err(SigningKeyNotConfigured)` if not set.
    pub(crate) fn signing_key(&self) -> Result<&[u8; 32], AuthError> {
        self.inner
            .signing_key
            .as_ref()
            .ok_or(AuthError::SigningKeyNotConfigured)
    }

    /// Returns the base URL (issuer), or `Err(BaseUrlNotConfigured)` if not set.
    pub fn base_url(&self) -> Result<&str, AuthError> {
        self.inner
            .base_url
            .as_deref()
            .ok_or(AuthError::BaseUrlNotConfigured)
    }

    pub fn csrf_key(&self) -> Result<&[u8; 32], AuthError> {
        self.inner
            .csrf_key
            .as_ref()
            .ok_or(AuthError::CsrfKeyNotConfigured)
    }

    /// Return a reference to the `on_user_active` callback, if configured.
    ///
    /// Used to pass the callback into free functions (e.g.
    /// `exchange_authorization_code`) that do not receive the full `AllowThem`
    /// handle.
    pub fn on_user_active(&self) -> Option<&OnUserActive> {
        self.inner.on_user_active.as_ref()
    }

    /// Borrow the configured email sender.
    ///
    /// Defaults to [`NoopEmailSender`] unless overridden via
    /// [`AllowThemBuilder::email_sender`].
    pub fn email_sender(&self) -> &dyn EmailSender {
        &*self.inner.email_sender
    }

    /// Borrow the configured event sink.
    ///
    /// Defaults to [`NoopEventSink`] unless overridden via
    /// [`AllowThemBuilder::event_sink`].
    pub fn event_sink(&self) -> &dyn EventSink {
        &*self.inner.event_sink
    }

    /// Emit an event to the configured sink.
    ///
    /// Awaits the sink's `emit` future. Returns when the sink finishes
    /// (typically a single local DB write or a noop). The sink contract
    /// forbids panics and errors; this method is unconditionally infallible.
    pub async fn emit_event(&self, event: AuthEvent) {
        self.event_sink().emit(&event).await;
    }

    // -------------------------------------------------------------------------
    // Email-sending helpers
    // -------------------------------------------------------------------------

    /// Send a password reset email to the given address.
    ///
    /// Creates a reset token, composes the reset URL from [`base_url`], and
    /// sends a `PasswordReset` template. Returns `Ok(())` silently if no user
    /// exists for that email (enumeration prevention). Requires [`base_url`] to
    /// be configured; returns `Err(BaseUrlNotConfigured)` otherwise.
    ///
    /// [`base_url`]: AllowThemBuilder::base_url
    pub async fn send_password_reset_email(&self, email: &Email) -> Result<(), AuthError> {
        let raw_token = match self.db().create_password_reset(email).await? {
            None => return Ok(()),
            Some(t) => t,
        };

        let username = match self.db().get_user_by_email(email).await {
            Ok(user) => fallback_username(&user),
            Err(_) => email
                .as_str()
                .split('@')
                .next()
                .unwrap_or("there")
                .to_owned(),
        };

        let reset_url = format!(
            "{}/auth/reset-password?token={}",
            self.base_url()?,
            raw_token
        );
        let message = EmailMessage {
            to: email.as_str().to_owned(),
            subject: "Reset your password".to_owned(),
            template: EmailTemplate::PasswordReset {
                url: reset_url,
                username,
            },
        };

        self.email_sender()
            .send(&message)
            .await
            .map_err(|e| AuthError::Email(e.to_string()))
    }

    /// Send an email verification link to the given user.
    ///
    /// Creates a verification token, composes the verification URL from
    /// [`base_url`], and sends an `EmailVerification` template. Requires
    /// [`base_url`] to be configured.
    ///
    /// [`base_url`]: AllowThemBuilder::base_url
    pub async fn send_verification_email(
        &self,
        user_id: UserId,
        email: &Email,
    ) -> Result<(), AuthError> {
        let raw_token = self.db().create_email_verification(user_id).await?;

        let username = match self.db().get_user(user_id).await {
            Ok(user) => fallback_username(&user),
            Err(_) => email
                .as_str()
                .split('@')
                .next()
                .unwrap_or("there")
                .to_owned(),
        };

        let verify_url = format!("{}/auth/verify-email?token={}", self.base_url()?, raw_token);
        let message = EmailMessage {
            to: email.as_str().to_owned(),
            subject: "Verify your email address".to_owned(),
            template: EmailTemplate::EmailVerification {
                url: verify_url,
                username,
            },
        };

        self.email_sender()
            .send(&message)
            .await
            .map_err(|e| AuthError::Email(e.to_string()))
    }

    /// Send an invitation email to the given address.
    ///
    /// Creates an invitation token in the database and sends an `Invitation`
    /// template. `invitation_url` must be pre-composed by the caller — the
    /// URL format varies by deployment (the saas binary uses
    /// `https://{base_domain}/invite/{token}`; standalone server may differ).
    /// `invited_by` is the `UserId` of the inviter; their display name is
    /// resolved from the database and used in the template. On lookup failure,
    /// falls back to `"your team"`.
    pub async fn send_invitation_email(
        &self,
        email: &Email,
        invitation_url: &str,
        invited_by: UserId,
        expires_at: chrono::DateTime<chrono::Utc>,
    ) -> Result<(), AuthError> {
        self.db()
            .create_invitation(Some(email), None, Some(invited_by), expires_at)
            .await?;

        let inviter_name = match self.db().get_user(invited_by).await {
            Ok(user) => fallback_username(&user),
            Err(_) => "your team".to_owned(),
        };

        let message = EmailMessage {
            to: email.as_str().to_owned(),
            subject: format!("You've been invited by {inviter_name}"),
            template: EmailTemplate::Invitation {
                url: invitation_url.to_owned(),
                invited_by: inviter_name,
            },
        };

        self.email_sender()
            .send(&message)
            .await
            .map_err(|e| AuthError::Email(e.to_string()))
    }

    /// Send MFA recovery codes to the given user via email.
    ///
    /// Looks up the user by `user_id` to determine recipient address and
    /// username. Sends an `MfaRecovery` template with the supplied codes. Does
    /// **not** write to the database — code generation and persistence are the
    /// caller's responsibility (see `Db::enable_mfa`).
    pub async fn send_mfa_recovery_email(
        &self,
        user_id: UserId,
        codes: Vec<String>,
    ) -> Result<(), AuthError> {
        let user = self.db().get_user(user_id).await?;
        let username = fallback_username(&user);

        let message = EmailMessage {
            to: user.email.as_str().to_owned(),
            subject: "Your MFA recovery codes".to_owned(),
            template: EmailTemplate::MfaRecovery { codes, username },
        };

        self.email_sender()
            .send(&message)
            .await
            .map_err(|e| AuthError::Email(e.to_string()))
    }

    /// Fire the `on_user_active` callback, if configured.
    ///
    /// Call this immediately after a session row or access token is durably
    /// written, for active auth events only. Panics from the callback are
    /// caught and logged; they never propagate to the caller.
    pub fn notify_user_active(&self, user_id: UserId) {
        let Some(cb) = self.inner.on_user_active.as_ref() else {
            return;
        };
        let now = Utc::now();
        let cb = cb.clone();
        if let Err(_payload) =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || cb(user_id, now)))
        {
            tracing::error!(user_id = %user_id, "on_user_active callback panicked");
        }
    }

    /// Fetch the active signing key and decrypt its private key PEM.
    ///
    /// Combines the encryption key, active key lookup, and decryption into
    /// a single call. Keeps the raw encryption key private to the core crate.
    pub async fn get_decrypted_signing_key(
        &self,
    ) -> Result<(crate::signing_keys::SigningKey, String), AuthError> {
        let enc_key = self.signing_key()?;
        let key = self.db().get_active_signing_key().await?;
        let pem = crate::signing_keys::decrypt_private_key(&key, enc_key)?;
        Ok((key, pem))
    }

    /// Build a `Set-Cookie` header value that expires the session cookie.
    ///
    /// Returns `Max-Age=0` with the same cookie name, path, domain, and flags
    /// used by `session_cookie()`. Pass this as the `Set-Cookie` header on a
    /// logout response to clear the browser's stored session cookie.
    pub fn clear_session_cookie(&self) -> String {
        sessions::clear_session_cookie(&self.inner.session_config, &self.inner.cookie_domain)
    }

    /// Extract the session token from a `Cookie` header value.
    ///
    /// Uses the stored cookie name. Delegates to `sessions::parse_session_cookie()`.
    pub fn parse_session_cookie(&self, cookie_header: &str) -> Option<SessionToken> {
        sessions::parse_session_cookie(cookie_header, self.inner.session_config.cookie_name)
    }

    /// Authenticate with credentials and create a session.
    ///
    /// Returns `Err(AuthError::InvalidCredentials)` for any credential failure —
    /// unknown identifier, wrong password, no local password hash (SSO-only
    /// account), or inactive user — to prevent account enumeration.
    ///
    /// Records an `AuditEvent::Login` on success. IP and user-agent are not
    /// available at this layer; callers who need them in the audit log should
    /// use the low-level `Db` methods directly.
    pub async fn login(&self, identifier: &str, password: &str) -> Result<LoginOutcome, AuthError> {
        use crate::audit::AuditEvent;
        use crate::password::verify_password;

        let user = self
            .db()
            .find_for_login(identifier)
            .await
            .map_err(|e| match e {
                AuthError::NotFound => AuthError::InvalidCredentials,
                other => other,
            })?;

        if !user.is_active {
            return Err(AuthError::InvalidCredentials);
        }

        let hash = user
            .password_hash
            .as_ref()
            .ok_or(AuthError::InvalidCredentials)?;

        if !verify_password(password, hash)? {
            return Err(AuthError::InvalidCredentials);
        }

        let token = sessions::generate_token();
        let token_hash = sessions::hash_token(&token);
        let expires_at = Utc::now() + self.inner.session_config.ttl;
        self.db()
            .create_session(user.id, token_hash, None, None, expires_at)
            .await?;

        let _ = self
            .db()
            .log_audit(AuditEvent::Login, Some(&user.id), None, None, None, None)
            .await;

        self.notify_user_active(user.id);
        self.emit_event(AuthEvent::new(
            "session.created",
            Some(user.id),
            serde_json::json!({ "user_id": user.id }),
        ))
        .await;

        let set_cookie = self.session_cookie(&token);
        Ok(LoginOutcome {
            user,
            token,
            set_cookie,
        })
    }

    /// Create a session for an already-authenticated user.
    ///
    /// Does not verify credentials. Intended for use after OAuth, TOTP, or
    /// other non-password authentication flows. The calling flow is responsible
    /// for audit logging.
    pub async fn create_session_cookie(&self, user_id: UserId) -> Result<LoginOutcome, AuthError> {
        let user = self.db().get_user(user_id).await?;
        let token = sessions::generate_token();
        let token_hash = sessions::hash_token(&token);
        let expires_at = Utc::now() + self.inner.session_config.ttl;
        self.db()
            .create_session(user_id, token_hash, None, None, expires_at)
            .await?;

        self.notify_user_active(user_id);
        self.emit_event(AuthEvent::new(
            "session.created",
            Some(user_id),
            serde_json::json!({ "user_id": user_id }),
        ))
        .await;

        let set_cookie = self.session_cookie(&token);
        Ok(LoginOutcome {
            user,
            token,
            set_cookie,
        })
    }
}

#[cfg(test)]
mod tests {
    use sqlx::sqlite::SqliteConnectOptions;
    use std::str::FromStr;

    use super::*;
    use crate::sessions::generate_token;
    use crate::types::Email;

    #[tokio::test]
    async fn build_with_url_defaults() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let config = ath.session_config();
        assert_eq!(config.ttl, Duration::hours(24));
        assert_eq!(config.cookie_name, "allowthem_session");
        assert!(config.secure);

        let token = generate_token();
        let cookie = ath.session_cookie(&token);
        assert!(!cookie.contains("; Domain="));
    }

    #[tokio::test]
    async fn build_with_pool() {
        let opts = SqliteConnectOptions::from_str("sqlite::memory:")
            .unwrap()
            .pragma("foreign_keys", "ON");
        let pool = sqlx::SqlitePool::connect_with(opts).await.unwrap();

        let ath = AllowThemBuilder::with_pool(pool).build().await.unwrap();

        let email = Email::new("test@example.com".into()).unwrap();
        let user = ath.db().create_user(email, "password123", None, None).await;
        assert!(user.is_ok());
    }

    #[tokio::test]
    async fn build_with_overrides() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .session_ttl(Duration::hours(48))
            .cookie_name("my_session")
            .cookie_secure(false)
            .cookie_domain("example.com")
            .build()
            .await
            .unwrap();

        let config = ath.session_config();
        assert_eq!(config.ttl, Duration::hours(48));
        assert_eq!(config.cookie_name, "my_session");
        assert!(!config.secure);
    }

    #[tokio::test]
    async fn session_cookie_uses_config() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("custom")
            .cookie_secure(false)
            .cookie_domain("example.com")
            .build()
            .await
            .unwrap();

        let token = generate_token();
        let cookie = ath.session_cookie(&token);

        assert!(cookie.contains("custom="));
        assert!(cookie.contains("; Domain=example.com"));
        assert!(!cookie.contains("; Secure"));
    }

    #[tokio::test]
    async fn clear_session_cookie_defaults() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let cookie = ath.clear_session_cookie();
        assert!(cookie.starts_with("allowthem_session=;"));
        assert!(cookie.contains("; Max-Age=0"));
        assert!(!cookie.contains("; Domain="));
        assert!(cookie.contains("; Secure"));
    }

    #[tokio::test]
    async fn clear_session_cookie_name_matches_session_cookie() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("app_session")
            .build()
            .await
            .unwrap();

        let token = generate_token();
        let set = ath.session_cookie(&token);
        let clear = ath.clear_session_cookie();

        // Both must share the same cookie name prefix so the browser matches them.
        assert!(set.starts_with("app_session="));
        assert!(clear.starts_with("app_session=;"));
        assert!(clear.contains("; Path=/"));
        assert!(clear.contains("; Max-Age=0"));
    }

    #[tokio::test]
    async fn clear_session_cookie_with_domain_and_no_secure() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("my_session")
            .cookie_secure(false)
            .cookie_domain("example.com")
            .build()
            .await
            .unwrap();

        let cookie = ath.clear_session_cookie();
        assert!(cookie.starts_with("my_session=;"));
        assert!(cookie.contains("; Max-Age=0"));
        assert!(cookie.contains("; Domain=example.com"));
        assert!(!cookie.contains("; Secure"));
    }

    #[tokio::test]
    async fn parse_session_cookie_uses_config() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("custom")
            .build()
            .await
            .unwrap();

        let header = "custom=abc123; other=xyz";
        let result = ath.parse_session_cookie(header);

        assert!(result.is_some());
        assert_eq!(result.unwrap().as_str(), "abc123");
    }

    #[tokio::test]
    async fn build_with_bad_url_fails() {
        let result = AllowThemBuilder::new("not-a-url").build().await;

        assert!(result.is_err());
        assert!(matches!(result.err().unwrap(), BuildError::Database(_)));
    }

    #[tokio::test]
    async fn clone_shares_state() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();
        let ath2 = ath.clone();

        let email = Email::new("shared@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "password123", None, None)
            .await
            .unwrap();

        let found = ath2.db().get_user(user.id).await;
        assert!(found.is_ok());
        assert_eq!(found.unwrap().id, user.id);
    }

    #[tokio::test]
    async fn signing_key_not_configured_returns_error() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();
        let result = ath.signing_key();
        assert!(matches!(
            result,
            Err(crate::error::AuthError::SigningKeyNotConfigured)
        ));
    }

    #[tokio::test]
    async fn base_url_not_configured_returns_error() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();
        let result = ath.base_url();
        assert!(matches!(
            result,
            Err(crate::error::AuthError::BaseUrlNotConfigured)
        ));
    }

    #[tokio::test]
    async fn base_url_configured_returns_value() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://auth.example.com")
            .build()
            .await
            .unwrap();
        let result = ath.base_url();
        assert!(matches!(result, Ok("https://auth.example.com")));
    }

    #[tokio::test]
    async fn login_success() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .build()
            .await
            .unwrap();

        let email = Email::new("login@example.com".into()).unwrap();
        ath.db()
            .create_user(email, "secret", None, None)
            .await
            .unwrap();

        let outcome = ath.login("login@example.com", "secret").await.unwrap();
        assert_eq!(outcome.user.email.as_str(), "login@example.com");
        assert!(!outcome.token.as_str().is_empty());
        assert!(outcome.set_cookie.contains("allowthem_session="));
    }

    #[tokio::test]
    async fn login_wrong_password() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let email = Email::new("wp@example.com".into()).unwrap();
        ath.db()
            .create_user(email, "correct", None, None)
            .await
            .unwrap();

        let result = ath.login("wp@example.com", "wrong").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn login_unknown_identifier() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let result = ath.login("nobody@example.com", "any").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn login_inactive_user() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let email = Email::new("inactive@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "secret", None, None)
            .await
            .unwrap();
        ath.db().update_user_active(user.id, false).await.unwrap();

        let result = ath.login("inactive@example.com", "secret").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn login_no_password_hash() {
        use crate::types::UserId;

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        // Insert a user directly with password_hash = NULL (SSO-only account).
        // UserId uses UUID v7; bind it properly so SQLx can round-trip it.
        let id = UserId::new();
        let now = chrono::Utc::now()
            .format("%Y-%m-%dT%H:%M:%S%.3fZ")
            .to_string();
        sqlx::query(
            "INSERT INTO allowthem_users \
             (id, email, username, password_hash, email_verified, is_active, created_at, updated_at) \
             VALUES (?, 'sso@example.com', NULL, NULL, 1, 1, ?, ?)",
        )
        .bind(id)
        .bind(&now)
        .bind(&now)
        .execute(ath.db().pool())
        .await
        .unwrap();

        let result = ath.login("sso@example.com", "any").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn create_session_cookie_success() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .build()
            .await
            .unwrap();

        let email = Email::new("sess@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "secret", None, None)
            .await
            .unwrap();

        let outcome = ath.create_session_cookie(user.id).await.unwrap();
        assert_eq!(outcome.user.id, user.id);
        assert!(!outcome.token.as_str().is_empty());
        assert!(outcome.set_cookie.contains("allowthem_session="));

        // Session must exist in DB
        let session = ath.db().lookup_session(&outcome.token).await.unwrap();
        assert!(session.is_some());
    }

    #[tokio::test]
    async fn create_session_cookie_unknown_user() {
        use crate::types::UserId;

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let result = ath.create_session_cookie(UserId::new()).await;
        assert!(matches!(result, Err(AuthError::NotFound)));
    }

    // -- on_user_active callback tests ------------------------------------------

    #[tokio::test]
    async fn on_user_active_default_is_none() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();
        assert!(ath.on_user_active().is_none());
    }

    #[tokio::test]
    async fn on_user_active_builder_stores_callback() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        assert!(ath.on_user_active().is_some());
    }

    #[tokio::test]
    async fn on_user_active_fires_on_login_success() {
        use std::sync::{Arc, Mutex};

        let captured: Arc<Mutex<Vec<(UserId, DateTime<Utc>)>>> = Arc::new(Mutex::new(Vec::new()));
        let cap = captured.clone();
        let cb: OnUserActive = Arc::new(move |uid, ts| {
            cap.lock().unwrap().push((uid, ts));
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let email = Email::new("active@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "hunter2", None, None)
            .await
            .unwrap();

        let before = Utc::now();
        ath.login("active@example.com", "hunter2").await.unwrap();
        let after = Utc::now();

        let events = captured.lock().unwrap();
        assert_eq!(events.len(), 1, "callback must fire exactly once");
        assert_eq!(events[0].0, user.id, "callback receives correct UserId");
        assert!(
            events[0].1 >= before && events[0].1 <= after,
            "callback timestamp must be within the test window"
        );
    }

    #[tokio::test]
    async fn on_user_active_no_fire_on_login_wrong_password() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let email = Email::new("wrongpw@example.com".into()).unwrap();
        ath.db()
            .create_user(email, "correct", None, None)
            .await
            .unwrap();

        let _ = ath.login("wrongpw@example.com", "wrong").await;
        assert_eq!(counter.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn on_user_active_no_fire_on_login_unknown_identifier() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let _ = ath.login("nobody@example.com", "any").await;
        assert_eq!(counter.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn on_user_active_no_fire_on_login_inactive_user() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let email = Email::new("inact@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "secret", None, None)
            .await
            .unwrap();
        ath.db().update_user_active(user.id, false).await.unwrap();

        let _ = ath.login("inact@example.com", "secret").await;
        assert_eq!(counter.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn on_user_active_no_fire_on_login_no_password_hash() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let id = UserId::new();
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        sqlx::query(
            "INSERT INTO allowthem_users \
             (id, email, username, password_hash, email_verified, is_active, created_at, updated_at) \
             VALUES (?, 'sso2@example.com', NULL, NULL, 1, 1, ?, ?)",
        )
        .bind(id)
        .bind(&now)
        .bind(&now)
        .execute(ath.db().pool())
        .await
        .unwrap();

        let _ = ath.login("sso2@example.com", "any").await;
        assert_eq!(counter.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn on_user_active_fires_on_create_session_cookie() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let email = Email::new("csc@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "pass", None, None)
            .await
            .unwrap();

        ath.create_session_cookie(user.id).await.unwrap();
        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn on_user_active_no_fire_on_create_session_cookie_unknown_user() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let _ = ath.create_session_cookie(UserId::new()).await;
        assert_eq!(counter.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn on_user_active_no_fire_on_session_validation() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU64, Ordering};

        let counter = Arc::new(AtomicU64::new(0));
        let c = counter.clone();
        let cb: OnUserActive = Arc::new(move |_uid, _ts| {
            c.fetch_add(1, Ordering::Relaxed);
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let email = Email::new("passive@example.com".into()).unwrap();
        ath.db()
            .create_user(email, "pass", None, None)
            .await
            .unwrap();

        let outcome = ath.login("passive@example.com", "pass").await.unwrap();
        // Counter is 1 after the login fire.
        assert_eq!(counter.load(Ordering::Relaxed), 1);

        // Session validation is a passive event — counter must not change.
        let _ = ath
            .db()
            .validate_session(&outcome.token, Duration::hours(24))
            .await
            .unwrap();
        assert_eq!(
            counter.load(Ordering::Relaxed),
            1,
            "session validation must not fire callback"
        );
    }

    #[tokio::test]
    async fn on_user_active_panic_does_not_propagate() {
        let cb: OnUserActive = Arc::new(|_uid, _ts| {
            panic!("intentional test panic in on_user_active callback");
        });

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .on_user_active(cb)
            .build()
            .await
            .unwrap();

        let email = Email::new("panic@example.com".into()).unwrap();
        ath.db()
            .create_user(email, "pass", None, None)
            .await
            .unwrap();

        // Suppress the default panic hook output so test output stays clean.
        let prev_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let result = ath.login("panic@example.com", "pass").await;
        std::panic::set_hook(prev_hook);

        assert!(
            result.is_ok(),
            "panic in callback must not propagate to caller"
        );
    }

    // ---- EmailSender integration tests ----

    /// A test-only sender that captures every message delivered to it.
    struct CapturingSender(std::sync::Arc<std::sync::Mutex<Vec<crate::email::EmailMessage>>>);

    impl crate::email::EmailSender for CapturingSender {
        fn send<'a>(
            &'a self,
            message: &'a crate::email::EmailMessage,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<(), crate::error::AuthError>> + Send + 'a>,
        > {
            self.0.lock().unwrap().push(message.clone());
            Box::pin(std::future::ready(Ok(())))
        }
    }

    fn capturing_sender() -> (
        Box<dyn crate::email::EmailSender>,
        std::sync::Arc<std::sync::Mutex<Vec<crate::email::EmailMessage>>>,
    ) {
        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sender = CapturingSender(captured.clone());
        (Box::new(sender), captured)
    }

    /// A test-only sender that always returns an error.
    struct FailingSender;

    impl crate::email::EmailSender for FailingSender {
        fn send<'a>(
            &'a self,
            _message: &'a crate::email::EmailMessage,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<(), crate::error::AuthError>> + Send + 'a>,
        > {
            Box::pin(std::future::ready(Err(crate::error::AuthError::Email(
                "injected failure".into(),
            ))))
        }
    }

    async fn make_user_with_username(ath: &AllowThem, email_str: &str, username: Option<&str>) {
        let email = Email::new(email_str.into()).unwrap();
        ath.db()
            .create_user(
                email,
                "password",
                username.map(|s| crate::types::Username::new(s)),
                None,
            )
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn email_sender_default_is_noop_and_succeeds() {
        // Build without email_sender — defaults to NoopEmailSender.
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .build()
            .await
            .unwrap();

        // NoopEmailSender::send always returns Ok(()).
        let msg = crate::email::EmailMessage {
            to: "nobody@example.com".into(),
            subject: "test".into(),
            template: crate::email::EmailTemplate::PasswordReset {
                url: "https://example.com/reset".into(),
                username: "nobody".into(),
            },
        };
        let result = ath.email_sender().send(&msg).await;
        assert!(result.is_ok(), "NoopEmailSender must return Ok");
    }

    #[tokio::test]
    async fn email_sender_custom_sender_installed() {
        let (sender_box, captured) = capturing_sender();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(sender_box)
            .build()
            .await
            .unwrap();

        let msg = crate::email::EmailMessage {
            to: "test@example.com".into(),
            subject: "subject".into(),
            template: crate::email::EmailTemplate::PasswordReset {
                url: "https://example.com/reset".into(),
                username: "test".into(),
            },
        };
        ath.email_sender().send(&msg).await.unwrap();
        assert_eq!(captured.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn send_password_reset_email_builds_correct_template() {
        let (sender_box, captured) = capturing_sender();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(sender_box)
            .build()
            .await
            .unwrap();
        make_user_with_username(&ath, "reset@example.com", Some("alice")).await;

        let email = Email::new("reset@example.com".into()).unwrap();
        ath.send_password_reset_email(&email).await.unwrap();

        let msgs = captured.lock().unwrap();
        assert_eq!(msgs.len(), 1);
        let msg = &msgs[0];
        assert_eq!(msg.to, "reset@example.com");
        assert_eq!(msg.subject, "Reset your password");
        match &msg.template {
            crate::email::EmailTemplate::PasswordReset { url, username } => {
                assert!(
                    url.contains("https://example.com"),
                    "URL must contain base_url"
                );
                assert!(
                    url.contains("/auth/reset-password?token="),
                    "URL must have path"
                );
                assert_eq!(username, "alice");
            }
            other => panic!("expected PasswordReset template, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn send_verification_email_builds_correct_template() {
        let (sender_box, captured) = capturing_sender();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(sender_box)
            .build()
            .await
            .unwrap();
        let email = Email::new("verify@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(
                email.clone(),
                "pass",
                Some(crate::types::Username::new("bob")),
                None,
            )
            .await
            .unwrap();

        ath.send_verification_email(user.id, &email).await.unwrap();

        let msgs = captured.lock().unwrap();
        assert_eq!(msgs.len(), 1);
        let msg = &msgs[0];
        assert_eq!(msg.to, "verify@example.com");
        assert_eq!(msg.subject, "Verify your email address");
        match &msg.template {
            crate::email::EmailTemplate::EmailVerification { url, username } => {
                assert!(url.contains("https://example.com"));
                assert!(url.contains("/auth/verify-email?token="));
                assert_eq!(username, "bob");
            }
            other => panic!("expected EmailVerification template, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn send_password_reset_email_username_fallback_uses_email_local_part() {
        let (sender_box, captured) = capturing_sender();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(sender_box)
            .build()
            .await
            .unwrap();
        // Create user with no username — fallback must use email local part.
        make_user_with_username(&ath, "noname@example.com", None).await;

        let email = Email::new("noname@example.com".into()).unwrap();
        ath.send_password_reset_email(&email).await.unwrap();

        let msgs = captured.lock().unwrap();
        let msg = &msgs[0];
        match &msg.template {
            crate::email::EmailTemplate::PasswordReset { username, .. } => {
                assert_eq!(username, "noname", "must fall back to email local part");
            }
            other => panic!("expected PasswordReset, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn sender_error_propagates_as_auth_error_email() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(Box::new(FailingSender))
            .build()
            .await
            .unwrap();
        make_user_with_username(&ath, "fail@example.com", Some("fail")).await;

        let email = Email::new("fail@example.com".into()).unwrap();
        let result = ath.send_password_reset_email(&email).await;
        assert!(
            matches!(result, Err(crate::error::AuthError::Email(_))),
            "sender error must surface as AuthError::Email"
        );
    }

    #[tokio::test]
    async fn send_password_reset_email_silent_on_unknown_email() {
        let (sender_box, captured) = capturing_sender();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(sender_box)
            .build()
            .await
            .unwrap();

        let email = Email::new("ghost@example.com".into()).unwrap();
        let result = ath.send_password_reset_email(&email).await;
        assert!(result.is_ok(), "must return Ok for unknown email");
        assert!(
            captured.lock().unwrap().is_empty(),
            "no email must be sent for unknown address"
        );
    }

    #[tokio::test]
    async fn send_invitation_email_creates_invitation_and_sends() {
        use crate::types::UserId;

        let (sender_box, captured) = capturing_sender();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(sender_box)
            .build()
            .await
            .unwrap();

        // Create the inviter.
        let inviter_email = Email::new("inviter@example.com".into()).unwrap();
        let inviter = ath
            .db()
            .create_user(
                inviter_email,
                "pass",
                Some(crate::types::Username::new("Alice")),
                None,
            )
            .await
            .unwrap();
        let inviter_id: UserId = inviter.id;

        let invitee = Email::new("invitee@example.com".into()).unwrap();
        let invite_url = "https://example.com/invite/tok123";
        let expires_at = chrono::Utc::now() + chrono::Duration::hours(48);

        ath.send_invitation_email(&invitee, invite_url, inviter_id, expires_at)
            .await
            .unwrap();

        // One email sent.
        let msgs = captured.lock().unwrap();
        assert_eq!(msgs.len(), 1);
        let msg = &msgs[0];
        assert_eq!(msg.to, "invitee@example.com");
        match &msg.template {
            crate::email::EmailTemplate::Invitation { url, invited_by } => {
                assert_eq!(url, invite_url);
                assert_eq!(invited_by, "Alice");
            }
            other => panic!("expected Invitation template, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn send_mfa_recovery_email_sends_codes_without_db_write() {
        let (sender_box, captured) = capturing_sender();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .email_sender(sender_box)
            .build()
            .await
            .unwrap();

        let email = Email::new("mfa@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(
                email,
                "pass",
                Some(crate::types::Username::new("carol")),
                None,
            )
            .await
            .unwrap();

        let codes = vec!["code-1".into(), "code-2".into(), "code-3".into()];
        ath.send_mfa_recovery_email(user.id, codes.clone())
            .await
            .unwrap();

        let msgs = captured.lock().unwrap();
        assert_eq!(msgs.len(), 1);
        let msg = &msgs[0];
        assert_eq!(msg.to, "mfa@example.com");
        assert_eq!(msg.subject, "Your MFA recovery codes");
        match &msg.template {
            crate::email::EmailTemplate::MfaRecovery {
                codes: sent_codes,
                username,
            } => {
                assert_eq!(sent_codes, &codes, "codes must be forwarded as-is");
                assert_eq!(username, "carol");
            }
            other => panic!("expected MfaRecovery template, got {other:?}"),
        }
    }

    // ---- EventSink integration tests ----

    /// A test-only sink that captures every event emitted to it.
    struct CapturingSink(std::sync::Arc<std::sync::Mutex<Vec<crate::event_sink::AuthEvent>>>);

    impl crate::event_sink::EventSink for CapturingSink {
        fn emit<'a>(
            &'a self,
            event: &'a crate::event_sink::AuthEvent,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
            self.0.lock().unwrap().push(event.clone());
            Box::pin(std::future::ready(()))
        }
    }

    fn capturing_sink() -> (
        Box<dyn crate::event_sink::EventSink>,
        std::sync::Arc<std::sync::Mutex<Vec<crate::event_sink::AuthEvent>>>,
    ) {
        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = CapturingSink(captured.clone());
        (Box::new(sink), captured)
    }

    async fn ath_with_sink() -> (
        AllowThem,
        std::sync::Arc<std::sync::Mutex<Vec<crate::event_sink::AuthEvent>>>,
    ) {
        let (sink_box, captured) = capturing_sink();
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .event_sink(sink_box)
            .build()
            .await
            .unwrap();
        (ath, captured)
    }

    #[tokio::test]
    async fn create_user_emits_user_created() {
        let (ath, captured) = ath_with_sink().await;
        let email = crate::types::Email::new("ev@example.com".into()).unwrap();
        ath.create_user(email, "pass1234", None, None)
            .await
            .unwrap();

        let events = captured.lock().unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, "user.created");
        assert!(events[0].user_id.is_some());
    }

    #[tokio::test]
    async fn login_emits_session_created() {
        let (ath, captured) = ath_with_sink().await;
        let email = crate::types::Email::new("ev@example.com".into()).unwrap();
        ath.create_user(email.clone(), "pass1234", None, None)
            .await
            .unwrap();
        captured.lock().unwrap().clear(); // discard user.created

        ath.login("ev@example.com", "pass1234").await.unwrap();

        let events = captured.lock().unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, "session.created");
    }

    #[tokio::test]
    async fn delete_session_emits_session_destroyed() {
        let (ath, captured) = ath_with_sink().await;
        let email = crate::types::Email::new("ev@example.com".into()).unwrap();
        ath.create_user(email.clone(), "pass1234", None, None)
            .await
            .unwrap();
        let token = ath.login("ev@example.com", "pass1234").await.unwrap().token;
        captured.lock().unwrap().clear();

        ath.delete_session(&token).await.unwrap();

        let events = captured.lock().unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, "session.destroyed");
    }

    #[tokio::test]
    async fn update_user_email_emits_user_updated() {
        let (ath, captured) = ath_with_sink().await;
        let email = crate::types::Email::new("ev@example.com".into()).unwrap();
        let user = ath
            .create_user(email, "pass1234", None, None)
            .await
            .unwrap();
        captured.lock().unwrap().clear();

        let new_email = crate::types::Email::new("new@example.com".into()).unwrap();
        ath.update_user_email(user.id, new_email).await.unwrap();

        let events = captured.lock().unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, "user.updated");
        assert_eq!(events[0].data["field"], "email");
    }

    #[tokio::test]
    async fn update_user_active_false_emits_user_blocked() {
        let (ath, captured) = ath_with_sink().await;
        let email = crate::types::Email::new("ev@example.com".into()).unwrap();
        let user = ath
            .create_user(email, "pass1234", None, None)
            .await
            .unwrap();
        captured.lock().unwrap().clear();

        ath.update_user_active(user.id, false).await.unwrap();

        let events = captured.lock().unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, "user.blocked");
    }

    #[tokio::test]
    async fn delete_user_emits_user_deleted() {
        let (ath, captured) = ath_with_sink().await;
        let email = crate::types::Email::new("ev@example.com".into()).unwrap();
        let user = ath
            .create_user(email, "pass1234", None, None)
            .await
            .unwrap();
        captured.lock().unwrap().clear();

        ath.delete_user(user.id).await.unwrap();

        let events = captured.lock().unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, "user.deleted");
    }

    #[tokio::test]
    async fn noop_sink_is_default_and_no_events_captured() {
        // No event_sink set → defaults to NoopEventSink; no events stored.
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://example.com")
            .build()
            .await
            .unwrap();
        let email = crate::types::Email::new("ev@example.com".into()).unwrap();
        // Just confirm this doesn't panic.
        ath.create_user(email, "pass1234", None, None)
            .await
            .unwrap();
    }
}