slabs-auth 0.4.0

Explicit low-level auth battery: Argon2id passwords, DB sessions, magic links, Bearer API tokens, and HMAC signing
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
//! Authentication, browser sessions, magic links, personal access tokens, and HMAC signing for Slabs.
//!
//! # What this crate owns
//!
//! - Types: [`Auth`], [`Session`], [`Principal`], [`MagicLinkIssued`], [`MagicLinkConsumed`],
//!   [`AccessTokenIssued`], [`SESSION_COOKIE_NAME`] (`"slabs_session"`), and
//!   [`HOST_SESSION_COOKIE_NAME`] (`"__Host-slabs_session"`).
//! - Framework SQLite tables created by `slabs_db::Db::init_system_tables`:
//!   - `slabs_sessions`: SHA-256 hashed browser session tokens, `user_id`, `role`, and `expires_at`.
//!   - `slabs_magic_links`: domain-separated HMAC-SHA256 hashed 6-character verification codes bound to
//!     normalized `email` and `purpose`, plus `expires_at`.
//!   - `slabs_access_tokens`: SHA-256 hashed `Authorization: Bearer` tokens, `user_id`, `role`, `permission`, `last_used_at`, and `expires_at`.
//! - User accounts live in your application's own `users` table in your SQL migrations. This crate does not own a `users` table.
//!
//! # Agent invariants
//!
//! - Put an explicit auth guard on line 1 of every protected slab handler. Do not rely on hidden middleware or callbacks.
//!   - [`Auth::require_session`]: requires a valid session cookie (HTTP 401 when missing or expired).
//!   - [`Auth::require_admin`]: requires a valid session with `role == "admin"` (HTTP 401 or 403).
//!   - [`Auth::require_auth`]: accepts either `Authorization: Bearer <token>` or a session cookie (HTTP 401).
//!   - [`Auth::require_write_auth`]: requires [`Auth::require_auth`] with `permission == "write"` (HTTP 403 for `"read"` tokens).
//! - Hash passwords asynchronously with [`Auth::hash_password`] (`Argon2id` offloaded to `spawn_blocking` with a concurrency semaphore and 1024-byte cap) and verify with [`Auth::verify_password`] or [`Auth::verify_password_constant_time`].
//! - Magic links generate 6-character alphanumeric codes without ambiguous characters (`0`, `O`, `1`, `I`), hashed with a keyed domain-separated HMAC bound to `(email, purpose)`. [`Auth::consume_magic_link`] requires matching `email`, `purpose`, and code, locks out after 5 failed attempts in 15 minutes, and runs `DELETE ... RETURNING` so every code is single-use.
//! - Personal access tokens start with `slb_` and are stored only as SHA-256 hex digests. Return [`AccessTokenIssued::token`] once at issuance because plaintext tokens cannot be recovered later.
//! - If an `Authorization: Bearer` header is present, [`Auth::optional_auth`] checks only the bearer token and does not fall back to a session cookie on failure.
//! - Use [`Auth::create_session_in_tx`] when creating a user and a browser session inside one SQLite transaction, and [`Auth::rotate_session`] on login or privilege escalation.
//!
//! # Example
//!
//! ```rust,no_run
//! use axum_extra::extract::CookieJar;
//! use http::HeaderMap;
//! use slabs_auth::Auth;
//! use slabs_core::SlabResult;
//!
//! async fn protected_handler(auth: &Auth, jar: &CookieJar, headers: &HeaderMap) -> SlabResult<()> {
//!     // Line 1 guard for browser-only endpoints:
//!     let session = auth.require_session(jar).await?;
//!
//!     // Or accept either a session cookie or a write-scoped Bearer token:
//!     let principal = auth.require_write_auth(jar, headers).await?;
//!
//!     let _ = (session.user_id, principal.user_id);
//!     Ok(())
//! }
//! ```

use argon2::{
    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Algorithm, Argon2,
};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use chrono::{DateTime, Duration, SecondsFormat, Utc};
use hmac::{Hmac, Mac};
use http::{header, HeaderMap};
use rand_core::{OsRng, RngCore};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sha2::{Digest, Sha256};
use slabs_core::{id, SlabError, SlabResult};
use slabs_db::Db;
use sqlx::{Sqlite, Transaction};
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration as StdDuration, Instant};
use tokio::sync::Semaphore;

type HmacSha256 = Hmac<Sha256>;

const MAX_PASSWORD_BYTES: usize = 1024;
const DEFAULT_SESSION_TTL_DAYS: i64 = 30;
const MAGIC_LINK_MAX_ATTEMPTS: u32 = 5;
const MAGIC_LINK_LOCKOUT_WINDOW: StdDuration = StdDuration::from_secs(15 * 60);
const ACCESS_TOKEN_LAST_USED_DEBOUNCE_SECS: i64 = 5 * 60;

static DUMMY_PASSWORD_HASH: OnceLock<String> = OnceLock::new();

fn dummy_password_hash() -> &'static str {
    DUMMY_PASSWORD_HASH.get_or_init(|| {
        let salt = SaltString::generate(&mut OsRng);
        Argon2::default()
            .hash_password(b"slabs-dummy-password-for-constant-time-verify", &salt)
            .expect("dummy Argon2id hash generation must succeed")
            .to_string()
    })
}

fn utc_timestamp(dt: DateTime<Utc>) -> String {
    dt.to_rfc3339_opts(SecondsFormat::Micros, true)
}

#[derive(Serialize)]
struct SignedTokenEnvelopeRef<'a, T: ?Sized> {
    p: &'a str,
    exp: i64,
    d: &'a T,
}

#[derive(Deserialize)]
struct SignedTokenEnvelope<T> {
    p: String,
    exp: i64,
    d: T,
}

/// Cookie name used to store browser session tokens when `cookie_secure` is `false`.
pub const SESSION_COOKIE_NAME: &str = "slabs_session";

/// Host-prefixed cookie name used when `cookie_secure` is `true` (`__Host-` prefix prevents subdomain injection).
pub const HOST_SESSION_COOKIE_NAME: &str = "__Host-slabs_session";

/// Active browser session persisted in the `slabs_sessions` table.
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Session {
    /// Prefixed session identifier (`ses_...`).
    pub id: String,
    /// Authenticated user's identifier.
    pub user_id: String,
    /// Role assigned to the user when the session was created (e.g. `"member"`, `"admin"`).
    pub role: String,
    /// RFC 3339 UTC timestamp after which the session is no longer valid.
    pub expires_at: String,
    /// RFC 3339 UTC timestamp when the session was created.
    pub created_at: String,
}

/// Authenticated actor resolved from either a browser session cookie or an `Authorization: Bearer` token.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Principal {
    /// Authenticated user's identifier.
    pub user_id: String,
    /// Role associated with the authenticated user.
    pub role: String,
    /// Authentication mechanism used (`"session"` or `"bearer"`).
    pub auth_kind: String,
    /// Granted permission level (`"write"` or `"read"`).
    pub permission: String,
}

