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
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
//! Grant credential — grant + Proof-of-Possession + opaque session bearer.
//!
//! This is the **default** session credential. A user-signed grant JWS is
//! exchanged at the homeserver for a short-lived opaque bearer and a session
//! record. The SDK refreshes the bearer transparently using the stored grant
//! and a fresh `PoP` proof.

use std::any::Any;
use std::fmt;
use std::sync::Arc;

use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use pubky_common::{
    auth::{
        grant::GrantClaims,
        grant_session_responses::{GrantSessionInfo, GrantSessionResponse},
        jws::{POP_JWS_TYP, PopNonce},
        pop::PopProofClaims,
    },
    crypto::{Keypair, PublicKey},
    encryption_keys::ScopedEncryptionKeyBundle,
};

use reqwest::{Method, RequestBuilder, StatusCode};
use tokio::sync::Mutex;
use zeroize::Zeroizing;

#[cfg(target_arch = "wasm32")]
use super::shared_session::GrantSessionLease;
use super::{
    approval::{GrantApproval, SignedApproval, VerifiedApproval},
    grant_exchange::{credential_from_grant_exchange, refresh_grant_session},
    pop_signer::{DelegatedSignFn, GrantPopSigner},
    shared_session::GrantSessionCoordinator,
};
use crate::actors::session::core::PubkySession;
use crate::actors::session::credential::{SessionCredential, credential_session_missing};
use crate::{
    PubkyHttpClient,
    actors::session::SessionInfo,
    cross_log,
    errors::{AuthError, CredentialRefreshError, Error, RequestError, Result},
};

/// Refresh the bearer proactively when it has less than this many seconds left.
pub(crate) const REFRESH_SLACK_SECS: u64 = 300;

const GRANT_SESSION_PATH: &str = "/auth/grant/session";
const STORED_GRANT_CREDENTIAL_PREFIX: &str = "pubky-grant-credential-v1";
const STORED_GRANT_CREDENTIAL_APPROVAL_PREFIX: &str = "pubky-grant-credential-v2";
const STORED_GRANT_CREDENTIAL_PREFIX_FAMILY: &str = "pubky-grant-credential-";

/// Current Unix timestamp in seconds, cross-target.
pub(crate) fn now_unix() -> u64 {
    web_time::SystemTime::now()
        .duration_since(web_time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .expect("System time duration_since should always valid")
}

/// Mutable grant credential state. Always wrapped in `Arc<Mutex<...>>`.
///
/// Refresh paths take the mutex and hold it across the HTTP call so
/// concurrent refreshes don't run into a race condition.
#[derive(Debug)]
pub(crate) struct GrantCredentialState {
    /// Current opaque bearer token (homeserver-issued).
    pub bearer: String,
    /// The grant JWS used to mint this and future bearers (refresh material).
    pub grant_jws: String,
    /// Decoded grant claims — exposes `iss`, `client_id`, `cnf`, `jti`, …
    pub grant_claims: GrantClaims,
    /// `PoP` signer bound to the grant's `cnf` claim. Signs refresh proofs.
    pub client_signer: GrantPopSigner,
    /// Homeserver public key (`PoP` audience).
    pub homeserver_pk: PublicKey,
    /// Latest server-reported session metadata.
    pub session: GrantSessionInfo,
    pub coordinator: Option<Arc<dyn GrantSessionCoordinator>>,
}

impl GrantCredentialState {
    pub(super) fn needs_refresh(&self, now: u64, slack: u64) -> bool {
        // Refresh cannot extend a valid bearer that already reaches grant expiry.
        self.session.token_expires_at <= now
            || (self.session.token_expires_at < self.grant_claims.exp
                && self.session.token_expires_at.saturating_sub(slack) <= now)
    }
}

/// Cheap-to-clone grant credential. The mutable token state is shared across
/// clones via `Arc<Mutex<…>>` so every `PubkySession` clone observes the
/// same refreshes. Session info is derived from the immutable grant and
/// never changes.
#[derive(Clone, Debug)]
pub struct GrantCredential {
    pub(crate) state: Arc<Mutex<GrantCredentialState>>,
    pub(crate) info: SessionInfo,
    /// None for bare grants; Some for signed approvals, even with no `e` scopes.
    /// Retaining an empty bundle preserves the approval format during export.
    verified_approval: Option<Arc<VerifiedApproval>>,
}

/// Validated restore inputs, including keys verified against the stored grant.
#[derive(Debug)]
struct GrantRestoreMaterial {
    grant_jws: String,
    grant_claims: GrantClaims,
    client_signer: GrantPopSigner,
    homeserver_pk: PublicKey,
    verified_approval: Option<VerifiedApproval>,
}

/// Durable refresh material for restoring a grant-backed session.
///
/// Portable restore material without a bearer or cached session metadata.
/// Generic restore exchanges it for a fresh bearer; browser restore can reuse
/// the bearer saved separately in `IndexedDB`. Encryption keys can also be
/// recovered offline.
///
/// Treat values of this type as bearer-equivalent secrets. Embedded encryption
/// keys remain confidential after the underlying grant expires or is revoked.
#[derive(Clone)]
struct StoredGrantCredential {
    /// User-signed grant JWS.
    grant_jws: String,
    /// Secret bytes for the `PoP` client keypair bound by the grant `cnf`.
    client_key_secret: [u8; 32],
    /// Homeserver public key used as the `PoP` audience.
    homeserver_pk: PublicKey,
    signed_approval: Option<SignedApproval>,
}

/// Non-secret durable metadata for browser delegated grant restore.
#[derive(Clone, PartialEq, Eq)]
pub struct DelegatedGrantCredentialState {
    /// User-signed grant JWS.
    pub grant_jws: String,
    /// Homeserver public key used as the `PoP` audience.
    pub homeserver_pk: PublicKey,
    /// `IndexedDB` key id for the non-extractable private `CryptoKey`.
    pub key_id: String,
    /// Public key for the delegated `PoP` signer.
    pub client_pk: PublicKey,
}

impl fmt::Debug for DelegatedGrantCredentialState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DelegatedGrantCredentialState")
            .field("grant_jws", &"<redacted>")
            .field("homeserver_pk", &self.homeserver_pk)
            .field("key_id", &self.key_id)
            .field("client_pk", &self.client_pk)
            .finish()
    }
}

impl fmt::Debug for StoredGrantCredential {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StoredGrantCredential")
            .field("grant_jws", &"<redacted>")
            .field("client_key_secret", &"<redacted>")
            .field("homeserver_pk", &self.homeserver_pk)
            .field("signed_approval", &self.signed_approval)
            .finish()
    }
}

impl StoredGrantCredential {
    /// Encode this credential as a compact token suitable for secure storage.
    fn encode(&self) -> String {
        let secret = Zeroizing::new(URL_SAFE_NO_PAD.encode(self.client_key_secret));
        match &self.signed_approval {
            Some(approval) => format!(
                "{STORED_GRANT_CREDENTIAL_APPROVAL_PREFIX}:{}:{}:{}:{}",
                self.homeserver_pk.z32(),
                secret.as_str(),
                self.grant_jws,
                approval.as_str(),
            ),
            None => format!(
                "{STORED_GRANT_CREDENTIAL_PREFIX}:{}:{}:{}",
                self.homeserver_pk.z32(),
                secret.as_str(),
                self.grant_jws,
            ),
        }
    }

