openrtc 0.2.0

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
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
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
/// Session token registry for gating iroh connections during short-lived sessions
/// (e.g. share page, magic-link).
///
/// # Compound ticket format
/// `<iroh_endpoint_ticket>.<base64url_token_payload>`
///
/// The token payload suffix is appended after the raw iroh ticket using `.`.
/// We must split on the LAST `.` because real endpoint tickets can contain dots
/// (for example through embedded relay URL data).
///
/// Token payload is compact JSON:
/// `{"t":"<token>","s":"<scope>","m":<maxConnections>,"h":"<endpointTicketHash>","e":<expiresAtMs>,"a":"openrtc:endpoint-ticket:v1","n":"<nonce>"}`
///
/// # Backward compatibility
/// If the registry is empty, ALL incoming connections are accepted without validation.
/// Existing trusted-device flows are completely unaffected.
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};

/// Default TTL for newly minted restricted endpoint-ticket grants.
pub const DEFAULT_RESTRICTED_SESSION_TOKEN_TTL_MS: u64 = 15 * 60 * 1000;
pub const TOKEN_PAYLOAD_ENDPOINT_TICKET_AUDIENCE: &str = "openrtc:endpoint-ticket:v1";
const TOKEN_PAYLOAD_NONCE_BYTES: usize = 16;