/// Result returned when a new one-time magic link code is issued.
#[derive(Clone, Serialize, Deserialize)]
pub struct MagicLinkIssued {
    /// Prefixed magic-link record identifier (`mlk_...`).
    pub id: String,
    /// Normalized lowercase email address the code was issued for.
    pub email: String,
    /// Application-defined purpose for the magic link (e.g. `"sign_in"`).
    pub purpose: String,
    /// Plaintext one-time verification code to deliver to the user.
    pub code: String,
    /// RFC 3339 UTC timestamp when the code expires.
    pub expires_at: String,
}

impl fmt::Debug for MagicLinkIssued {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MagicLinkIssued")
            .field("id", &self.id)
            .field("email", &self.email)
            .field("purpose", &self.purpose)
            .field("code", &"[REDACTED]")
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

/// Verified metadata returned after atomically consuming a magic link code.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MagicLinkConsumed {
    /// Prefixed magic-link record identifier (`mlk_...`).
    pub id: String,
    /// Normalized email address associated with the consumed code.
    pub email: String,
    /// Application-defined purpose associated with the consumed code.
    pub purpose: String,
}

/// Result returned when a new personal access token is issued.
#[derive(Clone, Serialize, Deserialize)]
pub struct AccessTokenIssued {
    /// Prefixed access-token record identifier (`pat_...`).
    pub id: String,
    /// Owner user identifier.
    pub user_id: String,
    /// Human-readable label describing the token's purpose.
    pub description: String,
    /// Permission scope granted to the token (`"write"` or `"read"`).
    pub permission: String,
    /// Plaintext bearer token shown once upon issuance (`slb_...`).
    pub token: String,
}

impl fmt::Debug for AccessTokenIssued {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AccessTokenIssued")
            .field("id", &self.id)
            .field("user_id", &self.user_id)
            .field("description", &self.description)
            .field("permission", &self.permission)
            .field("token", &"[REDACTED]")
            .finish()
    }
}

/// Explicit authentication and session service backed by `slabs_sessions`, `slabs_magic_links`, and `slabs_access_tokens`.
///
/// Supports async `Argon2id` password hashing, single-use 6-character magic links bound to
/// `(email, purpose)`, `HttpOnly` browser session cookies, SHA-256 hashed `Authorization: Bearer`
/// tokens, and domain-separated HMAC-SHA256 signing.
#[derive(Clone)]
pub struct Auth {
    db: Option<Db>,
    secret_key: String,
    cookie_secure: bool,
    password_permits: Arc<Semaphore>,
    magic_link_failures: Arc<Mutex<HashMap<String, (u32, Instant)>>>,
}

impl fmt::Debug for Auth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Auth")
            .field("db", &self.db)
            .field("secret_key", &"<redacted>")
            .field("cookie_secure", &self.cookie_secure)
            .finish_non_exhaustive()
    }
}

impl Auth {
    fn default_password_permits() -> Arc<Semaphore> {
        let permits = std::thread::available_parallelism().map_or(4, |n| n.get().clamp(2, 16));
        Arc::new(Semaphore::new(permits))
    }