    /// Decode a compact token produced by [`Self::encode`].
    ///
    /// # Errors
    /// Returns validation errors when the token is malformed or contains an
    /// unsupported version, invalid homeserver key, or invalid client secret.
    fn decode(token: &str) -> Result<Self> {
        // V1 remains authentication-only. V2 appends the confidential signed
        // approval; compact JWS values contain no colon separators.
        let (prefix, rest) = token.split_once(':').ok_or_else(invalid_stored_grant)?;
        if prefix != STORED_GRANT_CREDENTIAL_PREFIX
            && prefix != STORED_GRANT_CREDENTIAL_APPROVAL_PREFIX
        {
            return Err(RequestError::Validation {
                message: "unsupported grant credential token version".into(),
            }
            .into());
        }

        let (homeserver, rest) = rest.split_once(':').ok_or_else(invalid_stored_grant)?;
        let (secret, grant_jws) = rest.split_once(':').ok_or_else(invalid_stored_grant)?;
        let (grant_jws, signed_approval) = if prefix == STORED_GRANT_CREDENTIAL_APPROVAL_PREFIX {
            let (grant, approval) = grant_jws.split_once(':').ok_or_else(invalid_stored_grant)?;
            if approval.is_empty() {
                return Err(invalid_stored_grant().into());
            }
            (grant, Some(SignedApproval::new(approval)))
        } else {
            (grant_jws, None)
        };
        if grant_jws.is_empty() {
            return Err(invalid_stored_grant().into());
        }

        let homeserver_pk =
            PublicKey::try_from_z32(homeserver).map_err(|_err| RequestError::Validation {
                message: "invalid stored grant credential homeserver public key".into(),
            })?;
        let secret = Zeroizing::new(URL_SAFE_NO_PAD.decode(secret).map_err(|_err| {
            RequestError::Validation {
                message: "invalid stored grant credential client secret".into(),
            }
        })?);
        let client_key_secret =
            <[u8; 32]>::try_from(secret.as_slice()).map_err(|_err| RequestError::Validation {
                message: "stored grant credential client secret must be 32 bytes".into(),
            })?;

        Ok(Self {
            grant_jws: grant_jws.to_string(),
            client_key_secret,
            homeserver_pk,
            signed_approval,
        })
    }
}

impl GrantCredential {
    /// Build a grant credential from a `GrantSessionResponse` returned by
    /// `POST /auth/grant/session` or `POST /auth/grant/signup`.
    pub(crate) fn from_response(
        response: GrantSessionResponse,
        grant_jws: String,
        grant_claims: GrantClaims,
        client_signer: GrantPopSigner,
        homeserver_pk: PublicKey,
    ) -> Self {
        let info = to_session_info(&response.session);
        let state = GrantCredentialState {
            bearer: response.token,
            grant_jws,
            grant_claims,
            client_signer,
            homeserver_pk,
            session: response.session,
            coordinator: None,
        };
        Self {
            state: Arc::new(Mutex::new(state)),
            info,
            verified_approval: None,
        }
    }

    /// Read browser restore material without issuing a bearer.
    /// Expired grants remain usable for finishing a pending logout.
    #[doc(hidden)]
    pub fn from_shared_secret(token: &str) -> Result<Self> {
        let material = restore_material(StoredGrantCredential::decode(token)?, true)?;
        Ok(Self::from_shared_material(material))
    }

    /// Read browser-held restore material and verify its confidential approval.
    /// Retains keys without issuing a bearer; expired grants remain usable for logout.
    /// Pass `None` for authentication-only records.
    #[doc(hidden)]
    pub fn from_shared_delegated_state(
        state: DelegatedGrantCredentialState,
        sign: DelegatedSignFn,
        signed_approval: Option<&str>,
    ) -> Result<Self> {
        Ok(Self::from_shared_material(restore_delegated_material(
            state,
            sign,
            true,
            signed_approval,
        )?))
    }

    fn from_shared_material(material: GrantRestoreMaterial) -> Self {
        let GrantRestoreMaterial {
            grant_jws,
            grant_claims: claims,
            client_signer: signer,
            homeserver_pk: homeserver,
            verified_approval,
        } = material;
        let response = GrantSessionResponse {
            token: String::new(),
            session: GrantSessionInfo {
                homeserver: homeserver.clone(),
                pubky: claims.iss.clone(),
                client_id: claims.client_id.clone(),
                capabilities: claims.caps.clone(),
                grant_id: claims.jti.clone(),
                token_expires_at: 0,
                grant_expires_at: claims.exp,
                created_at: 0,
            },
        };
        let mut credential = Self::from_response(response, grant_jws, claims, signer, homeserver);
        credential.retain_verified_approval(verified_approval);
        credential
    }

    async fn exchange_restored_material(
        material: GrantRestoreMaterial,
        client: &PubkyHttpClient,
    ) -> Result<Self> {
        let mut credential = credential_from_grant_exchange(
            client,
            material.grant_jws,
            material.grant_claims,
            material.client_signer,
            material.homeserver_pk,
        )
        .await?;
        credential.retain_verified_approval(material.verified_approval);
        Ok(credential)
    }

    /// Retain scoped keys and their signed recovery approval together.
    pub(crate) fn retain_verified_approval(&mut self, approval: Option<VerifiedApproval>) {
        self.verified_approval = approval.map(Arc::new);
    }

    /// Verified scoped keys received with this approval, if any.
    ///
    /// Bare grants return `None`. Signed approvals return `Some`, with an empty
    /// bundle when no `e` scopes were approved. Storage V1 exports have no bundle;
    /// storage V2 preserves it. Clones share the same zeroizing key storage.
    pub fn encryption_keys(&self) -> Option<&ScopedEncryptionKeyBundle> {
        self.verified_approval
            .as_ref()
            .map(|approval| &approval.encryption_keys)
    }

    /// Snapshot of the current bearer token (released immediately).
    pub(crate) async fn current_bearer(&self) -> String {
        self.state.lock().await.bearer.clone()
    }

    /// Export the portable local secret material needed to restore this credential.
    ///
    /// Sessions with a signed approval export V2 tokens, even if the approved
    /// key bundle is empty. Bare-grant sessions retain the compatible V1 format.
    /// Delivered keys remain sensitive after the grant expires or is revoked.
    ///
    /// Returns `None` for delegated/browser-held `PoP` signers because their
    /// private key material is intentionally not extractable.
    pub async fn export_local_secret(&self) -> Option<String> {
        let state = self.state.lock().await;
        let client_key_secret = state.client_signer.local_secret()?;
        Some(
            StoredGrantCredential {
                grant_jws: state.grant_jws.clone(),
                client_key_secret,
                homeserver_pk: state.homeserver_pk.clone(),
                signed_approval: self
                    .verified_approval
                    .as_ref()
                    .map(|approval| approval.signed_approval.clone()),
            }
            .encode(),
        )
    }

    /// Borrow the confidential signed approval for secure key persistence.
    ///
    /// This may contain raw scoped secrets and must stay outside public metadata.
    /// Persist it alongside delegated restore metadata and pass it to
    /// [`Self::import_delegated_state`] to restore authentication
    /// too, or [`Self::restore_encryption_keys_from_approval`] for offline recovery.
    pub fn signed_approval(&self) -> Option<&str> {
        self.verified_approval
            .as_ref()
            .map(|approval| approval.signed_approval.as_str())
    }

    /// Export non-secret delegated restore metadata for browser-held keys.
    ///
    /// This metadata omits scoped encryption keys; restoring it only restores
    /// authentication.
    pub async fn export_delegated_restore_state(&self) -> Option<DelegatedGrantCredentialState> {
        let state = self.state.lock().await;
        let signer = state.client_signer.delegated_state()?;
        Some(DelegatedGrantCredentialState {
            grant_jws: state.grant_jws.clone(),
            homeserver_pk: state.homeserver_pk.clone(),
            key_id: signer.key_id,
            client_pk: signer.public_key,
        })
    }

    pub(crate) fn is_secret_token(token: &str) -> bool {
        token.starts_with(STORED_GRANT_CREDENTIAL_PREFIX_FAMILY)
    }

    /// Recover scoped encryption keys from a local secret token entirely offline.
    ///
    /// Verifies the signed approval, its exact grant binding, and key scopes.
    /// Bare-grant (storage V1) tokens return `None`. Signed approvals without
    /// `e` scopes return `Some` with an empty bundle. Grant expiry and revocation
    /// do not invalidate previously delivered keys. This method
    /// performs no network I/O and does not create an authenticated session.
    ///
    /// Returns authenticated claims alongside the keys. Check `claims.iss` and
    /// `claims.jti` against the user and grant you expect before using the keys.
    ///
    /// ```no_run
    /// use pubky::{GrantCredential, GrantId, PublicKey, StoragePath};
    ///
    /// # fn recover(
    /// #     saved_token: &str, expected_user: PublicKey, expected_grant: GrantId,
    /// # ) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some((claims, keys)) = GrantCredential::restore_encryption_keys(saved_token)? {
    ///     if claims.iss != expected_user || claims.jti != expected_grant {
    ///         return Err("saved keys belong to a different account or grant".into());
    ///     }
    ///     let path = StoragePath::new("/pub/chat/message")?;
    ///     let key = keys.derive_for_path(&path)?; // Wiped on drop.
    ///     // Use the key for locally downloaded ciphertext.
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    /// Rejects malformed tokens, invalid approvals, and mismatched grants.
    pub fn restore_encryption_keys(
        token: &str,
    ) -> Result<Option<(GrantClaims, ScopedEncryptionKeyBundle)>> {
        let saved = StoredGrantCredential::decode(token)?;
        Self::restore_encryption_keys_from_approval(
            &saved.grant_jws,
            saved.signed_approval.as_ref().map(SignedApproval::as_str),
        )
    }