pub fn now_unix_ms() -> u64 {
    #[cfg(target_arch = "wasm32")]
    {
        js_sys::Date::now().max(0.0) as u64
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        use std::time::{SystemTime, UNIX_EPOCH};
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
            .unwrap_or(0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
/// Admission-grant label carried by restricted session tokens and compound tickets.
///
/// This is distinct from the TypeScript `PeerScope` lifecycle label: `GrantScope`
/// governs authorization, validation, and revoke semantics in the Rust admission layer.
pub struct GrantScope(pub String);

impl GrantScope {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_inner(self) -> String {
        self.0
    }
}

impl From<&str> for GrantScope {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for GrantScope {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<&GrantScope> for GrantScope {
    fn from(value: &GrantScope) -> Self {
        value.clone()
    }
}

impl AsRef<str> for GrantScope {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl PartialEq<&str> for GrantScope {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<String> for GrantScope {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other
    }
}

impl std::fmt::Display for GrantScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// A registered session token.
#[derive(Debug, Clone)]
pub struct SessionToken {
    /// The raw token string (random, high-entropy).
    pub token: String,
    /// Application-defined admission grant (e.g. "share", "magic-link", "friend").
    /// Distinct from the TypeScript `PeerScope` lifecycle label.
    pub scope: GrantScope,
    /// Max number of connections allowed. 0 = unlimited.
    pub max_connections: u32,
    /// Number of connections that have consumed this token so far.
    pub use_count: u32,
    /// Absolute Unix-millisecond expiry. None means legacy/unbounded.
    pub expires_at_ms: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionAdmissionMechanism {
    SessionToken,
    TrustedNativeBinding,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionAdmission {
    Pending,
    Accepted {
        mechanism: SessionAdmissionMechanism,
        scope: Option<GrantScope>,
        authoritative_device_id: Option<String>,
    },
    Rejected {
        reason: String,
    },
}

/// Stable, low-cardinality fingerprint of a token value, used to correlate
/// duplicate presentations of the *same* token on the *same* connection
/// (the Phase 1 idempotency case) vs. presentations of a *different* token
/// on the same connection (e.g. a token rotation, which must re-validate).
///
/// The fingerprint is the first 16 hex chars of SHA-256 over the raw token
/// bytes — short enough to log, long enough to make collisions astronomically
/// unlikely in practice. It is intentionally not cryptographically reversible:
/// even logged in production, it does not leak the token.
pub fn token_fingerprint(token: &str) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(token.as_bytes());
    hex::encode(&digest[..8])
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeTrustedConnectionContext {
    pub connection_id: String,
    pub remote_node_id: Option<String>,
    pub known_device_id: Option<String>,
    pub claimed_device_id: Option<String>,
}

pub type NativeTrustedConnectionVerifier =
    Arc<dyn Fn(&NativeTrustedConnectionContext) -> Option<String> + Send + Sync>;

/// RAII handle returned by [`SessionTokenRegistry::begin_admission_response`].
/// While this guard exists, the registry reports
/// `is_session_token_admission_in_flight(connection_id) == true`. Drop it
/// only after the response has been fully written to the wire.
pub struct AdmissionResponseGuard {
    connection_id: String,
    counts: Arc<RwLock<HashMap<String, u32>>>,
}

impl AdmissionResponseGuard {
    pub fn connection_id(&self) -> &str {
        &self.connection_id
    }
}

impl Drop for AdmissionResponseGuard {
    fn drop(&mut self) {
        if let Ok(mut counts) = self.counts.write() {
            if let Some(n) = counts.get_mut(&self.connection_id) {
                if *n > 0 {
                    *n -= 1;
                }
                if *n == 0 {
                    counts.remove(&self.connection_id);
                }
            }
        }
    }
}

/// Thread-safe registry of active session tokens.
#[derive(Default, Clone)]
pub struct SessionTokenRegistry {
    inner: Arc<RwLock<HashMap<String, SessionToken>>>,
    /// Maps connection_id → scope for connections validated with a token.
    /// Used by `revoke_by_scope` to return connection IDs that should be disconnected.
    validated_connections: Arc<RwLock<HashMap<String, GrantScope>>>,
    admissions: Arc<RwLock<HashMap<String, SessionAdmission>>>,
    /// Per-connection record of the token fingerprint that produced the
    /// current admission verdict. Used by Phase 1 callers to distinguish
    /// "same token replayed" (idempotent) from "different token presented on
    /// the same connection" (must re-validate).
    admission_fingerprints: Arc<RwLock<HashMap<String, String>>>,
    /// Per-connection counter of in-flight session-token response writers.
    /// While this is non-zero for a connection, the transport must not be
    /// retired/replaced (otherwise the response stream the dialer is reading
    /// closes mid-flight → `0 bytes read`).
    in_flight_admissions: Arc<RwLock<HashMap<String, u32>>>,
    /// Maps `token_fingerprint:payload_nonce` → connection_id. Payload nonce
    /// replay on a different connection is rejected when modern peers present
    /// the compact token payload suffix alongside the raw token.
    seen_payload_nonces: Arc<RwLock<HashMap<String, String>>>,
    native_trusted_connection_verifier: Arc<RwLock<Option<NativeTrustedConnectionVerifier>>>,
}

impl SessionTokenRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new token. Replaces any existing token with the same value.
    pub fn register(&self, token: String, scope: impl Into<GrantScope>, max_connections: u32) {
        self.register_with_expiry_ms(token, scope, max_connections, None);
    }

    /// Register a new token with an optional absolute Unix-millisecond expiry.
    pub fn register_with_expiry_ms(
        &self,
        token: String,
        scope: impl Into<GrantScope>,
        max_connections: u32,
        expires_at_ms: Option<u64>,
    ) {
        let entry = SessionToken {
            token: token.clone(),
            scope: scope.into(),
            max_connections,
            use_count: 0,
            expires_at_ms,
        };
        if let Ok(mut map) = self.inner.write() {
            map.insert(token, entry);
        }
    }

    /// Validate a token and increment its use count.
    ///
    /// Returns `Ok(scope)` on success, `Err(reason)` on failure.
    /// If the registry is empty, returns `Ok("")` (backward-compat gate).
    pub fn validate_and_consume(&self, token: &str) -> Result<GrantScope, String> {
        self.validate_and_consume_for_connection(token, None)
    }

    /// Validate a token, increment its use count, and optionally record the
    /// connection_id so `revoke_by_scope` can return affected connections.
    pub fn validate_and_consume_for_connection(
        &self,
        token: &str,
        connection_id: Option<&str>,
    ) -> Result<GrantScope, String> {
        self.validate_and_consume_for_connection_with_payload(token, connection_id, None)
    }

    /// Validate a raw session token with optional compact payload metadata.
    ///
    /// Legacy callers may omit `payload_suffix`; modern compound-ticket callers
    /// should provide it so the host can enforce the payload audience, expiry,
    /// token binding, and nonce replay checks instead of seeing only the raw
    /// bearer token.
    pub fn validate_and_consume_for_connection_with_payload(
        &self,
        token: &str,
        connection_id: Option<&str>,
        payload_suffix: Option<&str>,
    ) -> Result<GrantScope, String> {
        let presented_fp = if !token.is_empty() {
            Some(token_fingerprint(token))
        } else {
            None
        };

        if let Some(conn_id) = connection_id {
            // Phase 1 idempotency: if this connection is already admitted
            // with a token whose fingerprint matches the presented token,
            // return the cached verdict deterministically. If the presented
            // token's fingerprint *differs* from the one originally admitted,
            // do not auto-accept — fall through to the registry path so a
            // rotated/forged token is re-validated.
            let cached_fp = self.admission_fingerprint(conn_id);
            match self.admission(conn_id) {
                SessionAdmission::Accepted {
                    mechanism: SessionAdmissionMechanism::SessionToken,
                    scope: Some(scope),
                    ..
                } if cached_fp.is_none()
                    || presented_fp.is_none()
                    || cached_fp.as_deref() == presented_fp.as_deref() =>
                {
                    return Ok(scope);
                }
                SessionAdmission::Rejected { reason } => {
                    return Err(reason);
                }
                _ => {}
            }
        }

        let map = self
            .inner
            .read()
            .map_err(|_| "registry lock poisoned".to_string())?;

        // Backward-compat gate: empty registry = no validation.
        if map.is_empty() {
            return Ok(GrantScope::new(String::new()));
        }

        let entry = map
            .get(token)
            .ok_or_else(|| "unknown session token".to_string())?;

        if let Some(suffix) = payload_suffix {
            self.validate_presented_payload_suffix(
                token,
                connection_id,
                suffix,
                entry.max_connections,
            )?;
        }

        if entry
            .expires_at_ms
            .is_some_and(|expires_at_ms| expires_at_ms <= now_unix_ms())
        {
            drop(map);
            if let Ok(mut map) = self.inner.write() {
                map.remove(token);
            }
            return Err("session token expired".to_string());
        }

        if entry.max_connections > 0 && entry.use_count >= entry.max_connections {
            return Err(format!(
                "session token exhausted (max={} used={})",
                entry.max_connections, entry.use_count
            ));
        }

        let scope = entry.scope.clone();
        drop(map);

        // Increment use count.
        if let Ok(mut map) = self.inner.write() {
            if let Some(entry) = map.get_mut(token) {
                entry.use_count += 1;
            }
        }

        // Record the connection → scope binding for revocation, the
        // admission verdict, and the token fingerprint that produced it.
        if let Some(conn_id) = connection_id {
            if let Ok(mut conns) = self.validated_connections.write() {
                conns.insert(conn_id.to_string(), scope.clone());
            }
            self.mark_accepted(
                conn_id,
                SessionAdmissionMechanism::SessionToken,
                Some(scope.clone()),
                None,
            );
            if let Some(fp) = presented_fp.as_ref() {
                if let Ok(mut fps) = self.admission_fingerprints.write() {
                    fps.insert(conn_id.to_string(), fp.clone());
                }
            }
        }

        Ok(scope)
    }

    /// Phase 1 verdict-only API. Returns the deterministic admission verdict
    /// for `(token, connection_id)` *without* running any post-admission side
    /// effects (no `accept_replacement_peer`, no WebRTC recovery, no
    /// transport replacement). Callers must:
    ///   1. Call this to compute the verdict.
    ///   2. Write + flush the response to the wire.
    ///   3. Then run their post-admission side effects (e.g. via
    ///      `Client::run_post_session_token_admission_side_effects`).
    ///
    /// This separation is what eliminates the `0 bytes read` race where the
    /// host's lifecycle hooks would retire the very transport the response
    /// writer was using before it could flush.
    pub fn validate_with_cached_response(
        &self,
        token: &str,
        connection_id: &str,
    ) -> Result<GrantScope, String> {
        self.validate_with_cached_response_and_payload(token, connection_id, None)
    }

    pub fn validate_with_cached_response_and_payload(
        &self,
        token: &str,
        connection_id: &str,
        payload_suffix: Option<&str>,
    ) -> Result<GrantScope, String> {
        self.validate_and_consume_for_connection_with_payload(
            token,
            Some(connection_id),
            payload_suffix,
        )
    }

    /// Mark a session-token response writer as in-flight for `connection_id`.
    /// Returns a guard whose `Drop` decrements the counter. While any guard
    /// is alive for a given connection, the transport must not be
    /// closed/retired by lifecycle code (see `is_session_token_admission_in_flight`).
    pub fn begin_admission_response(&self, connection_id: &str) -> AdmissionResponseGuard {
        if let Ok(mut counts) = self.in_flight_admissions.write() {
            *counts.entry(connection_id.to_string()).or_insert(0) += 1;
        }
        AdmissionResponseGuard {
            connection_id: connection_id.to_string(),
            counts: self.in_flight_admissions.clone(),
        }
    }

    /// True while at least one session-token response writer is mid-flight
    /// for `connection_id`. Lifecycle code (zombie-replace, managed-retire)
    /// must defer transport teardown while this returns true to avoid the
    /// `[session-token-response:protocol-byte] 0 bytes read` failure.
    pub fn is_session_token_admission_in_flight(&self, connection_id: &str) -> bool {
        self.in_flight_admissions
            .read()
            .ok()
            .and_then(|counts| counts.get(connection_id).copied())
            .map(|n| n > 0)
            .unwrap_or(false)
    }

    pub fn admission_fingerprint(&self, connection_id: &str) -> Option<String> {
        self.admission_fingerprints
            .read()
            .ok()
            .and_then(|fps| fps.get(connection_id).cloned())
    }

    /// Revoke a specific token.
    pub fn revoke(&self, token: &str) {
        if let Ok(mut map) = self.inner.write() {
            map.remove(token);
        }
        let nonce_key_prefix = format!("{}:", token_fingerprint(token));
        if let Ok(mut seen) = self.seen_payload_nonces.write() {
            seen.retain(|key, _| !key.starts_with(&nonce_key_prefix));
        }
    }

    /// Revoke all tokens with the given scope.
    /// Returns the connection IDs that were validated with tokens of this scope.
    pub fn revoke_by_scope(&self, scope: impl AsRef<str>) -> Vec<String> {
        let scope = scope.as_ref();
        if let Ok(mut map) = self.inner.write() {
            map.retain(|_, v| v.scope.as_str() != scope);
        }

        let mut affected = Vec::new();
        if let Ok(mut conns) = self.validated_connections.write() {
            conns.retain(|conn_id, conn_scope| {
                if conn_scope.as_str() == scope {
                    affected.push(conn_id.clone());
                    false
                } else {
                    true
                }
            });
        }
        if let Ok(mut admissions) = self.admissions.write() {
            for connection_id in &affected {
                admissions.remove(connection_id);
            }
        }
        if let Ok(mut fps) = self.admission_fingerprints.write() {
            for connection_id in &affected {
                fps.remove(connection_id);
            }
        }
        affected
    }

    /// Remove all tokens and validated connection bindings.
    pub fn clear(&self) {
        if let Ok(mut map) = self.inner.write() {
            map.clear();
        }
        if let Ok(mut conns) = self.validated_connections.write() {
            conns.clear();
        }
        if let Ok(mut admissions) = self.admissions.write() {
            admissions.clear();
        }
        if let Ok(mut fps) = self.admission_fingerprints.write() {
            fps.clear();
        }
        if let Ok(mut counts) = self.in_flight_admissions.write() {
            counts.clear();
        }
        if let Ok(mut seen) = self.seen_payload_nonces.write() {
            seen.clear();
        }
    }

    /// True if no tokens are registered (backward-compat gate).
    pub fn is_empty(&self) -> bool {
        self.inner.read().map(|m| m.is_empty()).unwrap_or(true)
    }

    pub fn admission(&self, connection_id: &str) -> SessionAdmission {
        self.admissions
            .read()
            .ok()
            .and_then(|admissions| admissions.get(connection_id).cloned())
            .unwrap_or(SessionAdmission::Pending)
    }

    /// True when this connection is already admitted via session token.
    ///
    /// Used to detect duplicate token frames on the same logical connection (e.g. new iroh
    /// substreams re-sending the compound ticket) — those must not re-trigger native WebRTC
    /// upgrade recovery, which is only appropriate for the **first** token presentation.
    pub fn is_session_token_admitted_for_connection(&self, connection_id: &str) -> bool {
        matches!(
            self.admission(connection_id),
            SessionAdmission::Accepted {
                mechanism: SessionAdmissionMechanism::SessionToken,
                ..
            }
        )
    }

    pub fn mark_rejected(&self, connection_id: &str, reason: impl Into<String>) {
        if let Ok(mut admissions) = self.admissions.write() {
            admissions.insert(
                connection_id.to_string(),
                SessionAdmission::Rejected {
                    reason: reason.into(),
                },
            );
        }
    }

    pub fn mark_accepted(
        &self,
        connection_id: &str,
        mechanism: SessionAdmissionMechanism,
        scope: Option<GrantScope>,
        authoritative_device_id: Option<String>,
    ) {
        if let Ok(mut admissions) = self.admissions.write() {
            admissions.insert(
                connection_id.to_string(),
                SessionAdmission::Accepted {
                    mechanism,
                    scope,
                    authoritative_device_id,
                },
            );
        }
    }

    pub fn bind_connection_scope(
        &self,
        connection_id: &str,
        scope: impl Into<GrantScope>,
        authoritative_device_id: Option<String>,
    ) {
        let scope = scope.into();
        if let Ok(mut conns) = self.validated_connections.write() {
            conns.insert(connection_id.to_string(), scope.clone());
        }
        self.mark_accepted(
            connection_id,
            SessionAdmissionMechanism::SessionToken,
            Some(scope),
            authoritative_device_id,
        );
    }

    pub fn forget_connection(&self, connection_id: &str) {
        if let Ok(mut conns) = self.validated_connections.write() {
            conns.remove(connection_id);
        }
        if let Ok(mut admissions) = self.admissions.write() {
            admissions.remove(connection_id);
        }
        if let Ok(mut fps) = self.admission_fingerprints.write() {
            fps.remove(connection_id);
        }
        if let Ok(mut counts) = self.in_flight_admissions.write() {
            counts.remove(connection_id);
        }
    }

    pub fn set_native_trusted_connection_verifier(
        &self,
        verifier: Option<NativeTrustedConnectionVerifier>,
    ) {
        if let Ok(mut slot) = self.native_trusted_connection_verifier.write() {
            *slot = verifier;
        }
    }

    pub fn evaluate_trusted_native_connection(
        &self,
        context: &NativeTrustedConnectionContext,
    ) -> Option<String> {
        self.native_trusted_connection_verifier
            .read()
            .ok()
            .and_then(|slot| slot.as_ref().and_then(|verifier| verifier(context)))
    }

    fn validate_presented_payload_suffix(
        &self,
        token: &str,
        connection_id: Option<&str>,
        payload_suffix: &str,
        max_connections: u32,
    ) -> Result<(), String> {
        let payload = decode_token_payload(payload_suffix)
            .ok_or_else(|| "invalid session token payload".to_string())?;
        if payload.token != token {
            return Err("session token payload mismatch".to_string());
        }
        if !token_payload_metadata_is_valid(&payload) {
            return Err("invalid session token payload metadata".to_string());
        }

        // The per-connection nonce binding is single-use anti-replay protection
        // for out-of-band share tickets (`max_connections == 1`). A multi-use or
        // unlimited presence ticket (e.g. `user-device`, `max_connections != 1`)
        // is advertised once and legitimately presented by EVERY dialing peer:
        // each dialer forwards the same signed payload nonce verbatim because it
        // cannot re-mint the ticket-bound payload (see
        // `auto_connect_impl::extracted_token_suffix`). Binding that shared nonce
        // to the first connection would falsely reject every other device as a
        // "nonce replayed" attacker and churn the mesh. Multi-use bounds are
        // enforced independently by `use_count >= max_connections`, so only
        // genuine single-use tokens need the per-connection nonce binding.
        if max_connections != 1 {
            return Ok(());
        }

        let Some(nonce) = payload.nonce.as_deref() else {
            return Ok(());
        };
        let Some(connection_id) = connection_id else {
            return Ok(());
        };

        let replay_key = format!("{}:{}", token_fingerprint(token), nonce);
        let mut seen = self
            .seen_payload_nonces
            .write()
            .map_err(|_| "registry lock poisoned".to_string())?;
        match seen.get(&replay_key) {
            Some(existing_connection_id) if existing_connection_id != connection_id => {
                Err("session token payload nonce replayed".to_string())
            }
            Some(_) => Ok(()),
            None => {
                seen.insert(replay_key, connection_id.to_string());
                Ok(())
            }
        }
    }
}

// --------------------------------------------------------------------------
// Compact token payload for embedding in ticket strings
// --------------------------------------------------------------------------

/// Decoded token payload embedded in a compound ticket.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenPayload {
    /// Raw token value.
    #[serde(rename = "t")]
    pub token: String,
    /// Scope string.
    #[serde(rename = "s")]
    pub scope: GrantScope,
    /// Max connections (0 = unlimited).
    #[serde(rename = "m")]
    pub max_connections: u32,
    /// SHA-256 hash of the endpoint ticket this payload was minted for.
    #[serde(rename = "h", default, skip_serializing_if = "Option::is_none")]
    pub ticket_hash: Option<String>,
    /// Absolute Unix-millisecond expiry.
    #[serde(rename = "e", default, skip_serializing_if = "Option::is_none")]
    pub expires_at_ms: Option<u64>,
    /// Explicit intended consumer for this compact payload.
    #[serde(rename = "a", default, skip_serializing_if = "Option::is_none")]
    pub audience: Option<String>,
    /// Per-payload nonce used to distinguish otherwise equivalent grants.
    #[serde(rename = "n", default, skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>,
}

/// Encode a token payload as a base64url (no padding) string.
pub fn encode_token_payload(
    token: &str,
    scope: impl Into<GrantScope>,
    max_connections: u32,
) -> String {
    let scope = scope.into();
    let payload = TokenPayload {
        token: token.to_string(),
        scope,
        max_connections,
        ticket_hash: None,
        expires_at_ms: None,
        audience: None,
        nonce: None,
    };
    let json = serde_json::to_string(&payload).unwrap_or_default();
    URL_SAFE_NO_PAD.encode(json.as_bytes())
}

/// Stable hash that binds a compact token payload to the endpoint ticket it
/// grants access to. The full SHA-256 digest is kept because this value is
/// carried inside bearer material rather than used only for logs.
pub fn endpoint_ticket_hash(iroh_ticket: &str) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(iroh_ticket.as_bytes());
    hex::encode(digest)
}

/// Encode a token payload and bind it to a specific endpoint ticket.
pub fn encode_token_payload_for_ticket(
    iroh_ticket: &str,
    token: &str,
    scope: impl Into<GrantScope>,
    max_connections: u32,
) -> String {
    encode_token_payload_for_ticket_with_expiry(iroh_ticket, token, scope, max_connections, None)
}

/// Encode a token payload, bind it to a specific endpoint ticket, and optionally
/// include the absolute expiry enforced by the host registry.
pub fn encode_token_payload_for_ticket_with_expiry(
    iroh_ticket: &str,
    token: &str,
    scope: impl Into<GrantScope>,
    max_connections: u32,
    expires_at_ms: Option<u64>,
) -> String {
    let scope = scope.into();
    let payload = TokenPayload {
        token: token.to_string(),
        scope,
        max_connections,
        ticket_hash: Some(endpoint_ticket_hash(iroh_ticket)),
        expires_at_ms,
        audience: Some(TOKEN_PAYLOAD_ENDPOINT_TICKET_AUDIENCE.to_string()),
        nonce: Some(generate_payload_nonce()),
    };
    let json = serde_json::to_string(&payload).unwrap_or_default();
    URL_SAFE_NO_PAD.encode(json.as_bytes())
}

/// Decode a base64url token payload string.
pub fn decode_token_payload(encoded: &str) -> Option<TokenPayload> {
    let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
    serde_json::from_slice(&bytes).ok()
}

/// Check whether a decoded payload is bound to the provided endpoint ticket.
///
/// Legacy payloads without `h` are accepted for backward compatibility.
pub fn token_payload_matches_ticket(iroh_ticket: &str, payload: &TokenPayload) -> bool {
    let ticket_matches = payload
        .ticket_hash
        .as_deref()
        .map_or(true, |hash| hash == endpoint_ticket_hash(iroh_ticket));
    let not_expired = payload
        .expires_at_ms
        .map_or(true, |expires_at_ms| expires_at_ms > now_unix_ms());
    ticket_matches && not_expired && token_payload_metadata_is_valid(payload)
}

pub fn token_payload_metadata_is_valid(payload: &TokenPayload) -> bool {
    let audience_matches = payload.audience.as_deref().map_or(true, |audience| {
        audience == TOKEN_PAYLOAD_ENDPOINT_TICKET_AUDIENCE
    });
    let nonce_is_valid = payload
        .nonce
        .as_deref()
        .map_or(true, is_valid_payload_nonce);
    let not_expired = payload
        .expires_at_ms
        .map_or(true, |expires_at_ms| expires_at_ms > now_unix_ms());
    audience_matches && nonce_is_valid && not_expired
}

/// Decode a token payload and reject it if its endpoint-ticket binding does
/// not match the accompanying iroh ticket.
pub fn decode_token_payload_for_ticket(iroh_ticket: &str, encoded: &str) -> Option<TokenPayload> {
    let payload = decode_token_payload(encoded)?;
    token_payload_matches_ticket(iroh_ticket, &payload).then_some(payload)
}

/// Split a (possibly compound) ticket string into `(iroh_ticket, Option<token_payload>)`.
///
/// If the string contains a `.`, everything before the last `.` is the iroh ticket
/// and everything after is the base64url-encoded token payload.
pub fn split_compound_ticket(compound: &str) -> (&str, Option<&str>) {
    match compound.rfind('.') {
        Some(pos) => (&compound[..pos], Some(&compound[pos + 1..])),
        None => (compound, None),
    }
}

/// Build a compound ticket by appending a token suffix bound to the endpoint ticket.
pub fn build_compound_ticket(
    iroh_ticket: &str,
    token: &str,
    scope: impl Into<GrantScope>,
    max_connections: u32,
) -> String {
    build_compound_ticket_with_expiry(iroh_ticket, token, scope, max_connections, None)
}

/// Build a compound ticket with an optional host-enforced absolute expiry.
pub fn build_compound_ticket_with_expiry(
    iroh_ticket: &str,
    token: &str,
    scope: impl Into<GrantScope>,
    max_connections: u32,
    expires_at_ms: Option<u64>,
) -> String {
    let scope = scope.into();
    let suffix = encode_token_payload_for_ticket_with_expiry(
        iroh_ticket,
        token,
        scope,
        max_connections,
        expires_at_ms,
    );
    format!("{}.{}", iroh_ticket, suffix)
}

// --------------------------------------------------------------------------
// Token generation
// --------------------------------------------------------------------------

/// Generate a cryptographically random 32-character alphanumeric token.
/// Uses the platform's secure RNG (getrandom on WASM, OsRng on native).
pub fn generate_token() -> String {
    let mut bytes = [0u8; 24]; // 24 bytes → 32 base64url chars (no padding)
    getrandom::getrandom(&mut bytes).expect("getrandom failed");
    URL_SAFE_NO_PAD.encode(bytes)
}

pub fn generate_payload_nonce() -> String {
    let mut bytes = [0u8; TOKEN_PAYLOAD_NONCE_BYTES];
    getrandom::getrandom(&mut bytes).expect("getrandom failed");
    URL_SAFE_NO_PAD.encode(bytes)
}

fn is_valid_payload_nonce(nonce: &str) -> bool {
    URL_SAFE_NO_PAD
        .decode(nonce)
        .map(|bytes| bytes.len() == TOKEN_PAYLOAD_NONCE_BYTES)
        .unwrap_or(false)
}

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

    #[test]
    fn test_split_no_dot() {
        let ticket = "endpointabcdef123456";
        let (iroh, token) = split_compound_ticket(ticket);
        assert_eq!(iroh, "endpointabcdef123456");
        assert!(token.is_none());
    }

    #[test]
    fn test_split_with_dot() {
        let encoded = encode_token_payload("my-token", "share", 5);
        let compound = format!("endpointabcdef123456.{}", encoded);
        let (iroh, token_str) = split_compound_ticket(&compound);
        assert_eq!(iroh, "endpointabcdef123456");
        let payload = decode_token_payload(token_str.unwrap()).unwrap();
        assert_eq!(payload.token, "my-token");
        assert_eq!(payload.scope, "share");
        assert_eq!(payload.max_connections, 5);
    }

    #[test]
    fn test_split_uses_last_dot_for_ticket_with_embedded_dots() {
        let encoded = encode_token_payload("my-token", "trusted", 0);
        let iroh_ticket = "ticket.with.embedded.dots";
        let compound = format!("{}.{}", iroh_ticket, encoded);
        let (recovered_ticket, token_str) = split_compound_ticket(&compound);

        assert_eq!(recovered_ticket, iroh_ticket);
        let payload = decode_token_payload(token_str.expect("token suffix")).expect("payload");
        assert_eq!(payload.token, "my-token");
        assert_eq!(payload.scope, "trusted");
    }

    #[test]
    fn test_registry_empty_gate() {
        let registry = SessionTokenRegistry::new();
        // Empty registry allows all.
        assert!(registry.validate_and_consume("anything").is_ok());
    }

    #[test]
    fn test_registry_validate_consume() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok1".to_string(), "share".to_string(), 2);

        assert_eq!(registry.validate_and_consume("tok1").unwrap(), "share");
        assert_eq!(registry.validate_and_consume("tok1").unwrap(), "share");
        // Third attempt should fail (max=2).
        assert!(registry.validate_and_consume("tok1").is_err());
    }

    #[test]
    fn test_registry_unlimited() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok2".to_string(), "magic-link".to_string(), 0);

        for _ in 0..100 {
            assert!(registry.validate_and_consume("tok2").is_ok());
        }
    }

    #[test]
    fn test_registry_rejects_expired_token() {
        let registry = SessionTokenRegistry::new();
        registry.register_with_expiry_ms(
            "expired-token".to_string(),
            "share".to_string(),
            0,
            Some(now_unix_ms().saturating_sub(1)),
        );
        registry.register("sentinel".to_string(), "sentinel".to_string(), 0);

        assert_eq!(
            registry.validate_and_consume("expired-token").unwrap_err(),
            "session token expired"
        );
        assert_eq!(
            registry.validate_and_consume("expired-token").unwrap_err(),
            "unknown session token"
        );
    }

    #[test]
    fn test_revoke_by_scope() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok1".to_string(), "share".to_string(), 0);
        registry.register("tok2".to_string(), "share".to_string(), 0);
        registry.register("tok3".to_string(), "other".to_string(), 0);

        registry.revoke_by_scope("share");

        // Share tokens are gone → registry still has "other" so empty-gate doesn't apply.
        assert!(registry.validate_and_consume("tok1").is_err());
        assert!(registry.validate_and_consume("tok2").is_err());
        assert!(registry.validate_and_consume("tok3").is_ok());
    }

    #[test]
    fn test_generate_token_length() {
        let t = generate_token();
        // 24 bytes → 32 base64url chars (no padding).
        assert_eq!(t.len(), 32);
    }

    #[test]
    fn test_build_and_split_compound_ticket_roundtrip() {
        let iroh_ticket = "abcdef1234567890abcdef";
        let token = "my-secret-token";
        let scope = "share";
        let max_conn = 3;

        let compound = build_compound_ticket(iroh_ticket, token, scope, max_conn);

        // Compound ticket contains exactly one dot
        assert_eq!(compound.matches('.').count(), 1);

        // Split recovers the iroh ticket and decodes the token payload
        let (recovered_ticket, suffix) = split_compound_ticket(&compound);
        assert_eq!(recovered_ticket, iroh_ticket);

        let payload = decode_token_payload(suffix.unwrap()).unwrap();
        assert_eq!(payload.token, token);
        assert_eq!(payload.scope, scope);
        assert_eq!(payload.max_connections, max_conn);
        assert_eq!(
            payload.ticket_hash.as_deref(),
            Some(endpoint_ticket_hash(iroh_ticket).as_str())
        );
        assert_eq!(
            payload.audience.as_deref(),
            Some(TOKEN_PAYLOAD_ENDPOINT_TICKET_AUDIENCE)
        );
        assert!(payload.nonce.as_deref().is_some_and(is_valid_payload_nonce));
        assert!(token_payload_matches_ticket(iroh_ticket, &payload));
        assert!(
            decode_token_payload_for_ticket("different-endpoint-ticket", suffix.unwrap()).is_none()
        );
    }

    #[test]
    fn test_bound_compound_ticket_rejects_wrong_audience_and_bad_nonce() {
        let iroh_ticket = "endpoint-ticket";
        let encoded = encode_token_payload_for_ticket(iroh_ticket, "token", "share", 1);
        let mut payload = decode_token_payload(&encoded).unwrap();

        payload.audience = Some("openrtc:other-audience:v1".to_string());
        assert!(!token_payload_matches_ticket(iroh_ticket, &payload));

        payload.audience = Some(TOKEN_PAYLOAD_ENDPOINT_TICKET_AUDIENCE.to_string());
        payload.nonce = Some("not-valid-base64url-nonce".to_string());
        assert!(!token_payload_matches_ticket(iroh_ticket, &payload));
    }

    #[test]
    fn test_bound_compound_ticket_nonces_are_unique() {
        let first = build_compound_ticket("endpoint-ticket", "token-one", "share", 1);
        let second = build_compound_ticket("endpoint-ticket", "token-two", "share", 1);
        let (_, first_suffix) = split_compound_ticket(&first);
        let (_, second_suffix) = split_compound_ticket(&second);
        let first_payload = decode_token_payload(first_suffix.unwrap()).unwrap();
        let second_payload = decode_token_payload(second_suffix.unwrap()).unwrap();

        assert_ne!(first_payload.nonce, second_payload.nonce);
        assert!(first_payload
            .nonce
            .as_deref()
            .is_some_and(is_valid_payload_nonce));
        assert!(second_payload
            .nonce
            .as_deref()
            .is_some_and(is_valid_payload_nonce));
    }

    #[test]
    fn test_single_use_payload_nonce_replay_rejected_across_connections() {
        // A single-use share ticket (max_connections == 1) binds its nonce to the
        // first admitting connection; a different connection presenting the same
        // out-of-band nonce is a replay and must be rejected.
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "share".to_string(), 1);
        let suffix = encode_token_payload_for_ticket("endpoint-ticket", "tok", "share", 1);

        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "tok",
                    Some("conn-A"),
                    Some(&suffix),
                )
                .unwrap(),
            "share"
        );
        // Idempotent re-presentation on the SAME connection still succeeds.
        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "tok",
                    Some("conn-A"),
                    Some(&suffix),
                )
                .unwrap(),
            "share"
        );
        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "tok",
                    Some("conn-B"),
                    Some(&suffix),
                )
                .unwrap_err(),
            "session token payload nonce replayed"
        );
    }

    #[test]
    fn test_multi_connection_payload_nonce_allowed_across_connections() {
        // A multi-use / unlimited presence ticket (max_connections == 0, e.g.
        // `user-device`) is advertised once and presented by every dialing peer,
        // each forwarding the SAME signed nonce. This must NOT be treated as a
        // replay — otherwise the second device in a same-user mesh is falsely
        // rejected and the connection churns. Regression test for the
        // browser↔native mesh stranding at session-admission-pending.
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "user-device".to_string(), 0);
        let suffix = encode_token_payload_for_ticket("endpoint-ticket", "tok", "user-device", 0);

        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "tok",
                    Some("conn-A"),
                    Some(&suffix),
                )
                .unwrap(),
            "user-device"
        );
        // A different connection presenting the same advertised nonce is a
        // legitimate second mesh peer, not a replay attacker.
        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "tok",
                    Some("conn-B"),
                    Some(&suffix),
                )
                .unwrap(),
            "user-device"
        );
        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "tok",
                    Some("conn-C"),
                    Some(&suffix),
                )
                .unwrap(),
            "user-device"
        );
    }

    #[test]
    fn test_payload_metadata_must_match_presented_token() {
        let registry = SessionTokenRegistry::new();
        registry.register("real-token".to_string(), "share".to_string(), 0);
        let suffix = encode_token_payload_for_ticket("endpoint-ticket", "other-token", "share", 0);

        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "real-token",
                    Some("conn-A"),
                    Some(&suffix),
                )
                .unwrap_err(),
            "session token payload mismatch"
        );
    }

    #[test]
    fn test_bound_compound_ticket_rejects_suffix_graft() {
        let first_ticket = "endpoint-ticket-one";
        let second_ticket = "endpoint-ticket-two";
        let first_compound = build_compound_ticket(first_ticket, "token-one", "share", 1);
        let second_compound = build_compound_ticket(second_ticket, "token-two", "share", 1);

        let (_, first_suffix) = split_compound_ticket(&first_compound);
        let grafted = format!("{}.{}", second_ticket, first_suffix.unwrap());
        let (grafted_ticket, grafted_suffix) = split_compound_ticket(&grafted);

        assert_eq!(grafted_ticket, second_ticket);
        assert!(
            decode_token_payload_for_ticket(grafted_ticket, grafted_suffix.unwrap()).is_none(),
            "a suffix minted for one endpoint ticket must not validate on another endpoint ticket"
        );

        let (_, second_suffix) = split_compound_ticket(&second_compound);
        let payload =
            decode_token_payload_for_ticket(second_ticket, second_suffix.unwrap()).unwrap();
        assert_eq!(payload.token, "token-two");
    }

    #[test]
    fn test_compound_ticket_payload_carries_expiry() {
        let expires_at_ms = now_unix_ms().saturating_add(DEFAULT_RESTRICTED_SESSION_TOKEN_TTL_MS);
        let compound = build_compound_ticket_with_expiry(
            "endpoint-ticket",
            "token-with-expiry",
            "share",
            1,
            Some(expires_at_ms),
        );
        let (iroh_ticket, suffix) = split_compound_ticket(&compound);
        let payload = decode_token_payload_for_ticket(iroh_ticket, suffix.unwrap()).unwrap();

        assert_eq!(payload.token, "token-with-expiry");
        assert_eq!(payload.expires_at_ms, Some(expires_at_ms));
        assert_eq!(
            payload.audience.as_deref(),
            Some(TOKEN_PAYLOAD_ENDPOINT_TICKET_AUDIENCE)
        );
        assert!(payload.nonce.as_deref().is_some_and(is_valid_payload_nonce));
    }

    #[test]
    fn test_build_compound_ticket_then_registry_validate() {
        // Simulates: host generates compound ticket → guest extracts token → host validates
        let registry = SessionTokenRegistry::new();
        let token = generate_token();
        let scope = "share";
        registry.register(token.clone(), scope.to_string(), 1);

        let compound = build_compound_ticket("irohticketbase32", &token, scope, 1);
        let (_iroh, suffix) = split_compound_ticket(&compound);
        let payload = decode_token_payload(suffix.unwrap()).unwrap();
        assert!(token_payload_matches_ticket("irohticketbase32", &payload));

        // Validate the extracted token against the registry
        let result = registry.validate_and_consume(&payload.token);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "share");

        // Second use should fail (max_connections = 1)
        let result2 = registry.validate_and_consume(&payload.token);
        assert!(result2.is_err());
    }

    #[test]
    fn test_revoke_single_token() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok-a".to_string(), "share".to_string(), 0);
        registry.register("tok-b".to_string(), "share".to_string(), 0);

        registry.revoke("tok-a");

        // tok-a gone, tok-b still works
        assert!(registry.validate_and_consume("tok-a").is_err());
        assert!(registry.validate_and_consume("tok-b").is_ok());
    }

    #[test]
    fn test_registry_clear() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok-x".to_string(), "share".to_string(), 0);
        assert!(!registry.is_empty());

        registry.clear();
        assert!(registry.is_empty());

        // Empty registry = backward-compat gate passes everything
        assert!(registry.validate_and_consume("anything").is_ok());
    }

    #[test]
    fn test_ts_encoded_payload_is_decodable() {
        // This payload was generated by the TS test helpers — ensures cross-language compat
        // TS: JSON.stringify({t:"test-token",s:"share",m:0}) → base64url
        let json = r#"{"t":"test-token","s":"share","m":0}"#;
        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
        let payload = decode_token_payload(&encoded).unwrap();
        assert_eq!(payload.token, "test-token");
        assert_eq!(payload.scope, "share");
        assert_eq!(payload.max_connections, 0);
    }

    #[test]
    fn test_generated_token_uniqueness() {
        let tokens: Vec<String> = (0..100).map(|_| generate_token()).collect();
        let unique: std::collections::HashSet<&String> = tokens.iter().collect();
        assert_eq!(unique.len(), 100, "generated tokens must be unique");
    }

    #[test]
    fn test_revoke_by_scope_returns_affected_connections() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok-share-1".to_string(), "share".to_string(), 0);
        registry.register("tok-share-2".to_string(), "share".to_string(), 0);
        registry.register("tok-other".to_string(), "other".to_string(), 0);

        // Validate with connection IDs
        registry
            .validate_and_consume_for_connection("tok-share-1", Some("conn-A"))
            .unwrap();
        registry
            .validate_and_consume_for_connection("tok-share-2", Some("conn-B"))
            .unwrap();
        registry
            .validate_and_consume_for_connection("tok-other", Some("conn-C"))
            .unwrap();

        // Revoke "share" scope — should return conn-A and conn-B
        let mut affected = registry.revoke_by_scope("share");
        affected.sort();
        assert_eq!(affected, vec!["conn-A", "conn-B"]);

        // conn-C should still be tracked
        let affected2 = registry.revoke_by_scope("other");
        assert_eq!(affected2, vec!["conn-C"]);
    }

    #[test]
    fn test_revoke_scoped_guest_scope_isolates_grants() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok-a".to_string(), "scoped:grant-a".to_string(), 0);
        registry.register("tok-b".to_string(), "scoped:grant-b".to_string(), 0);
        registry
            .validate_and_consume_for_connection("tok-a", Some("conn-a"))
            .unwrap();
        registry
            .validate_and_consume_for_connection("tok-b", Some("conn-b"))
            .unwrap();
        let affected = registry.revoke_by_scope("scoped:grant-a");
        assert_eq!(affected, vec!["conn-a"]);
        assert!(registry.validate_and_consume("tok-b").is_ok());
        assert!(registry.validate_and_consume("tok-a").is_err());
    }

    #[test]
    fn test_validate_for_connection_rejects_without_token() {
        let registry = SessionTokenRegistry::new();
        registry.register("real-tok".to_string(), "share".to_string(), 0);

        // No token → rejected
        let result = registry.validate_and_consume_for_connection("", Some("conn-X"));
        assert!(result.is_err());

        // Wrong token → rejected
        let result = registry.validate_and_consume_for_connection("wrong-tok", Some("conn-Y"));
        assert!(result.is_err());

        // Correct token → accepted
        let result = registry.validate_and_consume_for_connection("real-tok", Some("conn-Z"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "share");
    }

    #[test]
    fn test_connection_admission_tracks_token_acceptance_and_revoke() {
        let registry = SessionTokenRegistry::new();
        registry.register("real-tok".to_string(), "share".to_string(), 0);

        assert_eq!(registry.admission("conn-1"), SessionAdmission::Pending);

        registry
            .validate_and_consume_for_connection("real-tok", Some("conn-1"))
            .unwrap();

        assert_eq!(
            registry.admission("conn-1"),
            SessionAdmission::Accepted {
                mechanism: SessionAdmissionMechanism::SessionToken,
                scope: Some(GrantScope::from("share")),
                authoritative_device_id: None,
            }
        );

        assert_eq!(registry.revoke_by_scope("share"), vec!["conn-1"]);
        assert_eq!(registry.admission("conn-1"), SessionAdmission::Pending);
    }

    #[test]
    fn is_session_token_admitted_for_connection_tracks_first_vs_duplicate_presentation() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "share".to_string(), 0);

        assert!(
            !registry.is_session_token_admitted_for_connection("conn-dup"),
            "before first consume, not yet session-token admitted"
        );

        registry
            .validate_and_consume_for_connection("tok", Some("conn-dup"))
            .unwrap();

        assert!(
            registry.is_session_token_admitted_for_connection("conn-dup"),
            "after first consume, duplicate token frames must be detectable for WebRTC gating"
        );

        registry.forget_connection("conn-dup");
        assert!(
            !registry.is_session_token_admitted_for_connection("conn-dup"),
            "forget clears admission so a reconnect can run first-presentation recovery again"
        );
    }

    #[test]
    fn test_native_trusted_verifier_can_accept_authoritative_device() {
        let registry = SessionTokenRegistry::new();
        registry.register("sentinel".to_string(), "share".to_string(), 0);
        registry.set_native_trusted_connection_verifier(Some(Arc::new(|context| {
            if context.remote_node_id.as_deref() == Some("node-123")
                && context.claimed_device_id.as_deref() == Some("device-abc")
            {
                Some("device-abc".to_string())
            } else {
                None
            }
        })));

        let context = NativeTrustedConnectionContext {
            connection_id: "conn-native".to_string(),
            remote_node_id: Some("node-123".to_string()),
            known_device_id: None,
            claimed_device_id: Some("device-abc".to_string()),
        };

        let authoritative = registry.evaluate_trusted_native_connection(&context);
        assert_eq!(authoritative.as_deref(), Some("device-abc"));

        registry.mark_accepted(
            "conn-native",
            SessionAdmissionMechanism::TrustedNativeBinding,
            None,
            authoritative,
        );

        assert_eq!(
            registry.admission("conn-native"),
            SessionAdmission::Accepted {
                mechanism: SessionAdmissionMechanism::TrustedNativeBinding,
                scope: None,
                authoritative_device_id: Some("device-abc".to_string()),
            }
        );
    }

    // -----------------------------------------------------------------------
    // End-to-end scenario tests: native host ↔ web client token gating
    // -----------------------------------------------------------------------

    /// Simulates: native host generates compound ticket, web client extracts
    /// token, host validates token on incoming handshake. Verifies the full
    /// round-trip from ticket generation through validation.
    #[test]
    fn test_native_host_web_client_full_flow() {
        let registry = SessionTokenRegistry::new();

        // Host generates a compound ticket (native side)
        let host_token = generate_token();
        registry.register(host_token.clone(), "share".to_string(), 0);
        let compound = build_compound_ticket("nativeticketbase32", &host_token, "share", 0);

        // Client extracts the token from the compound ticket (web side)
        let (_iroh_ticket, suffix) = split_compound_ticket(&compound);
        let payload = decode_token_payload(suffix.unwrap()).unwrap();

        // Host validates the extracted token for a specific connection
        let result =
            registry.validate_and_consume_for_connection(&payload.token, Some("web-client-conn-1"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "share");
    }

    /// Client without a token is rejected when registry is non-empty.
    #[test]
    fn test_client_without_token_rejected() {
        let registry = SessionTokenRegistry::new();
        registry.register(generate_token(), "share".to_string(), 0);

        // Client arrives without a token
        let result = registry.validate_and_consume_for_connection("", Some("bad-conn"));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("unknown"));
    }

    /// Client with wrong token is rejected.
    #[test]
    fn test_client_with_wrong_token_rejected() {
        let registry = SessionTokenRegistry::new();
        let real_token = generate_token();
        registry.register(real_token, "share".to_string(), 0);

        let result = registry
            .validate_and_consume_for_connection("completely-wrong-token", Some("bad-conn"));
        assert!(result.is_err());
    }

    /// Revoking a scope disconnects all connections that used tokens of that
    /// scope and prevents new connections from using those tokens.
    #[test]
    fn test_revoke_scope_disconnects_and_blocks() {
        let registry = SessionTokenRegistry::new();
        let tok1 = generate_token();
        let tok2 = generate_token();
        registry.register(tok1.clone(), "share".to_string(), 0);
        registry.register(tok2.clone(), "share".to_string(), 0);
        // Keep a sentinel token so registry stays non-empty after revocation
        // (empty registry = backward-compat gate that accepts all).
        registry.register("sentinel".to_string(), "sentinel".to_string(), 0);

        // Two clients connect with valid tokens
        assert!(registry
            .validate_and_consume_for_connection(&tok1, Some("conn-web-1"))
            .is_ok());
        assert!(registry
            .validate_and_consume_for_connection(&tok2, Some("conn-web-2"))
            .is_ok());

        // Host revokes "share" scope
        let mut affected = registry.revoke_by_scope("share");
        affected.sort();
        assert_eq!(affected, vec!["conn-web-1", "conn-web-2"]);

        // New connection attempt with tok1 fails (token revoked)
        let result = registry.validate_and_consume_for_connection(&tok1, Some("conn-web-3"));
        assert!(result.is_err());

        // New connection attempt with tok2 also fails
        let result = registry.validate_and_consume_for_connection(&tok2, Some("conn-web-4"));
        assert!(result.is_err());
    }

    /// Mixed scopes: revoking "share" does not affect "other" connections.
    #[test]
    fn test_revoke_scope_only_affects_matching_scope() {
        let registry = SessionTokenRegistry::new();
        let share_tok = generate_token();
        let other_tok = generate_token();
        registry.register(share_tok.clone(), "share".to_string(), 0);
        registry.register(other_tok.clone(), "other".to_string(), 0);

        assert!(registry
            .validate_and_consume_for_connection(&share_tok, Some("share-conn"))
            .is_ok());
        assert!(registry
            .validate_and_consume_for_connection(&other_tok, Some("other-conn"))
            .is_ok());

        let affected = registry.revoke_by_scope("share");
        assert_eq!(affected, vec!["share-conn"]);

        // "other" token still works for new connections
        let new_other_tok = generate_token();
        registry.register(new_other_tok.clone(), "other".to_string(), 0);
        assert!(registry
            .validate_and_consume_for_connection(&new_other_tok, Some("other-conn-2"))
            .is_ok());
    }

    /// maxConnections enforcement: token with max=1 rejects second use.
    #[test]
    fn test_max_connections_enforced_per_token() {
        let registry = SessionTokenRegistry::new();
        let token = generate_token();
        registry.register(token.clone(), "share".to_string(), 1);

        // First use succeeds
        assert!(registry
            .validate_and_consume_for_connection(&token, Some("conn-1"))
            .is_ok());

        // Second use is rejected (exhausted)
        let result = registry.validate_and_consume_for_connection(&token, Some("conn-2"));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("exhausted"));
    }

    /// Backward-compat: empty registry accepts all connections.
    #[test]
    fn test_empty_registry_accepts_all() {
        let registry = SessionTokenRegistry::new();

        // Any token or no token is accepted
        assert!(registry
            .validate_and_consume_for_connection("any-token", Some("conn-1"))
            .is_ok());
        assert!(registry
            .validate_and_consume_for_connection("", Some("conn-2"))
            .is_ok());
    }

    /// Connection-level caching: once a connection_id is accepted with a token,
    /// repeat validations for that connection should not re-consume the token.
    #[test]
    fn test_validate_for_connection_is_idempotent_after_accept() {
        let registry = SessionTokenRegistry::new();
        let token = generate_token();
        registry.register(token.clone(), "share".to_string(), 1);

        // First validation consumes the single allowed use.
        assert!(registry
            .validate_and_consume_for_connection(&token, Some("conn-1"))
            .is_ok());

        // Subsequent validation for the same connection should be accepted
        // from cached admission, not rejected as exhausted.
        assert!(registry
            .validate_and_consume_for_connection(&token, Some("conn-1"))
            .is_ok());

        // A second connection should still be rejected (max_connections=1).
        let result = registry.validate_and_consume_for_connection(&token, Some("conn-2"));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("exhausted"));
    }

    /// Web host ↔ native client: host creates token in WASM registry,
    /// native client extracts from compound ticket and presents for validation.
    #[test]
    fn test_web_host_native_client_flow() {
        let registry = SessionTokenRegistry::new();

        // Web host generates compound ticket
        let host_token = generate_token();
        registry.register(host_token.clone(), "share".to_string(), 0);
        let compound = build_compound_ticket("wasmticketbase32", &host_token, "share", 0);

        // Native client parses compound ticket
        let (iroh_ticket, suffix) = split_compound_ticket(&compound);
        assert_eq!(iroh_ticket, "wasmticketbase32");
        let payload = decode_token_payload(suffix.unwrap()).unwrap();
        assert_eq!(payload.scope, "share");

        // Native client presents token → host validates
        let result = registry
            .validate_and_consume_for_connection(&payload.token, Some("native-client-conn"));
        assert!(result.is_ok());

        // Keep a sentinel so registry stays non-empty after revocation
        registry.register("sentinel".to_string(), "sentinel".to_string(), 0);

        // After revoke, same token fails
        registry.revoke_by_scope("share");
        let new_attempt = registry
            .validate_and_consume_for_connection(&payload.token, Some("native-client-conn-2"));
        assert!(new_attempt.is_err());
    }

    // -----------------------------------------------------------------------
    // Edge case coverage
    // -----------------------------------------------------------------------

    #[test]
    fn test_grant_scope_serde_roundtrip() {
        let scope = GrantScope::new("share");
        let json = serde_json::to_string(&scope).unwrap();
        assert_eq!(json, r#""share""#); // transparent serialization
        let deserialized: GrantScope = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, "share");
    }

    #[test]
    fn test_grant_scope_equality() {
        let scope = GrantScope::new("share");
        assert_eq!(scope, "share");
        assert_eq!(scope, "share".to_string());
        assert_eq!(scope, GrantScope::from("share"));
        assert_ne!(scope, "other");
    }

    #[test]
    fn test_forget_connection_cleans_up() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "share".to_string(), 0);

        registry
            .validate_and_consume_for_connection("tok", Some("conn-forget"))
            .unwrap();
        assert_eq!(
            registry.admission("conn-forget"),
            SessionAdmission::Accepted {
                mechanism: SessionAdmissionMechanism::SessionToken,
                scope: Some(GrantScope::from("share")),
                authoritative_device_id: None,
            }
        );

        registry.forget_connection("conn-forget");
        assert_eq!(registry.admission("conn-forget"), SessionAdmission::Pending);
    }

    #[test]
    fn test_forget_connection_does_not_clear_payload_nonce_replay_memory() {
        // Single-use ticket: the nonce binding must survive forget_connection so a
        // forgotten connection cannot be used to replay the one-shot token.
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "share".to_string(), 1);
        let suffix = encode_token_payload_for_ticket("endpoint-ticket", "tok", "share", 1);

        registry
            .validate_and_consume_for_connection_with_payload("tok", Some("conn-A"), Some(&suffix))
            .expect("first presentation");
        registry.forget_connection("conn-A");

        assert_eq!(
            registry
                .validate_and_consume_for_connection_with_payload(
                    "tok",
                    Some("conn-B"),
                    Some(&suffix),
                )
                .unwrap_err(),
            "session token payload nonce replayed"
        );
    }

    #[test]
    fn test_mark_rejected_and_readback() {
        let registry = SessionTokenRegistry::new();

        registry.mark_rejected("conn-bad", "invalid token");
        assert_eq!(
            registry.admission("conn-bad"),
            SessionAdmission::Rejected {
                reason: "invalid token".to_string(),
            }
        );
    }

    #[test]
    fn test_trusted_verifier_returns_none_does_not_admit() {
        let registry = SessionTokenRegistry::new();
        registry.register("sentinel".to_string(), "share".to_string(), 0);
        registry.set_native_trusted_connection_verifier(Some(Arc::new(|_context| {
            None // Always reject
        })));

        let context = NativeTrustedConnectionContext {
            connection_id: "conn-untrusted".to_string(),
            remote_node_id: Some("unknown-node".to_string()),
            known_device_id: None,
            claimed_device_id: Some("fake-device".to_string()),
        };

        let result = registry.evaluate_trusted_native_connection(&context);
        assert!(result.is_none());
        // Admission should still be Pending — verifier returning None doesn't mark rejected
        assert_eq!(
            registry.admission("conn-untrusted"),
            SessionAdmission::Pending
        );
    }

    #[test]
    fn test_validate_without_connection_id_does_not_track_admission() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "share".to_string(), 0);

        // Validate without connection_id (simple path)
        let result = registry.validate_and_consume("tok");
        assert!(result.is_ok());

        // No admission should be tracked since no connection_id was given
        // (there's nothing to look up)
    }

    #[test]
    fn test_revoke_by_scope_with_no_matching_connections() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok-a".to_string(), "share".to_string(), 0);
        registry.register("tok-b".to_string(), "other".to_string(), 0);

        // Validate tok-b but revoke "share" — no connections should be affected
        registry
            .validate_and_consume_for_connection("tok-b", Some("conn-other"))
            .unwrap();

        let affected = registry.revoke_by_scope("share");
        assert!(affected.is_empty());

        // conn-other should still be admitted
        assert_eq!(
            registry.admission("conn-other"),
            SessionAdmission::Accepted {
                mechanism: SessionAdmissionMechanism::SessionToken,
                scope: Some(GrantScope::from("other")),
                authoritative_device_id: None,
            }
        );
    }

    #[test]
    fn test_clear_removes_all_admission_state() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "share".to_string(), 0);
        registry
            .validate_and_consume_for_connection("tok", Some("conn-1"))
            .unwrap();
        registry.mark_rejected("conn-2", "bad");

        assert!(matches!(
            registry.admission("conn-1"),
            SessionAdmission::Accepted { .. }
        ));
        assert!(matches!(
            registry.admission("conn-2"),
            SessionAdmission::Rejected { .. }
        ));

        registry.clear();

        assert_eq!(registry.admission("conn-1"), SessionAdmission::Pending);
        assert_eq!(registry.admission("conn-2"), SessionAdmission::Pending);
        assert!(registry.is_empty());
    }

    // -----------------------------------------------------------------------
    // Phase 1 (idempotent admission + flush-before-side-effects) coverage.
    // -----------------------------------------------------------------------

    /// Phase 1: presenting the *same* token on the *same* connection_id twice
    /// must be idempotent — second call returns the cached verdict, never
    /// re-consumes the token, and never errors with "exhausted".
    #[test]
    fn validate_with_cached_response_is_idempotent_for_same_token() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "scoped:abc".to_string(), 1);

        let first = registry
            .validate_with_cached_response("tok", "conn-A")
            .expect("first admission");
        assert_eq!(first, "scoped:abc");

        let second = registry
            .validate_with_cached_response("tok", "conn-A")
            .expect("replay must succeed deterministically");
        assert_eq!(second, "scoped:abc");
        assert_eq!(first, second);
    }

    /// Phase 1: same token presented on *different* connection_ids consumes
    /// the token's max_connections budget per connection (not idempotent
    /// across connections).
    #[test]
    fn validate_with_cached_response_is_not_idempotent_across_connection_ids() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "scoped:abc".to_string(), 1);

        registry
            .validate_with_cached_response("tok", "conn-A")
            .expect("first connection accepted");

        // max_connections=1 → second connection must be rejected.
        let err = registry
            .validate_with_cached_response("tok", "conn-B")
            .expect_err("second connection rejected");
        assert!(err.contains("exhausted"), "expected exhausted, got: {err}");
    }

    /// Phase 1: presenting a *different* token on a connection that is
    /// already admitted must NOT auto-accept from cache. A rotated/forged
    /// token must be re-validated.
    #[test]
    fn validate_with_cached_response_rejects_different_token_on_admitted_connection() {
        let registry = SessionTokenRegistry::new();
        registry.register("real-tok".to_string(), "scoped:abc".to_string(), 0);

        registry
            .validate_with_cached_response("real-tok", "conn-X")
            .expect("first admission");

        let err = registry
            .validate_with_cached_response("forged-tok", "conn-X")
            .expect_err("rotated/forged token must be re-validated");
        assert!(
            err.contains("unknown"),
            "expected 'unknown session token', got: {err}",
        );
    }

    /// Phase 1: token fingerprints are deterministic, hex-encoded, low
    /// cardinality, and *not* equal to the raw token.
    #[test]
    fn token_fingerprint_is_deterministic_and_short() {
        let fp1 = token_fingerprint("hello-world");
        let fp2 = token_fingerprint("hello-world");
        assert_eq!(fp1, fp2);
        assert_eq!(fp1.len(), 16);
        assert_ne!(fp1, "hello-world");
        assert!(fp1.chars().all(|c| c.is_ascii_hexdigit()));
        assert_ne!(fp1, token_fingerprint("hello-worldX"));
    }

    /// Phase 1: in-flight admission counter is correct under interleaved
    /// guard scopes (matches the shape used by the desktop response writer).
    #[test]
    fn in_flight_admission_guard_tracks_concurrent_writers() {
        let registry = SessionTokenRegistry::new();

        assert!(!registry.is_session_token_admission_in_flight("conn-1"));

        let g1 = registry.begin_admission_response("conn-1");
        assert!(registry.is_session_token_admission_in_flight("conn-1"));

        // Nested guard for the same connection (e.g. two concurrent
        // session-token streams on a single transport): both must be alive
        // before the connection is "quiet" again.
        let g2 = registry.begin_admission_response("conn-1");
        assert!(registry.is_session_token_admission_in_flight("conn-1"));

        drop(g1);
        assert!(
            registry.is_session_token_admission_in_flight("conn-1"),
            "still in-flight while second guard is alive",
        );
        drop(g2);
        assert!(!registry.is_session_token_admission_in_flight("conn-1"));
    }

    /// Phase 1: in-flight tracking is per-connection (a writer on conn-1 must
    /// not block lifecycle action on conn-2).
    #[test]
    fn in_flight_admission_guard_is_per_connection() {
        let registry = SessionTokenRegistry::new();

        let _g = registry.begin_admission_response("conn-A");
        assert!(registry.is_session_token_admission_in_flight("conn-A"));
        assert!(!registry.is_session_token_admission_in_flight("conn-B"));
    }

    /// Phase 1: forget_connection clears all per-connection state including
    /// fingerprints + in-flight counters.
    #[test]
    fn forget_connection_clears_phase1_state() {
        let registry = SessionTokenRegistry::new();
        registry.register("tok".to_string(), "scoped:abc".to_string(), 0);

        registry
            .validate_with_cached_response("tok", "conn-A")
            .expect("admit");
        assert!(registry.admission_fingerprint("conn-A").is_some());

        let _g = registry.begin_admission_response("conn-A");
        assert!(registry.is_session_token_admission_in_flight("conn-A"));
        drop(_g);

        registry.forget_connection("conn-A");
        assert_eq!(registry.admission("conn-A"), SessionAdmission::Pending);
        assert!(registry.admission_fingerprint("conn-A").is_none());
        assert!(!registry.is_session_token_admission_in_flight("conn-A"));
    }

    #[test]
    fn test_token_payload_with_grant_scope_cross_language_compat() {
        // Verify that GrantScope serializes transparently in token payloads,
        // matching the flat string format that TypeScript expects.
        let json = r#"{"t":"test-token","s":"share","m":0}"#;
        let encoded = URL_SAFE_NO_PAD.encode(json.as_bytes());
        let payload = decode_token_payload(&encoded).unwrap();
        assert_eq!(payload.scope, GrantScope::from("share"));

        // Re-encode and verify roundtrip
        let re_encoded = encode_token_payload(
            &payload.token,
            payload.scope.clone(),
            payload.max_connections,
        );
        let re_decoded = decode_token_payload(&re_encoded).unwrap();
        assert_eq!(re_decoded.token, "test-token");
        assert_eq!(re_decoded.scope, "share");
    }
}