    /// Create an [`Auth`] service backed by `db`, using `secret_key` for HMAC signing and `cookie_secure` for the cookie `Secure` flag.
    #[must_use]
    pub fn new(db: Db, secret_key: impl Into<String>, cookie_secure: bool) -> Self {
        Self {
            db: Some(db),
            secret_key: secret_key.into(),
            cookie_secure,
            password_permits: Self::default_password_permits(),
            magic_link_failures: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Create a stateless [`Auth`] handle for HMAC signing, token verification, and signed cookies without a database connection.
    #[must_use]
    pub fn for_signing(secret_key: impl Into<String>, cookie_secure: bool) -> Self {
        Self {
            db: None,
            secret_key: secret_key.into(),
            cookie_secure,
            password_permits: Self::default_password_permits(),
            magic_link_failures: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Return whether cookies emitted by this [`Auth`] instance should set the `Secure` attribute.
    #[must_use]
    pub fn cookie_secure(&self) -> bool {
        self.cookie_secure
    }

    /// Return the active session cookie name (`"__Host-slabs_session"` when `cookie_secure` is `true`,
    /// or `"slabs_session"` when `false`).
    #[must_use]
    pub fn session_cookie_name(&self) -> &'static str {
        if self.cookie_secure {
            HOST_SESSION_COOKIE_NAME
        } else {
            SESSION_COOKIE_NAME
        }
    }

    fn db(&self) -> SlabResult<&Db> {
        self.db
            .as_ref()
            .ok_or_else(|| SlabError::internal("Auth requires a database connection"))
    }

    /// Hash a plaintext password asynchronously with `Argon2id` and a random OS salt, returning a PHC string.
    ///
    /// Rejects passwords exceeding 1024 bytes and runs hashing inside `tokio::task::spawn_blocking`
    /// guarded by a bounded concurrency semaphore so CPU-heavy hashing cannot starve the async runtime.
    pub async fn hash_password(&self, password: &str) -> SlabResult<String> {
        if password.len() > MAX_PASSWORD_BYTES {
            return Err(SlabError::bad_request("password exceeds maximum length"));
        }
        let _permit = self
            .password_permits
            .acquire()
            .await
            .map_err(|_| SlabError::internal("password hashing semaphore closed"))?;
        let password_owned = password.to_owned();
        tokio::task::spawn_blocking(move || {
            let salt = SaltString::generate(&mut OsRng);
            Argon2::default()
                .hash_password(password_owned.as_bytes(), &salt)
                .map(|h| h.to_string())
                .map_err(|e| SlabError::internal(format!("password hashing failed: {e}")))
        })
        .await
        .map_err(|e| SlabError::internal(format!("password hashing task failed: {e}")))?
    }

    /// Verify a plaintext password asynchronously against a stored `Argon2id` PHC hash string.
    ///
    /// Rejects passwords exceeding 1024 bytes, requires the parsed PHC hash to use
    /// [`argon2::Algorithm::Argon2id`], and executes verification inside `tokio::task::spawn_blocking`
    /// guarded by the password semaphore.
    pub async fn verify_password(&self, password: &str, encoded_hash: &str) -> SlabResult<bool> {
        if password.len() > MAX_PASSWORD_BYTES {
            return Err(SlabError::bad_request("password exceeds maximum length"));
        }
        let _permit = self
            .password_permits
            .acquire()
            .await
            .map_err(|_| SlabError::internal("password verification semaphore closed"))?;
        let password_owned = password.to_owned();
        let hash_owned = encoded_hash.to_owned();
        tokio::task::spawn_blocking(move || {
            let Ok(parsed) = PasswordHash::new(&hash_owned) else {
                return false;
            };
            let Ok(alg) = Algorithm::try_from(parsed.algorithm) else {
                return false;
            };
            if alg != Algorithm::Argon2id {
                return false;
            }
            Argon2::default()
                .verify_password(password_owned.as_bytes(), &parsed)
                .is_ok()
        })
        .await
        .map_err(|e| SlabError::internal(format!("password verification task failed: {e}")))
    }

    /// Verify a plaintext password against an optional stored `Argon2id` hash in constant time
    /// with respect to user existence.
    ///
    /// When `encoded_hash` is `None`, still runs an `Argon2id` verification against a precomputed
    /// dummy hash and returns `Ok(false)` to prevent login timing enumeration.
    pub async fn verify_password_constant_time(
        &self,
        password: &str,
        encoded_hash: Option<&str>,
    ) -> SlabResult<bool> {
        if password.len() > MAX_PASSWORD_BYTES {
            return Err(SlabError::bad_request("password exceeds maximum length"));
        }
        if let Some(hash) = encoded_hash {
            self.verify_password(password, hash).await
        } else {
            let _ = self
                .verify_password(password, dummy_password_hash())
                .await?;
            Ok(false)
        }
    }

    /// Compute the hex-encoded SHA-256 digest of a raw token.
    pub fn hash_token(&self, raw_token: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(raw_token.as_bytes());
        hex::encode(hasher.finalize())
    }

    /// Generate a cryptographically random 32-byte hex-encoded token.
    pub fn generate_token(&self) -> String {
        let mut bytes = [0u8; 32];
        OsRng.fill_bytes(&mut bytes);
        hex::encode(bytes)
    }

    /// Generate a random alphanumeric code of length `len`, omitting ambiguous `0`, `O`, `1`, and `I` characters.
    pub fn generate_short_code(&self, len: usize) -> String {
        const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
        let mut bytes = vec![0u8; len];
        OsRng.fill_bytes(&mut bytes);
        bytes
            .into_iter()
            .map(|b| ALPHABET[(b as usize) % ALPHABET.len()] as char)
            .collect()
    }

    /// Compute a domain-separated hex-encoded HMAC-SHA256 signature over `"slabs:v1:{domain}\0{payload}"`.
    pub fn sign_with_domain(&self, domain: &str, payload: &str) -> String {
        let mut mac = HmacSha256::new_from_slice(self.secret_key.as_bytes())
            .expect("HMAC accepts keys of any size");
        mac.update(b"slabs:v1:");
        mac.update(domain.as_bytes());
        mac.update(b"\0");
        mac.update(payload.as_bytes());
        hex::encode(mac.finalize().into_bytes())
    }

    /// Verify a domain-separated hex-encoded HMAC-SHA256 signature in constant time.
    pub fn verify_with_domain(&self, domain: &str, payload: &str, signature_hex: &str) -> bool {
        let Ok(sig_bytes) = hex::decode(signature_hex) else {
            return false;
        };
        let Ok(mut mac) = HmacSha256::new_from_slice(self.secret_key.as_bytes()) else {
            return false;
        };
        mac.update(b"slabs:v1:");
        mac.update(domain.as_bytes());
        mac.update(b"\0");
        mac.update(payload.as_bytes());
        mac.verify_slice(&sig_bytes).is_ok()
    }

    /// Compute a hex-encoded HMAC-SHA256 signature for `payload` under the `"raw"` domain.
    pub fn sign(&self, payload: &str) -> String {
        self.sign_with_domain("raw", payload)
    }

    /// Verify a hex-encoded HMAC-SHA256 signature for `payload` under the `"raw"` domain in constant time.
    pub fn verify_signature(&self, payload: &str, signature_hex: &str) -> bool {
        self.verify_with_domain("raw", payload, signature_hex)
    }

    /// Mint a purpose-bound, expiring HMAC-signed token carrying `payload`.
    ///
    /// Encodes `{"p": purpose, "exp": unix_ts, "d": payload}` as URL-safe base64 without padding
    /// and appends `.<hex_hmac_sig>` signed under the `"token"` domain.
    pub fn sign_token<T: Serialize>(
        &self,
        purpose: &str,
        payload: &T,
        ttl: StdDuration,
    ) -> SlabResult<String> {
        let ttl_secs = i64::try_from(ttl.as_secs())
            .map_err(|_| SlabError::bad_request("token ttl exceeds supported range"))?;
        let exp = Utc::now()
            .timestamp()
            .checked_add(ttl_secs)
            .ok_or_else(|| SlabError::bad_request("token expiration timestamp overflow"))?;
        let envelope = SignedTokenEnvelopeRef {
            p: purpose,
            exp,
            d: payload,
        };
        let json = sqlx::types::Json(&envelope)
            .encode_to_string()
            .map_err(|e| SlabError::internal(format!("failed to serialize signed token: {e}")))?;
        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
        let sig = self.sign_with_domain("token", &encoded);
        Ok(format!("{encoded}.{sig}"))
    }

    /// Verify a signed token produced by [`Auth::sign_token`], enforcing purpose and expiration.
    ///
    /// Returns a uniform HTTP `401 Unauthorized` (`"invalid or expired token"`) when the format,
    /// HMAC signature, encoding, payload shape, purpose, or expiration check fails.
    pub fn verify_token<T: DeserializeOwned>(&self, purpose: &str, token: &str) -> SlabResult<T> {
        let invalid = || SlabError::unauthorized("invalid or expired token");

        let Some((encoded, sig)) = token.split_once('.') else {
            return Err(invalid());
        };
        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
            return Err(invalid());
        }
        if !self.verify_with_domain("token", encoded, sig) {
            return Err(invalid());
        }
        let raw = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| invalid())?;
        let envelope = sqlx::types::Json::<SignedTokenEnvelope<T>>::decode_from_bytes(&raw)
            .map_err(|_| invalid())?
            .0;
        if envelope.p != purpose || envelope.exp <= Utc::now().timestamp() {
            return Err(invalid());
        }
        Ok(envelope.d)
    }

    // ---- Browser Sessions ----

    /// Insert a new browser session inside an existing SQLite transaction and return its cookie.
    ///
    /// Rejects `ttl_days` outside `1..=365`.
    pub async fn create_session_in_tx(
        &self,
        tx: &mut Transaction<'_, Sqlite>,
        user_id: &str,
        role: &str,
        ttl_days: i64,
    ) -> SlabResult<(Session, Cookie<'static>)> {
        if !(1..=365).contains(&ttl_days) {
            return Err(SlabError::bad_request(
                "session ttl_days must be between 1 and 365",
            ));
        }

        let session_id = id::new("ses");
        let raw_token = self.generate_token();
        let token_hash = self.hash_token(&raw_token);
        let now = Utc::now();
        let expires = now
            .checked_add_signed(Duration::days(ttl_days))
            .ok_or_else(|| SlabError::bad_request("session expiration timestamp overflow"))?;
        let now_str = utc_timestamp(now);
        let expires_str = utc_timestamp(expires);

        sqlx::query(
            "INSERT INTO slabs_sessions (id, user_id, role, token_hash, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?)",
        )
        .bind(&session_id)
        .bind(user_id)
        .bind(role)
        .bind(&token_hash)
        .bind(&expires_str)
        .bind(&now_str)
        .execute(&mut **tx)
        .await?;

        let cookie = self.build_session_cookie_with_ttl(raw_token, ttl_days);
        let session = Session {
            id: session_id,
            user_id: user_id.to_string(),
            role: role.to_string(),
            expires_at: expires_str,
            created_at: now_str,
        };
        Ok((session, cookie))
    }

    /// Create and persist a new browser session in its own transaction and return its cookie.
    pub async fn create_session(
        &self,
        user_id: &str,
        role: &str,
        ttl_days: i64,
    ) -> SlabResult<(Session, Cookie<'static>)> {
        let mut tx = self.db()?.begin().await?;
        let res = self
            .create_session_in_tx(&mut tx, user_id, role, ttl_days)
            .await?;
        tx.commit().await?;
        Ok(res)
    }

    /// Atomically revoke any existing session cookie in `jar` (checking both `__Host-slabs_session`
    /// and `slabs_session`) and create a new session inside an open `SQLite` transaction.
    ///
    /// Use this on sign-in, sign-up, password reset, or role changes to prevent session fixation
    /// while keeping session rotation atomic with surrounding domain writes.
    pub async fn rotate_session_in_tx(
        &self,
        tx: &mut Transaction<'_, Sqlite>,
        jar: &CookieJar,
        user_id: &str,
        role: &str,
        ttl_days: i64,
    ) -> SlabResult<(Session, Cookie<'static>)> {
        if !(1..=365).contains(&ttl_days) {
            return Err(SlabError::bad_request(
                "session ttl_days must be between 1 and 365",
            ));
        }

        for cookie_name in [HOST_SESSION_COOKIE_NAME, SESSION_COOKIE_NAME] {
            if let Some(cookie) = jar.get(cookie_name) {
                let old_raw = cookie.value();
                if !old_raw.is_empty() {
                    let old_hash = self.hash_token(old_raw);
                    sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
                        .bind(&old_hash)
                        .execute(&mut **tx)
                        .await?;
                }
            }
        }

        self.create_session_in_tx(tx, user_id, role, ttl_days).await
    }

    /// Atomically revoke an existing session token (if present) and create a new session in a single transaction.
    ///
    /// Use this on authentication or privilege changes to prevent session fixation.
    pub async fn rotate_session(
        &self,
        old_raw_token: &str,
        user_id: &str,
        role: &str,
        ttl_days: i64,
    ) -> SlabResult<(Session, Cookie<'static>)> {
        let mut tx = self.db()?.begin().await?;
        if !old_raw_token.is_empty() {
            let old_hash = self.hash_token(old_raw_token);
            sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
                .bind(&old_hash)
                .execute(&mut *tx)
                .await?;
        }
        let res = self
            .create_session_in_tx(&mut tx, user_id, role, ttl_days)
            .await?;
        tx.commit().await?;
        Ok(res)
    }

    /// Look up the active, unexpired [`Session`] for the request's cookie jar, if present.
    pub async fn optional_session(&self, jar: &CookieJar) -> SlabResult<Option<Session>> {
        let Some(cookie) = jar.get(self.session_cookie_name()) else {
            return Ok(None);
        };
        let token_hash = self.hash_token(cookie.value());
        let now_str = utc_timestamp(Utc::now());

        let session: Option<Session> = sqlx::query_as(
            "SELECT id, user_id, role, expires_at, created_at
             FROM slabs_sessions
             WHERE token_hash = ? AND expires_at > ?",
        )
        .bind(&token_hash)
        .bind(&now_str)
        .fetch_optional(self.db()?.reader())
        .await?;

        Ok(session)
    }

    /// Require a valid browser session from `jar`, failing with HTTP 401 if unauthenticated.
    pub async fn require_session(&self, jar: &CookieJar) -> SlabResult<Session> {
        self.optional_session(jar)
            .await?
            .ok_or_else(|| SlabError::unauthorized("authentication required"))
    }

    /// Require a valid browser session with the `"admin"` role, failing with HTTP 401 or 403 otherwise.
    pub async fn require_admin(&self, jar: &CookieJar) -> SlabResult<Session> {
        let session = self.require_session(jar).await?;
        if session.role != "admin" {
            return Err(SlabError::forbidden("administrator role required"));
        }
        Ok(session)
    }

    /// Delete the current session from the database (if present) and return a removal cookie.
    pub async fn destroy_session(&self, jar: &CookieJar) -> SlabResult<Cookie<'static>> {
        if let Some(cookie) = jar.get(self.session_cookie_name()) {
            let token_hash = self.hash_token(cookie.value());
            sqlx::query("DELETE FROM slabs_sessions WHERE token_hash = ?")
                .bind(&token_hash)
                .execute(self.db()?.pool())
                .await?;
        }
        Ok(self.clear_session_cookie())
    }