    /// Recover keys and authenticated claims from an approval bound to `grant_jws`.
    ///
    /// Works offline, without a signing key or valid grant. No approval returns
    /// `None`. Check `claims.iss` and `claims.jti` against the expected record
    /// before using the returned `(claims, keys)`.
    ///
    /// # Errors
    /// Rejects invalid approvals, inconsistent scopes, and mismatched grants.
    pub fn restore_encryption_keys_from_approval(
        grant_jws: &str,
        signed_approval: Option<&str>,
    ) -> Result<Option<(GrantClaims, ScopedEncryptionKeyBundle)>> {
        let approval = restore_verified_approval(signed_approval, grant_jws)?;
        Ok(approval.map(|(claims, verified)| (claims, verified.encryption_keys)))
    }

    /// Restore a grant credential from an exported secret token.
    ///
    /// This validates the token locally, then exchanges its grant and `PoP`
    /// key with the homeserver for a fresh short-lived bearer. For offline key
    /// recovery without authentication, use [`Self::restore_encryption_keys`].
    ///
    /// # Errors
    /// - Returns validation errors for malformed tokens, expired grants, or
    ///   mismatched `PoP` keys.
    /// - Propagates HTTP/server errors from `POST /auth/grant/session`.
    pub async fn import_secret(token: &str, client: &PubkyHttpClient) -> Result<Self> {
        let saved = StoredGrantCredential::decode(token)?;
        Self::exchange_restored_material(restore_material(saved, false)?, client).await
    }

    /// Restore browser-held authentication and optionally its confidential keys.
    ///
    /// The separate approval must be securely persisted; delegated state remains
    /// non-secret. An approval is verified and must bind the exact stored grant.
    /// `None` restores legacy authentication-only sessions.
    ///
    /// # Errors
    /// Rejects invalid approvals or a different inner grant before network I/O.
    /// Rejects invalid or expired delegated metadata and mismatched signing keys.
    /// Propagates transport/server errors from the grant session exchange.
    pub async fn import_delegated_state(
        state: DelegatedGrantCredentialState,
        client: &PubkyHttpClient,
        sign: DelegatedSignFn,
        signed_approval: Option<&str>,
    ) -> Result<Self> {
        let material = restore_delegated_material(state, sign, false, signed_approval)?;
        Self::exchange_restored_material(material, client).await
    }

    /// Refresh the credential by exchanging the stored grant for a new bearer.
    ///
    /// Holds the credential mutex for the entire refresh so concurrent
    /// refreshes serialize on the same `Arc<Mutex<…>>`.
    pub(crate) async fn refresh(&self, client: &PubkyHttpClient) -> Result<()> {
        if let Some(coordinator) = self.coordinator().await {
            return self
                .refresh_shared(client, coordinator.as_ref(), None)
                .await;
        }
        cross_log!(info, "Refreshing grant credential");
        let mut state = self.state.lock().await;

        // Another caller may have refreshed while we waited for the lock.
        if !state.needs_refresh(now_unix(), REFRESH_SLACK_SECS / 2) {
            return Ok(());
        }

        let parsed = refresh_grant_session(
            client,
            &state.grant_jws,
            &state.grant_claims,
            &state.client_signer,
            &state.homeserver_pk,
        )
        .await?;

        state.bearer = parsed.token;
        state.session = parsed.session;
        Ok(())
    }

    async fn grant_session_request(
        &self,
        client: &PubkyHttpClient,
        method: Method,
    ) -> Result<RequestBuilder> {
        let (homeserver, user) = {
            let state = self.state.lock().await;
            (state.homeserver_pk.clone(), state.grant_claims.iss.clone())
        };
        client
            .cross_request_via_homeserver(method, &homeserver, &user, GRANT_SESSION_PATH)
            .await
    }
}

// Mirrors the cfg pair on the trait definition: native gets `Send` bounds
// for tokio, WASM uses `?Send` because `wasm-bindgen-futures` are not
// `Send`. See [`crate::actors::session::credential::SessionCredential`] for
// the full rationale.
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl SessionCredential for GrantCredential {
    fn info(&self) -> SessionInfo {
        self.info.clone()
    }

    async fn signout(&self, client: &PubkyHttpClient) -> Result<()> {
        let lease = match self.coordinator().await {
            Some(coordinator) => Some(coordinator.acquire(true).await?),
            None => None,
        };
        if let Some(lease) = &lease {
            let Some(mut shared) = lease.load().await? else {
                return Ok(());
            };
            self.state.lock().await.adopt(shared.response.clone())?;
            shared.logout_pending = true;
            lease.store(&shared).await?;
        }
        let request = self.grant_session_request(client, Method::DELETE).await?;
        let homeserver = self.state.lock().await.homeserver_pk.clone();
        let supports_proof_logout = client
            .features
            .supports(
                client,
                &homeserver,
                pubky_common::constants::features::GRANT_PROOF_LOGOUT,
            )
            .await;
        let proof = {
            let state = self.state.lock().await;
            if supports_proof_logout {
                let pop = sign_pop_for_grant(
                    &state.client_signer,
                    &state.homeserver_pk,
                    &state.grant_claims.jti,
                )
                .await?;
                Some(serde_json::json!({ "grant": state.grant_jws, "pop": pop }))
            } else {
                None
            }
        };
        // Older servers only understand bearer-authenticated logout.
        let request = match proof {
            Some(proof) => request.json(&proof),
            None => request.bearer_auth(self.current_bearer().await),
        };
        let response = request.send().await?;
        client.check_http_status(response).await?;
        if let Some(lease) = lease {
            lease.remove().await?;
        }
        Ok(())
    }

    async fn send(
        &self,
        rb: RequestBuilder,
        client: &PubkyHttpClient,
    ) -> Result<reqwest::Response> {
        if let Some(coordinator) = self.coordinator().await {
            return self.send_shared(rb, client, coordinator.as_ref()).await;
        }
        Ok(self.attach(rb, client).await?.send().await?)
    }

    async fn attach(&self, rb: RequestBuilder, client: &PubkyHttpClient) -> Result<RequestBuilder> {
        // Snapshot expiry quickly so we don't hold the lock across the
        // network call when no refresh is needed.
        let needs_refresh = {
            let grant_state = self.state.lock().await;
            grant_state.needs_refresh(now_unix(), REFRESH_SLACK_SECS)
        };
        if needs_refresh {
            self.refresh(client).await?;
        }
        let bearer = self.state.lock().await.bearer.clone();
        Ok(rb.bearer_auth(bearer))
    }

    #[cfg(target_arch = "wasm32")]
    async fn prepare_external(
        &self,
        rb: RequestBuilder,
        client: &PubkyHttpClient,
    ) -> Result<(RequestBuilder, Option<Box<dyn GrantSessionLease>>)> {
        if let Some(coordinator) = self.coordinator().await {
            let (request, lease, _) = self
                .prepare_shared(rb, client, coordinator.as_ref())
                .await?;
            return Ok((request, Some(lease)));
        }
        Ok((self.attach(rb, client).await?, None))
    }

    #[cfg(target_arch = "wasm32")]
    async fn refresh_rejected_bearer(
        &self,
        bearer: &str,
        client: &PubkyHttpClient,
    ) -> Result<bool> {
        let Some(coordinator) = self.coordinator().await else {
            return Ok(false);
        };
        self.refresh_shared(client, coordinator.as_ref(), Some(bearer))
            .await?;
        Ok(true)
    }

    async fn can_attach_to(&self, homeserver: &PublicKey) -> bool {
        &self.state.lock().await.homeserver_pk == homeserver
    }

    async fn revalidate(
        &self,
        client: &PubkyHttpClient,
        _user: &PublicKey,
    ) -> Result<Option<SessionInfo>> {
        let request = self.grant_session_request(client, Method::GET).await?;
        let response = if let Some(coordinator) = self.coordinator().await {
            // A shared send only checks HTTP status inside the refresh
            // exchange, so a rejected refresh is how the server reports a
            // missing session before the GET itself is answered.
            match self
                .send_shared(request, client, coordinator.as_ref())
                .await
            {
                Err(Error::CredentialRefresh(CredentialRefreshError::Request {
                    status: Some(StatusCode::UNAUTHORIZED | StatusCode::NOT_FOUND),
                })) => return Ok(None),
                result => result?,
            }
        } else {
            request
                .bearer_auth(self.current_bearer().await)
                .send()
                .await?
        };
        if credential_session_missing(&response) {
            return Ok(None);
        }
        let response = client.check_http_status(response).await?;
        let session: GrantSessionInfo =
            response
                .json()
                .await
                .map_err(|e| RequestError::DecodeJson {
                    message: format!("decoding /auth/grant/session response: {e}"),
                })?;
        Ok(Some(to_session_info(&session)))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl PubkySession {
    /// Build a grant-backed [`PubkySession`] from a [`GrantCredential`].
    ///
    /// Typical use: after
    /// [`PubkyGrantAuthFlow::await_credential`](crate::PubkyGrantAuthFlow::await_credential)
    /// returns a credential you want to hold separately, this lifts it into
    /// a full session bound to the given HTTP client.
    #[must_use]
    pub fn from_grant_credential(client: PubkyHttpClient, credential: GrantCredential) -> Self {
        Self::from_credential(client, Arc::new(credential))
    }

    /// Restore a grant-backed [`PubkySession`] from an exported secret token.
    ///
    /// This mints a fresh bearer from the token's grant and `PoP` key instead
    /// of replaying an old short-lived bearer. The token should come from
    /// [`GrantSessionView::export_local_secret`](crate::GrantSessionView::export_local_secret)
    /// or [`GrantCredential::export_local_secret`].
    ///
    /// # Errors
    /// - See [`GrantCredential::import_secret`].
    pub async fn import_grant_secret(token: &str, client: Option<PubkyHttpClient>) -> Result<Self> {
        let client = match client {
            Some(client) => client,
            None => PubkyHttpClient::new()?,
        };
        let credential = GrantCredential::import_secret(token, &client).await?;
        Ok(Self::from_grant_credential(client, credential))
    }
}

/// Build a minimal [`SessionInfo`] from a [`GrantSessionInfo`].
fn to_session_info(session: &GrantSessionInfo) -> SessionInfo {
    SessionInfo::new(session.pubky.clone(), session.capabilities.clone())
}

fn restore_material(
    saved: StoredGrantCredential,
    allow_expired: bool,
) -> Result<GrantRestoreMaterial> {
    let verified_approval = restore_verified_approval(
        saved.signed_approval.as_ref().map(SignedApproval::as_str),
        &saved.grant_jws,
    )?
    .map(|(_, approval)| approval);
    let grant_claims = GrantClaims::decode(&saved.grant_jws).map_err(|err| {
        AuthError::Validation(format!("invalid stored grant credential grant JWS: {err}"))
    })?;
    if !allow_expired && grant_claims.exp <= now_unix() {
        return Err(AuthError::Validation("stored grant credential has expired".into()).into());
    }

    let client_keypair = Keypair::from_secret(&saved.client_key_secret);
    if client_keypair.public_key() != grant_claims.cnf {
        return Err(AuthError::Validation(
            "stored grant credential client key does not match the grant cnf".into(),
        )
        .into());
    }

    Ok(GrantRestoreMaterial {
        grant_jws: saved.grant_jws,
        grant_claims,
        client_signer: GrantPopSigner::local(client_keypair),
        homeserver_pk: saved.homeserver_pk,
        verified_approval,
    })
}

fn restore_verified_approval(
    signed: Option<&str>,
    grant_jws: &str,
) -> Result<Option<(GrantClaims, VerifiedApproval)>> {
    let Some(signed) = signed else {
        return Ok(None);
    };
    let approval = GrantApproval::decode_text(
        signed,
        crate::actors::auth::deep_links::GrantApprovalFormat::SignedApprovalV1,
    )?;
    if approval.grant_jws != grant_jws {
        return Err(AuthError::Validation(
            "stored approval does not match the stored grant".into(),
        )
        .into());
    }
    Ok(approval
        .verified_approval
        .map(|verified| (approval.claims, verified)))
}

fn restore_delegated_material(
    saved: DelegatedGrantCredentialState,
    sign: DelegatedSignFn,
    allow_expired: bool,
    signed_approval: Option<&str>,
) -> Result<GrantRestoreMaterial> {
    let verified_approval =
        restore_verified_approval(signed_approval, &saved.grant_jws)?.map(|(_, approval)| approval);
    let grant_claims = GrantClaims::decode(&saved.grant_jws).map_err(|err| {
        AuthError::Validation(format!(
            "invalid delegated grant credential grant JWS: {err}"
        ))
    })?;
    if !allow_expired && grant_claims.exp <= now_unix() {
        return Err(AuthError::Validation("delegated grant credential has expired".into()).into());
    }

    if saved.client_pk != grant_claims.cnf {
        return Err(AuthError::Validation(
            "delegated grant credential client key does not match the grant cnf".into(),
        )
        .into());
    }

    Ok(GrantRestoreMaterial {
        grant_jws: saved.grant_jws,
        grant_claims,
        client_signer: GrantPopSigner::delegated(saved.key_id, saved.client_pk, sign),
        homeserver_pk: saved.homeserver_pk,
        verified_approval,
    })
}

fn invalid_stored_grant() -> AuthError {
    AuthError::Validation(format!(
        "invalid stored grant credential: expected `{STORED_GRANT_CREDENTIAL_PREFIX}:<homeserver>:<client_secret>:<grant_jws>`"
    ))
}

/// Sign a Proof-of-Possession proof JWS for a given grant.
///
/// Builds the canonical `pubky-pop` claims (`aud`, `gid`, `nonce`, `iat`)
/// and signs them with the client keypair via
/// [`pubky_common::auth::jws::sign_jws`].
pub(crate) async fn sign_pop_for_grant(
    client_signer: &GrantPopSigner,
    homeserver_pk: &PublicKey,
    grant_id: &pubky_common::auth::jws::GrantId,
) -> Result<String> {
    let claims = PopProofClaims {
        aud: homeserver_pk.clone(),
        gid: grant_id.clone(),
        nonce: PopNonce::generate(),
        iat: now_unix(),
    };
    client_signer
        .sign_jws(POP_JWS_TYP, &claims)
        .await
        .map_err(|error| AuthError::Validation(error.to_string()).into())
}

#[cfg(test)]
mod tests {
    use std::{num::NonZeroUsize, time::Duration};

    use pkarr::{Cache, InMemoryCache, SignedPacket, dns::rdata::SVCB};
    use pubky_common::{
        auth::jws::{ClientId, GRANT_JWS_TYP, GrantId},
        capabilities::{Capabilities, Capability},
        session::CookieSessionRecord,
    };
    use pubky_testnet::EphemeralTestnet;
    use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
    use tokio::{
        io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
        net::TcpListener,
    };
    use tokio_rustls::TlsAcceptor;

    use super::super::shared_session::{GrantSessionLease, SharedGrantSession};
    use super::*;
    #[allow(
        deprecated,
        reason = "cookie credential is the supported non-grant control"
    )]
    use crate::CookieCredential;

    #[tokio::test]
    #[pubky_testnet::test]
    async fn capped_bearer_requests_and_legacy_logout_do_not_refresh() {
        let testnet = EphemeralTestnet::builder().build().await.unwrap();
        let user = Keypair::random();
        let homeserver = testnet.homeserver_app().public_key();
        testnet
            .sdk()
            .unwrap()
            .signer(user.clone())
            .signup(&homeserver, None)
            .await
            .unwrap();
        let mut builder = PubkyHttpClient::builder();
        builder.pkarr(|b| {
            *b = testnet.pkarr_client_builder();
            b
        });
        let client = builder.build().unwrap();
        client.features.insert(&homeserver, &[]);
        let pop_key = Keypair::random();
        let now = now_unix();
        let grant = GrantClaims {
            iss: user.public_key(),
            client_id: ClientId::new("refresh.test").unwrap(),
            caps: vec![Capability::root()],
            cnf: pop_key.public_key(),
            jti: GrantId::generate(),
            iat: now,
            exp: now + 120,
        };
        let jws = grant.sign(&user, GRANT_JWS_TYP);
        let signer = GrantPopSigner::local(pop_key);
        let credential = credential_from_grant_exchange(&client, jws, grant, signer, homeserver)
            .await
            .unwrap();
        let state = credential.state.lock().await;
        let bearer = state.bearer.clone();
        assert_eq!(state.session.token_expires_at, state.grant_claims.exp);
        drop(state);
        for _ in 0..3 {
            credential.refresh(&client).await.unwrap();
            let request = credential
                .grant_session_request(&client, Method::GET)
                .await
                .unwrap();
            let response = credential
                .attach(request, &client)
                .await
                .unwrap()
                .send()
                .await
                .unwrap();
            client.check_http_status(response).await.unwrap();
            assert_eq!(credential.current_bearer().await, bearer);
        }

        // Logout must also work when the cached bearer would normally need a refresh.
        credential.state.lock().await.session.token_expires_at = now_unix() + 60;
        credential.signout(&client).await.unwrap();
        assert!(
            credential
                .revalidate(&client, &user.public_key())
                .await
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn refresh_policy_preserves_capped_bearers_until_expiry() {
        let (stored, claims) = stored_credential(5_000);
        let signer = GrantPopSigner::local(Keypair::from_secret(&stored.client_key_secret));
        let credential = test_credential(stored, claims, signer);
        let mut state = credential.state.blocking_lock();
        let now = 1_000;
        for (bearer_exp, grant_exp, slack, expected) in [
            (1_301, 5_000, 300, false),
            (1_300, 5_000, 300, true),
            (1_151, 5_000, 150, false),
            (1_150, 5_000, 150, true),
            (1_120, 1_120, 150, false),
            (1_120, 1_100, 150, false),
            (1_000, 1_000, 150, true),
            (999, 999, 150, true),
            (0, 1_120, 150, true),
        ] {
            state.session.token_expires_at = bearer_exp;
            state.grant_claims.exp = grant_exp;
            assert_eq!(
                state.needs_refresh(now, slack),
                expected,
                "bearer_exp={bearer_exp}, grant_exp={grant_exp}, slack={slack}"
            );
        }
    }

    #[test]
    fn stored_grant_credential_encode_decode_round_trips() {
        let (stored, _claims) = stored_credential(now_unix() + 3600);

        let encoded = stored.encode();
        let decoded = StoredGrantCredential::decode(&encoded).unwrap();

        assert_eq!(decoded.grant_jws, stored.grant_jws);
        assert_eq!(decoded.client_key_secret, stored.client_key_secret);
        assert_eq!(decoded.homeserver_pk, stored.homeserver_pk);
        assert!(decoded.signed_approval.is_none());
    }

    #[test]
    fn key_bearing_secret_round_trip_verifies_approval_and_preserves_keys() {
        let identity = Keypair::random();
        let (mut stored, mut claims) = stored_credential(now_unix() + 3600);
        claims.iss = identity.public_key();
        claims.caps = vec!["/pub/chat/:re".parse().unwrap()];
        stored.grant_jws = claims.sign(&identity, GRANT_JWS_TYP);
        let signed =
            super::super::approval_envelope::GrantApprovalEnvelope::sign(&identity, &claims);
        stored.signed_approval = Some(SignedApproval::new(&signed));

        let encoded = Zeroizing::new(stored.encode());
        assert!(encoded.starts_with(STORED_GRANT_CREDENTIAL_APPROVAL_PREFIX));
        let decoded = StoredGrantCredential::decode(&encoded).unwrap();
        let (_, approval) = restore_verified_approval(
            decoded.signed_approval.as_ref().map(SignedApproval::as_str),
            &decoded.grant_jws,
        )
        .unwrap()
        .unwrap();
        let keys = approval.encryption_keys;
        let path = pubky_common::StoragePath::new("/pub/chat/message").unwrap();
        let expected = ScopedEncryptionKeyBundle::from_identity_secret(&identity.secret(), [&path]);
        assert_eq!(
            *keys.derive_for_path(&path).unwrap(),
            *expected.derive_for_path(&path).unwrap()
        );
        keys.derive_for_path(&pubky_common::StoragePath::new("/pub/other/file").unwrap())
            .unwrap_err();
        assert!(!format!("{decoded:?}").contains(signed.as_str()));

        let (other, _) = stored_credential(now_unix() + 3600);
        restore_verified_approval(Some(&signed), &other.grant_jws).unwrap_err();
        let mut tampered = signed.as_bytes().to_vec();
        let signature_start = signed.rfind('.').unwrap() + 1;
        tampered[signature_start] = if tampered[signature_start] == b'A' {
            b'B'
        } else {
            b'A'
        };
        restore_verified_approval(
            Some(std::str::from_utf8(&tampered).unwrap()),
            &stored.grant_jws,
        )
        .unwrap_err();
    }

    fn expired_key_credential() -> (
        StoredGrantCredential,
        DelegatedGrantCredentialState,
        Keypair,
    ) {
        let identity = Keypair::random();
        let (mut saved, mut claims) = stored_credential(1);
        claims.iat = 0;
        claims.iss = identity.public_key();
        claims.caps = vec!["/pub/chat/:re".parse().unwrap()];
        saved.grant_jws = claims.sign(&identity, GRANT_JWS_TYP);
        let signed =
            super::super::approval_envelope::GrantApprovalEnvelope::sign(&identity, &claims);
        saved.signed_approval = Some(SignedApproval::new(&signed));
        let delegated = DelegatedGrantCredentialState {
            grant_jws: saved.grant_jws.clone(),
            homeserver_pk: saved.homeserver_pk.clone(),
            key_id: "missing-browser-key".into(),
            client_pk: claims.cnf,
        };
        (saved, delegated, identity)
    }

    #[test]
    fn offline_key_recovery_accepts_expiry_without_relaxing_session_restore() {
        let (saved, delegated, identity) = expired_key_credential();
        let token = Zeroizing::new(saved.encode());
        let (local_claims, local_keys) = GrantCredential::restore_encryption_keys(&token)
            .unwrap()
            .unwrap();
        let (delegated_claims, delegated_keys) =
            GrantCredential::restore_encryption_keys_from_approval(
                &delegated.grant_jws,
                saved.signed_approval.as_ref().map(SignedApproval::as_str),
            )
            .unwrap()
            .unwrap();
        assert_eq!(local_claims.iss, identity.public_key());
        assert_eq!(local_claims.jti, delegated_claims.jti);
        assert_eq!(delegated_claims.iss, identity.public_key());
        let path = pubky_common::StoragePath::new("/pub/chat/message").unwrap();
        let expected = ScopedEncryptionKeyBundle::from_identity_secret(&identity.secret(), [&path]);
        let shared_local = GrantCredential::from_shared_secret(&token).unwrap();
        let shared_delegated = GrantCredential::from_shared_delegated_state(
            delegated.clone(),
            test_delegated_signer(),
            saved.signed_approval.as_ref().map(SignedApproval::as_str),
        )
        .unwrap();
        assert!(shared_local.signed_approval().is_some());
        assert!(shared_delegated.signed_approval().is_some());
        for keys in [
            &local_keys,
            &delegated_keys,
            shared_local.encryption_keys().unwrap(),
            shared_delegated.encryption_keys().unwrap(),
        ] {
            assert_eq!(
                *keys.derive_for_path(&path).unwrap(),
                *expected.derive_for_path(&path).unwrap()
            );
            keys.derive_for_path(&pubky_common::StoragePath::new("/pub/other/file").unwrap())
                .unwrap_err();
            keys.derive_for_path(&pubky_common::StoragePath::new("/pub/chat/").unwrap())
                .unwrap_err();
        }
        assert!(
            restore_material(saved, false)
                .unwrap_err()
                .to_string()
                .contains("has expired")
        );
        assert!(
            restore_delegated_material(delegated, test_delegated_signer(), false, None)
                .unwrap_err()
                .to_string()
                .contains("has expired")
        );
    }

    #[test]
    fn offline_key_recovery_rejects_tampering_and_mismatched_grants() {
        let (mut saved, mut delegated, _) = expired_key_credential();
        let signed = saved.signed_approval.clone().unwrap();
        let (other, _) = stored_credential(now_unix() + 3600);
        delegated.grant_jws = other.grant_jws.clone();
        GrantCredential::restore_encryption_keys_from_approval(
            &delegated.grant_jws,
            Some(signed.as_str()),
        )
        .unwrap_err();
        let original_grant = std::mem::replace(&mut saved.grant_jws, other.grant_jws);
        GrantCredential::restore_encryption_keys(&saved.encode()).unwrap_err();
        saved.grant_jws = original_grant;
        delegated.grant_jws = saved.grant_jws.clone();

        let mut tampered = signed.as_str().as_bytes().to_vec();
        let signature_start = signed.as_str().rfind('.').unwrap() + 1;
        tampered[signature_start] = if tampered[signature_start] == b'A' {
            b'B'
        } else {
            b'A'
        };
        let tampered = Zeroizing::new(String::from_utf8(tampered).unwrap());
        saved.signed_approval = Some(SignedApproval::new(&tampered));
        GrantCredential::from_shared_secret(&saved.encode()).unwrap_err();
        GrantCredential::from_shared_delegated_state(
            delegated.clone(),
            test_delegated_signer(),
            Some(&tampered),
        )
        .unwrap_err();
        GrantCredential::restore_encryption_keys(&saved.encode()).unwrap_err();
        GrantCredential::restore_encryption_keys_from_approval(
            &delegated.grant_jws,
            Some(&tampered),
        )
        .unwrap_err();
        GrantCredential::restore_encryption_keys("malformed").unwrap_err();
    }

    #[test]
    fn offline_legacy_restore_returns_no_keys() {
        let (saved, _) = stored_credential(1);
        assert!(
            GrantCredential::restore_encryption_keys(&saved.encode())
                .unwrap()
                .is_none()
        );
        let (_, delegated, _) = expired_key_credential();
        assert!(
            GrantCredential::restore_encryption_keys_from_approval(&delegated.grant_jws, None)
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn v2_secret_rejects_missing_approval() {
        let (stored, _) = stored_credential(now_unix() + 3600);
        let token = stored.encode().replacen(
            STORED_GRANT_CREDENTIAL_PREFIX,
            STORED_GRANT_CREDENTIAL_APPROVAL_PREFIX,
            1,
        );
        StoredGrantCredential::decode(&token).unwrap_err();
        StoredGrantCredential::decode(&format!("{token}:")).unwrap_err();
    }

    #[test]
    fn restore_material_rejects_mismatched_client_key() {
        let (mut stored, _claims) = stored_credential(now_unix() + 3600);
        stored.client_key_secret = Keypair::random().secret();

        let error = restore_material(stored, false).unwrap_err().to_string();

        assert!(error.contains("client key does not match"));
    }

    #[test]
    fn restore_delegated_material_rejects_mismatched_client_key() {
        let (stored, _claims) = stored_credential(now_unix() + 3600);
        let saved = DelegatedGrantCredentialState {
            grant_jws: stored.grant_jws,
            homeserver_pk: stored.homeserver_pk,
            key_id: "delegated-test-key".into(),
            client_pk: Keypair::random().public_key(),
        };

        let error = restore_delegated_material(saved, test_delegated_signer(), false, None)
            .unwrap_err()
            .to_string();

        assert!(error.contains("client key does not match"));
    }

    #[test]
    fn restore_delegated_material_rejects_expired_grant() {
        let (stored, claims) = stored_credential(now_unix().saturating_sub(1));
        let saved = DelegatedGrantCredentialState {
            grant_jws: stored.grant_jws,
            homeserver_pk: stored.homeserver_pk,
            key_id: "delegated-test-key".into(),
            client_pk: claims.cnf,
        };

        let error = restore_delegated_material(saved, test_delegated_signer(), false, None)
            .unwrap_err()
            .to_string();

        assert!(error.contains("has expired"));
    }

    #[tokio::test]
    async fn export_local_secret_is_only_available_for_local_signers() {
        let (stored, claims) = stored_credential(now_unix() + 3600);
        let local_signer = GrantPopSigner::local(Keypair::from_secret(&stored.client_key_secret));
        let delegated_signer = GrantPopSigner::delegated(
            "delegated-test-key".into(),
            claims.cnf.clone(),
            test_delegated_signer(),
        );

        let local = test_credential(stored.clone(), claims.clone(), local_signer);
        let delegated = test_credential(stored, claims, delegated_signer);

        assert!(local.export_local_secret().await.is_some());
        assert!(delegated.export_local_secret().await.is_none());
        assert!(delegated.export_delegated_restore_state().await.is_some());
    }

    #[test]
    fn restore_material_rejects_expired_grant() {
        let (stored, _claims) = stored_credential(now_unix().saturating_sub(1));

        let error = restore_material(stored, false).unwrap_err().to_string();

        assert!(error.contains("has expired"));
    }

    #[test]
    fn shared_restore_keeps_expired_material_for_logout() {
        let (stored, claims) = stored_credential(now_unix().saturating_sub(1));
        GrantCredential::from_shared_secret(&stored.encode()).unwrap();
        let delegated = DelegatedGrantCredentialState {
            grant_jws: stored.grant_jws,
            homeserver_pk: stored.homeserver_pk,
            key_id: "delegated-test-key".into(),
            client_pk: claims.cnf,
        };
        GrantCredential::from_shared_delegated_state(delegated, test_delegated_signer(), None)
            .unwrap();
    }

    #[test]
    fn stored_grant_credential_decode_rejects_wrong_prefix() {
        let error = StoredGrantCredential::decode("wrong:v:secret:grant")
            .unwrap_err()
            .to_string();

        assert!(error.contains("unsupported grant credential token version"));
    }

    #[tokio::test]
    async fn refresh_server_failure_has_typed_secret_safe_provenance() {
        let fixture = RequestFailureFixture::new(TestServerBehavior::Reply(
            b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 9\r\n\r\nsensitive".to_vec(),
        ))
        .await;
        let credential = fixture.grant_credential(true);

        let error = credential.refresh(&fixture.client).await.unwrap_err();

        assert!(
            matches!(
                &error,
                Error::CredentialRefresh(CredentialRefreshError::Request {
                    status: Some(StatusCode::SERVICE_UNAVAILABLE)
                })
            ),
            "unexpected error: {error:?}"
        );
        let display = error.to_string();
        assert_eq!(
            display,
            "Credential refresh failed: Grant credential refresh request failed"
        );
        let debug = format!("{error:?}");
        for secret in [
            "sensitive",
            "test-bearer",
            "auth/grant/session",
            "localhost",
        ] {
            assert!(!display.contains(secret));
            assert!(!debug.contains(secret));
        }
    }

    #[tokio::test]
    async fn refresh_error_status_does_not_wait_for_response_body() {
        let fixture = RequestFailureFixture::new_with_timeout(
            TestServerBehavior::ReplyThenStall(
                b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 9\r\n\r\n".to_vec(),
            ),
            Duration::from_secs(5),
        )
        .await;
        let credential = fixture.grant_credential(true);

        let error =
            tokio::time::timeout(Duration::from_secs(1), credential.refresh(&fixture.client))
                .await
                .expect("refresh must discard the unread error body")
                .unwrap_err();

        assert!(matches!(
            error,
            Error::CredentialRefresh(CredentialRefreshError::Request {
                status: Some(StatusCode::SERVICE_UNAVAILABLE)
            })
        ));
    }

    #[tokio::test]
    async fn refresh_json_decode_failure_preserves_response_status() {
        let fixture = RequestFailureFixture::new(TestServerBehavior::Reply(
            b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nnot-json".to_vec(),
        ))
        .await;
        let credential = fixture.grant_credential(true);

        let error = credential.refresh(&fixture.client).await.unwrap_err();

        assert!(matches!(
            error,
            Error::CredentialRefresh(CredentialRefreshError::Request {
                status: Some(StatusCode::OK)
            })
        ));
    }

    #[tokio::test]
    async fn refresh_timeout_has_typed_secret_safe_provenance() {
        let fixture = RequestFailureFixture::new(TestServerBehavior::Stall).await;
        let credential = fixture.grant_credential(true);

        let error = credential.refresh(&fixture.client).await.unwrap_err();

        assert!(
            matches!(
                &error,
                Error::CredentialRefresh(CredentialRefreshError::Request { status: None })
            ),
            "unexpected error: {error:?}"
        );
        let debug = format!("{error:?}");
        assert!(!debug.contains("localhost"));
        assert!(!debug.contains("auth/grant/session"));
    }

    #[tokio::test]
    async fn shared_refresh_request_failure_uses_same_secret_safe_error() {
        let fixture = RequestFailureFixture::new(TestServerBehavior::Reply(
            b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 9\r\n\r\nsensitive".to_vec(),
        ))
        .await;
        let credential = fixture.grant_credential(true);
        let coordinator = TestCoordinator {
            shared: Arc::new(tokio::sync::Mutex::new(Some(SharedGrantSession {
                response: credential.state.lock().await.response(),
                refresh_pending: false,
                logout_pending: false,
            }))),
        };

        let error = credential
            .refresh_shared(&fixture.client, &coordinator, None)
            .await
            .unwrap_err();

        assert!(matches!(
            error,
            Error::CredentialRefresh(CredentialRefreshError::Request {
                status: Some(StatusCode::SERVICE_UNAVAILABLE)
            })
        ));
    }

    #[tokio::test]
    async fn refresh_preserves_local_authentication_failure() {
        let (stored, claims) = stored_credential(now_unix() + 3600);
        let credential = test_credential(
            stored,
            claims.clone(),
            GrantPopSigner::delegated(
                "missing-key".into(),
                claims.cnf,
                super::super::pop_signer::delegated_sign_callback(|_| async {
                    Err(super::super::pop_signer::GrantSigningError::KeyUnavailable(
                        "deleted key".into(),
                    ))
                }),
            ),
        );
        credential.state.lock().await.session.token_expires_at = now_unix();
        let client = PubkyHttpClient::new().unwrap();

        let error = credential.refresh(&client).await.unwrap_err();

        assert!(matches!(
            error,
            Error::Authentication(AuthError::Validation(message)) if message.contains("deleted key")
        ));
    }

    #[tokio::test]
    async fn shared_refresh_preserves_coordinator_request_failure() {
        let (stored, claims) = stored_credential(now_unix() + 3600);
        let signer = GrantPopSigner::local(Keypair::from_secret(&stored.client_key_secret));
        let credential = test_credential(stored, claims, signer);
        let client = PubkyHttpClient::new().unwrap();

        let error = credential
            .refresh_shared(&client, &FailingCoordinator, None)
            .await
            .unwrap_err();

        assert!(matches!(
            error,
            Error::Request(RequestError::Validation { message }) if message == "browser storage failed"
        ));
    }

    #[tokio::test]
    async fn shared_revalidation_treats_wrapped_missing_refresh_sessions_as_absent() {
        for (status, reason) in [(401, "Unauthorized"), (404, "Not Found")] {
            let response =
                format!("HTTP/1.1 {status} {reason}\r\nContent-Length: 7\r\n\r\nprivate");
            let fixture =
                RequestFailureFixture::new(TestServerBehavior::Reply(response.into_bytes())).await;
            let credential = fixture.grant_credential(true);
            let shared = SharedGrantSession {
                response: credential.state.lock().await.response(),
                refresh_pending: false,
                logout_pending: false,
            };
            credential.state.lock().await.coordinator = Some(Arc::new(TestCoordinator {
                shared: Arc::new(tokio::sync::Mutex::new(Some(shared))),
            }));

            let result = credential
                .revalidate(&fixture.client, &fixture.user.public_key())
                .await;

            assert!(
                matches!(result, Ok(None)),
                "wrapped {status} refresh failure must mean missing session, got {result:?}"
            );
        }
    }

    #[tokio::test]
    async fn storage_server_failure_remains_request_error_for_all_credentials() {
        for credential in [CredentialKind::Grant, CredentialKind::Cookie] {
            let fixture = RequestFailureFixture::new(TestServerBehavior::Reply(
                b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 7\r\n\r\nstorage".to_vec(),
            ))
            .await;
            let session = fixture.session(credential);

            let error = session.storage().get("/pub/test/file").await.unwrap_err();

            assert!(matches!(
                error,
                Error::Request(RequestError::Server {
                    status: StatusCode::INTERNAL_SERVER_ERROR,
                    ..
                })
            ));
        }
    }

    #[tokio::test]
    async fn storage_timeout_remains_request_error_for_all_credentials() {
        for credential in [CredentialKind::Grant, CredentialKind::Cookie] {
            let fixture = RequestFailureFixture::new(TestServerBehavior::Stall).await;
            let session = fixture.session(credential);

            let error = session.storage().get("/pub/test/file").await.unwrap_err();

            assert!(matches!(
                error,
                Error::Request(RequestError::Transport(ref source)) if source.is_timeout()
            ));
        }
    }

    #[derive(Clone, Copy)]
    enum CredentialKind {
        Grant,
        Cookie,
    }

    #[derive(Debug)]
    struct TestCoordinator {
        shared: Arc<tokio::sync::Mutex<Option<SharedGrantSession>>>,
    }

    #[derive(Debug)]
    struct FailingCoordinator;

    #[async_trait]
    impl GrantSessionCoordinator for FailingCoordinator {
        async fn acquire(&self, _: bool) -> Result<Box<dyn GrantSessionLease>> {
            Err(RequestError::Validation {
                message: "browser storage failed".into(),
            }
            .into())
        }
    }

    #[derive(Debug)]
    struct TestLease {
        shared: Arc<tokio::sync::Mutex<Option<SharedGrantSession>>>,
    }

    #[async_trait]
    impl GrantSessionCoordinator for TestCoordinator {
        async fn acquire(&self, _: bool) -> Result<Box<dyn GrantSessionLease>> {
            Ok(Box::new(TestLease {
                shared: Arc::clone(&self.shared),
            }))
        }
    }

    #[async_trait]
    impl GrantSessionLease for TestLease {
        async fn load(&self) -> Result<Option<SharedGrantSession>> {
            Ok(self.shared.lock().await.clone())
        }

        async fn store(&self, session: &SharedGrantSession) -> Result<()> {
            *self.shared.lock().await = Some(session.clone());
            Ok(())
        }

        async fn remove(&self) -> Result<()> {
            *self.shared.lock().await = None;
            Ok(())
        }
    }

    /// A client whose homeserver resolves to a one-shot TLS server.
    struct RequestFailureFixture {
        client: PubkyHttpClient,
        user: Keypair,
        homeserver: pkarr::Keypair,
    }

    impl RequestFailureFixture {
        async fn new(behavior: TestServerBehavior) -> Self {
            Self::new_with_timeout(behavior, Duration::from_millis(100)).await
        }

        async fn new_with_timeout(behavior: TestServerBehavior, timeout: Duration) -> Self {
            let port = spawn_https_test_server(behavior).await;
            let homeserver = pkarr::Keypair::random();
            let user = Keypair::random();
            let cache = resolver_cache(&homeserver, &user, port);

            let mut builder = PubkyHttpClient::builder();
            builder
                .isolated_pkarr_test()
                .pkarr(|builder| builder.cache(cache))
                .request_timeout(timeout)
                .add_root_certificates_pem(include_bytes!("../../../client/test_certs/ca.pem"))
                .unwrap();
            let fixture = Self {
                client: builder.build().unwrap(),
                user,
                homeserver,
            };
            fixture
                .client
                .features
                .insert(&fixture.homeserver_pk(), &[]);
            fixture
        }

        fn homeserver_pk(&self) -> PublicKey {
            PublicKey::try_from_z32(&self.homeserver.public_key().to_string()).unwrap()
        }

        #[allow(
            deprecated,
            reason = "cookie credential is the supported non-grant control"
        )]
        fn session(&self, credential: CredentialKind) -> PubkySession {
            match credential {
                CredentialKind::Grant => PubkySession::from_grant_credential(
                    self.client.clone(),
                    self.grant_credential(false),
                ),
                CredentialKind::Cookie => PubkySession::from_cookie_credential(
                    self.client.clone(),
                    self.cookie_credential(),
                ),
            }
        }

        /// A credential whose bearer is either already due for refresh or
        /// valid for an hour.
        fn grant_credential(&self, refresh: bool) -> GrantCredential {
            let client_keypair = Keypair::random();
            let now = now_unix();
            let claims = GrantClaims {
                iss: self.user.public_key(),
                client_id: ClientId::new("refresh-errors.test").unwrap(),
                caps: vec![Capability::root()],
                cnf: client_keypair.public_key(),
                jti: GrantId::generate(),
                iat: now,
                exp: now + 3600,
            };
            let homeserver = self.homeserver_pk();
            GrantCredential::from_response(
                GrantSessionResponse {
                    token: "test-bearer".into(),
                    session: GrantSessionInfo {
                        homeserver: homeserver.clone(),
                        pubky: claims.iss.clone(),
                        client_id: claims.client_id.clone(),
                        capabilities: claims.caps.clone(),
                        grant_id: claims.jti.clone(),
                        token_expires_at: if refresh { now } else { now + 3600 },
                        grant_expires_at: claims.exp,
                        created_at: now,
                    },
                },
                claims.sign(&self.user, GRANT_JWS_TYP),
                claims,
                GrantPopSigner::local(client_keypair),
                homeserver,
            )
        }

        #[allow(
            deprecated,
            reason = "cookie credential is the supported non-grant control"
        )]
        fn cookie_credential(&self) -> CookieCredential {
            let record = CookieSessionRecord::new(
                &self.user.public_key(),
                Capabilities::from(vec![Capability::root()]),
                None,
            );
            CookieCredential::new(
                self.user.public_key(),
                Some("cookie-secret".into()),
                record,
                Some(self.homeserver_pk()),
            )
        }
    }

    /// How the one-shot TLS server answers the single request it accepts.
    enum TestServerBehavior {
        /// Write these raw HTTP bytes once the request headers have arrived.
        Reply(Vec<u8>),
        /// Write response headers, then keep the declared body pending.
        ReplyThenStall(Vec<u8>),
        /// Keep the connection open without answering.
        Stall,
    }

    /// Accept one TLS connection on an ephemeral `localhost` port and return that port.
    async fn spawn_https_test_server(behavior: TestServerBehavior) -> u16 {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let acceptor = TlsAcceptor::from(Arc::new(test_server_config()));

        tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut stream = acceptor.accept(stream).await.unwrap();
            if !read_request_headers(&mut stream).await {
                return;
            }
            match behavior {
                TestServerBehavior::Reply(response) => stream.write_all(&response).await.unwrap(),
                TestServerBehavior::ReplyThenStall(response) => {
                    stream.write_all(&response).await.unwrap();
                    tokio::time::sleep(Duration::from_secs(2)).await;
                }
                TestServerBehavior::Stall => tokio::time::sleep(Duration::from_secs(1)).await,
            }
        });

        port
    }

    fn test_server_config() -> rustls::ServerConfig {
        let server_cert =
            CertificateDer::from_pem_slice(include_bytes!("../../../client/test_certs/server.pem"))
                .unwrap();
        let server_key =
            PrivateKeyDer::from_pem_slice(include_bytes!("../../../client/test_certs/server.key"))
                .unwrap();
        rustls::ServerConfig::builder_with_provider(Arc::new(
            rustls::crypto::aws_lc_rs::default_provider(),
        ))
        .with_safe_default_protocol_versions()
        .unwrap()
        .with_no_client_auth()
        .with_single_cert(vec![server_cert], server_key)
        .unwrap()
    }

    /// Returns `false` when the client hung up before sending its headers.
    async fn read_request_headers(stream: &mut (impl AsyncRead + Unpin)) -> bool {
        let mut request = Vec::new();
        let mut buffer = [0; 1024];
        while !request.windows(4).any(|window| window == b"\r\n\r\n") {
            let read = stream.read(&mut buffer).await.unwrap();
            if read == 0 {
                return false;
            }
            request.extend_from_slice(&buffer[..read]);
        }
        true
    }

    /// Pkarr cache that points `user` at `homeserver` and `homeserver` at
    /// `localhost:port`, so no DHT lookups happen.
    fn resolver_cache(homeserver: &pkarr::Keypair, user: &Keypair, port: u16) -> Arc<dyn Cache> {
        let cache: Arc<dyn Cache> = Arc::new(InMemoryCache::new(NonZeroUsize::new(2).unwrap()));

        let mut endpoint = SVCB::new(10, "localhost".try_into().unwrap());
        endpoint.set_port(port);
        let homeserver_packet = SignedPacket::builder()
            .https(".".try_into().unwrap(), endpoint, 3600)
            .sign(homeserver)
            .unwrap();
        cache.put(&homeserver.public_key().into(), &homeserver_packet);

        let homeserver_z32 = homeserver.public_key().to_string();
        let alias = SVCB::new(0, homeserver_z32.as_str().try_into().unwrap());
        let user_pkarr = pkarr::PublicKey::try_from(user.public_key().z32().as_str()).unwrap();
        let user_packet = SignedPacket::builder()
            .https("_pubky".try_into().unwrap(), alias, 3600)
            .sign(&pkarr::Keypair::from_secret_key(&user.secret()))
            .unwrap();
        cache.put(&user_pkarr.into(), &user_packet);

        cache
    }

    fn stored_credential(exp: u64) -> (StoredGrantCredential, GrantClaims) {
        let user_keypair = Keypair::random();
        let client_keypair = Keypair::random();
        let homeserver_keypair = Keypair::random();
        let claims = GrantClaims {
            iss: user_keypair.public_key(),
            client_id: ClientId::new("stored-grant.test").unwrap(),
            caps: vec![Capability::root()],
            cnf: client_keypair.public_key(),
            jti: GrantId::generate(),
            iat: now_unix(),
            exp,
        };
        let grant_jws = claims.sign(&user_keypair, GRANT_JWS_TYP);
        let stored = StoredGrantCredential {
            grant_jws,
            client_key_secret: client_keypair.secret(),
            homeserver_pk: homeserver_keypair.public_key(),
            signed_approval: None,
        };
        (stored, claims)
    }

    fn test_credential(
        stored: StoredGrantCredential,
        claims: GrantClaims,
        client_signer: GrantPopSigner,
    ) -> GrantCredential {
        let now = now_unix();
        GrantCredential::from_response(
            GrantSessionResponse {
                token: "test-bearer".into(),
                session: GrantSessionInfo {
                    homeserver: stored.homeserver_pk.clone(),
                    pubky: claims.iss.clone(),
                    client_id: claims.client_id.clone(),
                    capabilities: claims.caps.clone(),
                    grant_id: claims.jti.clone(),
                    token_expires_at: now + 300,
                    grant_expires_at: claims.exp,
                    created_at: now,
                },
            },
            stored.grant_jws,
            claims,
            client_signer,
            stored.homeserver_pk,
        )
    }

    fn test_delegated_signer() -> DelegatedSignFn {
        super::super::pop_signer::delegated_sign_callback(|_| async { Ok(vec![0; 64]) })
    }

    #[tokio::test]
    async fn can_attach_to_only_matches_bound_homeserver() {
        let bound = Keypair::random().public_key();
        let other = Keypair::random().public_key();
        let (mut stored, claims) = stored_credential(now_unix() + 3600);
        stored.homeserver_pk = bound.clone();
        let client_signer = GrantPopSigner::local(Keypair::from_secret(&stored.client_key_secret));
        let credential = test_credential(stored, claims, client_signer);

        assert!(
            credential.can_attach_to(&bound).await,
            "grant credential must attach to the homeserver it was minted for"
        );
        assert!(
            !credential.can_attach_to(&other).await,
            "grant credential must NOT attach to a homeserver it was not minted for"
        );
    }

    #[tokio::test]
    async fn grant_session_request_routes_through_bound_homeserver() {
        use pkarr::{SignedPacket, dns::rdata::SVCB};

        let (mut stored, claims) = stored_credential(now_unix() + 3600);
        let homeserver_keypair = pkarr::Keypair::random();
        stored.homeserver_pk =
            PublicKey::try_from_z32(&homeserver_keypair.public_key().to_string()).unwrap();
        let icann = SVCB::new(10, "example.com".try_into().unwrap());
        let homeserver_packet = SignedPacket::builder()
            .https(".".try_into().unwrap(), icann, 3600)
            .sign(&homeserver_keypair)
            .unwrap();
        let client_signer = GrantPopSigner::local(Keypair::from_secret(&stored.client_key_secret));
        let credential = test_credential(stored, claims.clone(), client_signer);

        let cache = Arc::new(InMemoryCache::new(NonZeroUsize::MIN));
        let mut builder = PubkyHttpClient::builder();
        builder
            .isolated_pkarr_test()
            .pkarr(|b| b.cache(Arc::<InMemoryCache>::clone(&cache)));
        let client = builder.build().unwrap();
        cache.put(&homeserver_keypair.public_key().into(), &homeserver_packet);

        let request = credential
            .grant_session_request(&client, Method::POST)
            .await
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(request.url().host_str(), Some("example.com"));
        assert_eq!(request.url().path(), "/auth/grant/session");
        assert_eq!(
            request.headers().get("pubky-host").unwrap(),
            &claims.iss.z32()
        );
    }
}