    /// Delete all active browser sessions belonging to `user_id` and return the number of sessions removed.
    pub async fn destroy_user_sessions(&self, user_id: &str) -> SlabResult<u64> {
        let res = sqlx::query("DELETE FROM slabs_sessions WHERE user_id = ?")
            .bind(user_id)
            .execute(self.db()?.pool())
            .await?;
        Ok(res.rows_affected())
    }

    /// Delete all browser sessions (`slabs_sessions`) and personal access tokens
    /// (`slabs_access_tokens`) belonging to `user_id` inside an open `SQLite` transaction.
    ///
    /// Returns the total number of revoked session and access-token rows. Use this on password
    /// changes, account deactivation, or privilege revocation so every active credential is
    /// invalidated atomically with the user update.
    pub async fn revoke_all_for_user_in_tx(
        &self,
        tx: &mut Transaction<'_, Sqlite>,
        user_id: &str,
    ) -> SlabResult<u64> {
        let sessions = sqlx::query("DELETE FROM slabs_sessions WHERE user_id = ?")
            .bind(user_id)
            .execute(&mut **tx)
            .await?;
        let tokens = sqlx::query("DELETE FROM slabs_access_tokens WHERE user_id = ?")
            .bind(user_id)
            .execute(&mut **tx)
            .await?;
        Ok(sessions
            .rows_affected()
            .saturating_add(tokens.rows_affected()))
    }

    /// Delete all expired session rows from `slabs_sessions` and return the number of rows removed.
    pub async fn cleanup_expired_sessions(&self) -> SlabResult<u64> {
        let now_str = utc_timestamp(Utc::now());
        let res = sqlx::query("DELETE FROM slabs_sessions WHERE expires_at <= ?")
            .bind(&now_str)
            .execute(self.db()?.pool())
            .await?;
        Ok(res.rows_affected())
    }

    /// Build an `HttpOnly`, `SameSite=Lax` session cookie carrying `raw_token` with an explicit `Max-Age` in days (clamped to `1..=365`).
    pub fn build_session_cookie_with_ttl(
        &self,
        raw_token: impl Into<String>,
        ttl_days: i64,
    ) -> Cookie<'static> {
        let clamped_days = ttl_days.clamp(1, 365);
        Cookie::build((self.session_cookie_name(), raw_token.into()))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(self.cookie_secure)
            .max_age(time::Duration::days(clamped_days))
            .build()
    }

    /// Build an `HttpOnly`, `SameSite=Lax` session cookie carrying `raw_token` with a default 30-day `Max-Age`.
    pub fn build_session_cookie(&self, raw_token: impl Into<String>) -> Cookie<'static> {
        self.build_session_cookie_with_ttl(raw_token, DEFAULT_SESSION_TTL_DAYS)
    }

    /// Build an expired removal cookie that clears the browser session cookie.
    pub fn clear_session_cookie(&self) -> Cookie<'static> {
        let mut cookie = Cookie::build((self.session_cookie_name(), ""))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(self.cookie_secure)
            .build();
        cookie.make_removal();
        cookie
    }

    // ---- Passwordless Magic Links (extracted from Fizzy) ----

    fn hash_magic_link_code(&self, email_lower: &str, purpose: &str, code: &str) -> String {
        self.sign_with_domain("magic_link", &format!("{email_lower}\0{purpose}\0{code}"))
    }

    /// Issue an expiring 6-character magic link code bound to `(email, purpose)` and store its keyed HMAC digest in `slabs_magic_links`.
    ///
    /// Deletes any prior pending codes for `(email, purpose)` in the same transaction.
    /// Rejects `ttl_minutes` outside `1..=1440`.
    pub async fn issue_magic_link(
        &self,
        email: &str,
        purpose: &str,
        ttl_minutes: i64,
    ) -> SlabResult<MagicLinkIssued> {
        if !(1..=1440).contains(&ttl_minutes) {
            return Err(SlabError::bad_request(
                "magic link ttl_minutes must be between 1 and 1440",
            ));
        }

        let link_id = id::new("mlk");
        let code = self.generate_short_code(6);
        let email = email.trim().to_lowercase();
        let code_hash = self.hash_magic_link_code(&email, purpose, &code);
        let now = Utc::now();
        let expires = now
            .checked_add_signed(Duration::minutes(ttl_minutes))
            .ok_or_else(|| SlabError::bad_request("magic link expiration timestamp overflow"))?;
        let expires_at = utc_timestamp(expires);
        let created_at = utc_timestamp(now);

        let mut tx = self.db()?.begin().await?;
        sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
            .bind(&email)
            .bind(purpose)
            .execute(&mut *tx)
            .await?;

        sqlx::query(
            "INSERT INTO slabs_magic_links (id, email, purpose, code_hash, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?)",
        )
        .bind(&link_id)
        .bind(&email)
        .bind(purpose)
        .bind(&code_hash)
        .bind(&expires_at)
        .bind(&created_at)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;

        Ok(MagicLinkIssued {
            id: link_id,
            email,
            purpose: purpose.to_string(),
            code,
            expires_at,
        })
    }

    fn record_magic_link_failure(&self, fail_key: &str) -> u32 {
        let now = Instant::now();
        let mut guard = self
            .magic_link_failures
            .lock()
            .expect("magic link failure tracker mutex poisoned");
        if guard.len() > 10_000 {
            guard.retain(|_, (_, first_failed)| {
                now.saturating_duration_since(*first_failed) < MAGIC_LINK_LOCKOUT_WINDOW
            });
        }
        let entry = guard.entry(fail_key.to_string()).or_insert((0, now));
        if now.saturating_duration_since(entry.1) >= MAGIC_LINK_LOCKOUT_WINDOW {
            entry.0 = 0;
            entry.1 = now;
        }
        entry.0 = entry.0.saturating_add(1);
        entry.0
    }

    fn is_magic_link_locked_out(&self, fail_key: &str) -> bool {
        let now = Instant::now();
        let mut guard = self
            .magic_link_failures
            .lock()
            .expect("magic link failure tracker mutex poisoned");
        if let Some((count, first_failed)) = guard.get(fail_key).copied() {
            if now.saturating_duration_since(first_failed) >= MAGIC_LINK_LOCKOUT_WINDOW {
                guard.remove(fail_key);
                return false;
            }
            return count >= MAGIC_LINK_MAX_ATTEMPTS;
        }
        false
    }

    fn clear_magic_link_failures(&self, fail_key: &str) {
        let mut guard = self
            .magic_link_failures
            .lock()
            .expect("magic link failure tracker mutex poisoned");
        guard.remove(fail_key);
    }

    /// Atomically consume a valid, unexpired magic link code bound to `email` and `purpose`.
    ///
    /// Returns `Ok(Some(MagicLinkConsumed))` on success, or `Ok(None)` if the code is invalid,
    /// expired, mismatched, or locked out. After 5 failed attempts within 15 minutes for a given
    /// `(email, purpose)`, any pending magic links for that pair are deleted.
    pub async fn consume_magic_link(
        &self,
        email: &str,
        purpose: &str,
        raw_code: &str,
    ) -> SlabResult<Option<MagicLinkConsumed>> {
        let email_lower = email.trim().to_lowercase();
        let fail_key = format!("{email_lower}\0{purpose}");

        if self.is_magic_link_locked_out(&fail_key) {
            sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
                .bind(&email_lower)
                .bind(purpose)
                .execute(self.db()?.pool())
                .await?;
            return Ok(None);
        }

        let sanitized: String = raw_code
            .chars()
            .filter(char::is_ascii_alphanumeric)
            .map(|c| c.to_ascii_uppercase())
            .collect();

        if sanitized.is_empty() {
            if self.record_magic_link_failure(&fail_key) >= MAGIC_LINK_MAX_ATTEMPTS {
                sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
                    .bind(&email_lower)
                    .bind(purpose)
                    .execute(self.db()?.pool())
                    .await?;
            }
            return Ok(None);
        }

        let code_hash = self.hash_magic_link_code(&email_lower, purpose, &sanitized);
        let now_str = utc_timestamp(Utc::now());

        let consumed: Option<(String, String, String)> = sqlx::query_as(
            "DELETE FROM slabs_magic_links
             WHERE email = ? AND purpose = ? AND code_hash = ? AND expires_at > ?
             RETURNING id, email, purpose",
        )
        .bind(&email_lower)
        .bind(purpose)
        .bind(&code_hash)
        .bind(&now_str)
        .fetch_optional(self.db()?.pool())
        .await?;

        let Some((id, email, purpose)) = consumed else {
            if self.record_magic_link_failure(&fail_key) >= MAGIC_LINK_MAX_ATTEMPTS {
                sqlx::query("DELETE FROM slabs_magic_links WHERE email = ? AND purpose = ?")
                    .bind(&email_lower)
                    .bind(purpose)
                    .execute(self.db()?.pool())
                    .await?;
            }
            return Ok(None);
        };

        self.clear_magic_link_failures(&fail_key);
        Ok(Some(MagicLinkConsumed { id, email, purpose }))
    }

    /// Delete all expired magic link rows and return the number of rows removed.
    pub async fn cleanup_expired_magic_links(&self) -> SlabResult<u64> {
        let now_str = utc_timestamp(Utc::now());
        let res = sqlx::query("DELETE FROM slabs_magic_links WHERE expires_at <= ?")
            .bind(&now_str)
            .execute(self.db()?.pool())
            .await?;
        Ok(res.rows_affected())
    }

    // ---- Personal Access Tokens / Bearer Auth (extracted from Fizzy for CLIs & Agents) ----

    /// Issue a personal access token prefixed with `slb_` and optional expiration in days.
    ///
    /// Validates that `permission` is `"read"` or `"write"`, and stores only the SHA-256 hex digest.
    pub async fn issue_access_token_with_expiry(
        &self,
        user_id: &str,
        role: &str,
        description: &str,
        permission: &str,
        ttl_days: Option<i64>,
    ) -> SlabResult<AccessTokenIssued> {
        if permission != "read" && permission != "write" {
            return Err(SlabError::validation(
                "permission",
                "must be \"read\" or \"write\"",
            ));
        }

        let now = Utc::now();
        let expires_at = match ttl_days {
            Some(days) => {
                if !(1..=3650).contains(&days) {
                    return Err(SlabError::bad_request(
                        "access token ttl_days must be between 1 and 3650",
                    ));
                }
                let exp = now
                    .checked_add_signed(Duration::days(days))
                    .ok_or_else(|| {
                        SlabError::bad_request("access token expiration timestamp overflow")
                    })?;
                Some(utc_timestamp(exp))
            }
            None => None,
        };

        let token_id = id::new("pat");
        let raw_token = format!("slb_{}", self.generate_token());
        let token_hash = self.hash_token(&raw_token);
        let created_at = utc_timestamp(now);

        sqlx::query(
            "INSERT INTO slabs_access_tokens (id, user_id, role, description, permission, token_hash, expires_at, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&token_id)
        .bind(user_id)
        .bind(role)
        .bind(description)
        .bind(permission)
        .bind(&token_hash)
        .bind(&expires_at)
        .bind(&created_at)
        .execute(self.db()?.pool())
        .await?;

        Ok(AccessTokenIssued {
            id: token_id,
            user_id: user_id.to_string(),
            description: description.to_string(),
            permission: permission.to_string(),
            token: raw_token,
        })
    }

    /// Issue a non-expiring personal access token prefixed with `slb_` and store its SHA-256 hash in `slabs_access_tokens`.
    ///
    /// Validates that `permission` is `"read"` or `"write"`.
    pub async fn issue_access_token(
        &self,
        user_id: &str,
        role: &str,
        description: &str,
        permission: &str,
    ) -> SlabResult<AccessTokenIssued> {
        self.issue_access_token_with_expiry(user_id, role, description, permission, None)
            .await
    }

    /// Revoke a personal access token owned by `user_id`, returning `Ok(true)` if a row was deleted.
    pub async fn revoke_access_token(&self, token_id: &str, user_id: &str) -> SlabResult<bool> {
        let res = sqlx::query("DELETE FROM slabs_access_tokens WHERE id = ? AND user_id = ?")
            .bind(token_id)
            .bind(user_id)
            .execute(self.db()?.pool())
            .await?;
        Ok(res.rows_affected() > 0)
    }

    /// Authenticate via `Authorization: Bearer <token>` or the session cookie.
    ///
    /// When a `Bearer` header is present, this method validates only that token on the read pool,
    /// debounces `last_used_at` writes to at most once every 5 minutes, and returns `Ok(None)` if invalid.
    pub async fn optional_auth(
        &self,
        jar: &CookieJar,
        headers: &HeaderMap,
    ) -> SlabResult<Option<Principal>> {
        if let Some(auth_hdr) = headers
            .get(header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
        {
            if let Some(raw_token) = auth_hdr
                .strip_prefix("Bearer ")
                .or_else(|| auth_hdr.strip_prefix("bearer "))
            {
                let token_hash = self.hash_token(raw_token.trim());
                let now = Utc::now();
                let now_str = utc_timestamp(now);

                let db = self.db()?;
                let row: Option<(String, String, String, String, Option<String>)> = sqlx::query_as(
                    "SELECT id, user_id, role, permission, last_used_at
                     FROM slabs_access_tokens
                     WHERE token_hash = ? AND (expires_at IS NULL OR expires_at > ?)",
                )
                .bind(&token_hash)
                .bind(&now_str)
                .fetch_optional(db.reader())
                .await?;

                if let Some((token_id, user_id, role, permission, last_used_at)) = row {
                    let should_update_last_used = match last_used_at.as_deref() {
                        None => true,
                        Some(ts) => DateTime::parse_from_rfc3339(ts).map_or(true, |parsed| {
                            now.signed_duration_since(parsed.with_timezone(&Utc))
                                .num_seconds()
                                >= ACCESS_TOKEN_LAST_USED_DEBOUNCE_SECS
                        }),
                    };

                    if should_update_last_used {
                        let _ = sqlx::query(
                            "UPDATE slabs_access_tokens SET last_used_at = ? WHERE id = ?",
                        )
                        .bind(&now_str)
                        .bind(&token_id)
                        .execute(db.pool())
                        .await;
                    }

                    return Ok(Some(Principal {
                        user_id,
                        role,
                        auth_kind: "bearer".to_string(),
                        permission,
                    }));
                }
                return Ok(None);
            }
        }

        if let Some(session) = self.optional_session(jar).await? {
            return Ok(Some(Principal {
                user_id: session.user_id,
                role: session.role,
                auth_kind: "session".to_string(),
                permission: "write".to_string(),
            }));
        }

        Ok(None)
    }

    /// Require authentication via either session cookie or `Authorization: Bearer` token.
    pub async fn require_auth(
        &self,
        jar: &CookieJar,
        headers: &HeaderMap,
    ) -> SlabResult<Principal> {
        self.optional_auth(jar, headers).await?.ok_or_else(|| {
            SlabError::unauthorized("authentication required (session cookie or Bearer token)")
        })
    }

    /// Require an authenticated [`Principal`] with `"write"` permission.
    pub async fn require_write_auth(
        &self,
        jar: &CookieJar,
        headers: &HeaderMap,
    ) -> SlabResult<Principal> {
        let principal = self.require_auth(jar, headers).await?;
        if principal.permission != "write" {
            return Err(SlabError::forbidden(
                "access token does not have write permission",
            ));
        }
        Ok(principal)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    struct InvitePayload {
        user_id: String,
        org_id: String,
    }

    fn test_auth() -> Auth {
        Auth::for_signing("unit-test-secret-key-for-signed-tokens", false)
    }

    async fn db_auth(cookie_secure: bool) -> (Db, Auth) {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();
        let auth = Auth::new(
            db.clone(),
            "unit-test-secret-key-for-db-auth",
            cookie_secure,
        );
        (db, auth)
    }

    #[tokio::test]
    async fn async_argon2id_hashes_verifies_and_enforces_limits() {
        let auth = test_auth();
        let hash = auth.hash_password("correct-horse-battery").await.unwrap();
        assert!(hash.starts_with("$argon2id$"));

        assert!(auth
            .verify_password("correct-horse-battery", &hash)
            .await
            .unwrap());
        assert!(!auth.verify_password("wrong-password", &hash).await.unwrap());

        // Constant-time verify handles both Some and None without erroring.
        assert!(auth
            .verify_password_constant_time("correct-horse-battery", Some(&hash))
            .await
            .unwrap());
        assert!(!auth
            .verify_password_constant_time("correct-horse-battery", None)
            .await
            .unwrap());

        // Non-Argon2id algorithm string must be rejected.
        let argon2i_hash = hash.replacen("$argon2id$", "$argon2i$", 1);
        assert!(!auth
            .verify_password("correct-horse-battery", &argon2i_hash)
            .await
            .unwrap());

        // Passwords over 1024 bytes are rejected with 400 Bad Request.
        let oversized = "a".repeat(1025);
        assert_eq!(
            auth.hash_password(&oversized)
                .await
                .unwrap_err()
                .status_code(),
            http::StatusCode::BAD_REQUEST
        );
        assert_eq!(
            auth.verify_password(&oversized, &hash)
                .await
                .unwrap_err()
                .status_code(),
            http::StatusCode::BAD_REQUEST
        );
        assert_eq!(
            auth.verify_password_constant_time(&oversized, None)
                .await
                .unwrap_err()
                .status_code(),
            http::StatusCode::BAD_REQUEST
        );
    }

    #[test]
    fn domain_separated_hmac_prevents_cross_domain_reuse() {
        let auth = test_auth();
        let raw_sig = auth.sign("payload");
        assert!(auth.verify_signature("payload", &raw_sig));
        assert!(auth.verify_with_domain("raw", "payload", &raw_sig));
        assert!(!auth.verify_with_domain("token", "payload", &raw_sig));
        assert!(!auth.verify_with_domain("magic_link", "payload", &raw_sig));

        let token_sig = auth.sign_with_domain("token", "payload");
        assert_ne!(raw_sig, token_sig);
        assert!(auth.verify_with_domain("token", "payload", &token_sig));
        assert!(!auth.verify_signature("payload", &token_sig));
    }

    #[test]
    fn sign_and_verify_token_roundtrip_and_uniform_errors() {
        let auth = test_auth();
        let payload = InvitePayload {
            user_id: "usr_01".to_string(),
            org_id: "org_42".to_string(),
        };

        let token = auth
            .sign_token("invite", &payload, StdDuration::from_secs(300))
            .unwrap();
        let decoded: InvitePayload = auth.verify_token("invite", &token).unwrap();
        assert_eq!(decoded, payload);

        // Wrong purpose, tampered signature, bad format, and expired tokens all return uniform 401.
        let wrong_purpose = auth
            .verify_token::<InvitePayload>("other", &token)
            .unwrap_err();
        let (encoded, sig) = token.split_once('.').unwrap();
        let flipped = if sig.starts_with('a') { 'b' } else { 'a' };
        let tampered_tok = format!("{encoded}.{flipped}{}", &sig[1..]);
        let tampered = auth
            .verify_token::<InvitePayload>("invite", &tampered_tok)
            .unwrap_err();
        let bad_fmt = auth
            .verify_token::<InvitePayload>("invite", "not-a-token")
            .unwrap_err();
        let expired_tok = auth
            .sign_token("invite", &payload, StdDuration::ZERO)
            .unwrap();
        let expired = auth
            .verify_token::<InvitePayload>("invite", &expired_tok)
            .unwrap_err();

        for err in [wrong_purpose, tampered, bad_fmt, expired] {
            assert_eq!(err.status_code(), http::StatusCode::UNAUTHORIZED);
            assert_eq!(err.to_string(), "unauthorized: invalid or expired token");
        }
    }

    #[tokio::test]
    async fn session_cookie_prefix_rotation_and_cleanup() {
        let (_db, secure_auth) = db_auth(true).await;
        assert_eq!(secure_auth.session_cookie_name(), "__Host-slabs_session");

        let (ses1, cookie1) = secure_auth
            .create_session("usr_1", "member", 7)
            .await
            .unwrap();
        assert_eq!(cookie1.name(), "__Host-slabs_session");
        assert_eq!(cookie1.secure(), Some(true));
        assert_eq!(cookie1.max_age(), Some(time::Duration::days(7)));

        let jar1 = CookieJar::new().add(cookie1.clone());
        let fetched = secure_auth.optional_session(&jar1).await.unwrap().unwrap();
        assert_eq!(fetched.id, ses1.id);

        // Rotate invalidates old session and creates a new one atomically.
        let (ses2, cookie2) = secure_auth
            .rotate_session(cookie1.value(), "usr_1", "admin", 14)
            .await
            .unwrap();
        assert_ne!(ses1.id, ses2.id);
        assert!(secure_auth.optional_session(&jar1).await.unwrap().is_none());

        let jar2 = CookieJar::new().add(cookie2);
        let fetched2 = secure_auth.optional_session(&jar2).await.unwrap().unwrap();
        assert_eq!(fetched2.role, "admin");

        // Reject invalid TTLs.
        assert!(secure_auth
            .create_session("usr_1", "member", 0)
            .await
            .is_err());
        assert!(secure_auth
            .create_session("usr_1", "member", 366)
            .await
            .is_err());

        // Destroy all sessions for user.
        let removed = secure_auth.destroy_user_sessions("usr_1").await.unwrap();
        assert_eq!(removed, 1);
        assert!(secure_auth.optional_session(&jar2).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn magic_link_binds_email_purpose_and_locks_out_after_five_failures() {
        let (_db, auth) = db_auth(false).await;
        let issued = auth
            .issue_magic_link("Alice@Example.com", "sign_in", 15)
            .await
            .unwrap();

        // Debug redacts the code.
        let dbg = format!("{issued:?}");
        assert!(!dbg.contains(&issued.code));
        assert!(dbg.contains("[REDACTED]"));

        // Wrong email or wrong purpose fails to consume the valid code.
        assert!(auth
            .consume_magic_link("bob@example.com", "sign_in", &issued.code)
            .await
            .unwrap()
            .is_none());
        assert!(auth
            .consume_magic_link("alice@example.com", "reset_password", &issued.code)
            .await
            .unwrap()
            .is_none());

        // 5 failed attempts for (alice@example.com, sign_in) lock out and delete the pending code.
        for _ in 0..5 {
            assert!(auth
                .consume_magic_link("alice@example.com", "sign_in", "ZZZZZZ")
                .await
                .unwrap()
                .is_none());
        }
        // Now even the real code is rejected because the lockout deleted it.
        assert!(auth
            .consume_magic_link("alice@example.com", "sign_in", &issued.code)
            .await
            .unwrap()
            .is_none());

        // A separate email/purpose still succeeds when matching email, purpose, and code.
        let issued2 = auth
            .issue_magic_link("charlie@example.com", "sign_in", 15)
            .await
            .unwrap();
        let consumed = auth
            .consume_magic_link("CHARLIE@example.com", "sign_in", &issued2.code)
            .await
            .unwrap()
            .expect("valid code should consume");
        assert_eq!(consumed.email, "charlie@example.com");
        assert_eq!(consumed.purpose, "sign_in");

        // Replaying the same code fails (single-use).
        assert!(auth
            .consume_magic_link("charlie@example.com", "sign_in", &issued2.code)
            .await
            .unwrap()
            .is_none());
    }

    #[tokio::test]
    async fn access_token_validates_permission_expiry_revocation_and_debug_redaction() {
        let (_db, auth) = db_auth(false).await;

        assert!(auth
            .issue_access_token("usr_1", "member", "bad", "admin")
            .await
            .is_err());

        let issued = auth
            .issue_access_token_with_expiry("usr_1", "member", "cli", "read", Some(7))
            .await
            .unwrap();
        let dbg = format!("{issued:?}");
        assert!(!dbg.contains(&issued.token));
        assert!(dbg.contains("[REDACTED]"));

        let mut headers = HeaderMap::new();
        headers.insert(
            header::AUTHORIZATION,
            format!("Bearer {}", issued.token).parse().unwrap(),
        );
        let jar = CookieJar::new();
        let principal = auth.optional_auth(&jar, &headers).await.unwrap().unwrap();
        assert_eq!(principal.user_id, "usr_1");
        assert_eq!(principal.permission, "read");

        // Wrong owner cannot revoke token.
        assert!(!auth.revoke_access_token(&issued.id, "usr_2").await.unwrap());
        assert!(auth.revoke_access_token(&issued.id, "usr_1").await.unwrap());
        assert!(auth.optional_auth(&jar, &headers).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn rotate_session_in_tx_replaces_host_and_plain_cookies_atomically() {
        let (db, secure_auth) = db_auth(true).await;
        let plain_auth = Auth::new(db.clone(), "unit-test-secret-key-for-db-auth", false);

        let (host_ses, host_cookie) = secure_auth
            .create_session("usr_1", "member", 7)
            .await
            .unwrap();
        let (plain_ses, plain_cookie) = plain_auth
            .create_session("usr_1", "member", 7)
            .await
            .unwrap();

        let jar_both = CookieJar::new()
            .add(host_cookie.clone())
            .add(plain_cookie.clone());

        // Rolled-back rotation keeps old sessions alive.
        let mut rollback_tx = db.begin().await.unwrap();
        let _ = secure_auth
            .rotate_session_in_tx(&mut rollback_tx, &jar_both, "usr_1", "admin", 14)
            .await
            .unwrap();
        rollback_tx.rollback().await.unwrap();
        assert!(secure_auth
            .optional_session(&CookieJar::new().add(host_cookie.clone()))
            .await
            .unwrap()
            .is_some());
        assert!(plain_auth
            .optional_session(&CookieJar::new().add(plain_cookie.clone()))
            .await
            .unwrap()
            .is_some());

        // Committed rotation deletes both old cookies and activates the new session.
        let mut tx = db.begin().await.unwrap();
        let (new_ses, new_cookie) = secure_auth
            .rotate_session_in_tx(&mut tx, &jar_both, "usr_1", "admin", 14)
            .await
            .unwrap();
        tx.commit().await.unwrap();

        assert_ne!(new_ses.id, host_ses.id);
        assert_ne!(new_ses.id, plain_ses.id);
        assert!(secure_auth
            .optional_session(&CookieJar::new().add(host_cookie))
            .await
            .unwrap()
            .is_none());
        assert!(plain_auth
            .optional_session(&CookieJar::new().add(plain_cookie))
            .await
            .unwrap()
            .is_none());

        let new_jar = CookieJar::new().add(new_cookie);
        let active = secure_auth
            .optional_session(&new_jar)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(active.id, new_ses.id);
        assert_eq!(active.role, "admin");
    }

    #[tokio::test]
    async fn revoke_all_for_user_in_tx_deletes_sessions_and_access_tokens_only_for_target_user() {
        let (db, auth) = db_auth(false).await;

        let (_, c1) = auth
            .create_session("usr_target", "member", 7)
            .await
            .unwrap();
        let (_, c2) = auth
            .create_session("usr_target", "member", 7)
            .await
            .unwrap();
        let pat = auth
            .issue_access_token("usr_target", "member", "cli", "write")
            .await
            .unwrap();

        let (_, other_cookie) = auth.create_session("usr_other", "member", 7).await.unwrap();
        let other_pat = auth
            .issue_access_token("usr_other", "member", "cli", "write")
            .await
            .unwrap();

        let mut tx = db.begin().await.unwrap();
        let revoked = auth
            .revoke_all_for_user_in_tx(&mut tx, "usr_target")
            .await
            .unwrap();
        tx.commit().await.unwrap();
        assert_eq!(revoked, 3);

        // Target user's sessions and bearer tokens are all revoked.
        assert!(auth
            .optional_session(&CookieJar::new().add(c1))
            .await
            .unwrap()
            .is_none());
        assert!(auth
            .optional_session(&CookieJar::new().add(c2))
            .await
            .unwrap()
            .is_none());
        let mut target_headers = HeaderMap::new();
        target_headers.insert(
            header::AUTHORIZATION,
            format!("Bearer {}", pat.token).parse().unwrap(),
        );
        assert!(auth
            .optional_auth(&CookieJar::new(), &target_headers)
            .await
            .unwrap()
            .is_none());

        // Other user's session and bearer token remain valid.
        assert!(auth
            .optional_session(&CookieJar::new().add(other_cookie))
            .await
            .unwrap()
            .is_some());
        let mut other_headers = HeaderMap::new();
        other_headers.insert(
            header::AUTHORIZATION,
            format!("Bearer {}", other_pat.token).parse().unwrap(),
        );
        assert!(auth
            .optional_auth(&CookieJar::new(), &other_headers)
            .await
            .unwrap()
            .is_some());
    }
}