vouch-core 4.0.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
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
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
//! The verifier's decision, with no I/O: accept or refuse a Vouch Credential,
//! and why, exactly as the Python reference `vouch.verifier` decides it.
//!
//! The host language does every fetch (DID documents, did:webvh logs, status
//! lists) and keeps the replay store. It hands this module what it fetched,
//! the caller's trust settings and the clock; this module gives back the same
//! verdict and the same refusal text as `vouch.verifier.Verifier.verify`.
//!
//! The order of the checks is the reference's, the same on every path:
//!
//! 1. the credential's shape ([`structure_problem`]): contexts, types, issuer,
//!    vouchVersion, intent and its resource, the validity window, and the
//!    credential's own binding fields; then the trusted issuers (when the
//!    caller limits them); then every proof's own fields ([`read_proofs`]);
//! 2. for a delegation chain, before any key is looked up: the size guard
//!    and any depth budget, the trusted roots, and the link fields alone
//!    (each link continues the one before it, the chain starts at a trusted
//!    root, and every grant is bound to the grant before it);
//! 3. the issuer's keys, then the proof (or both proofs of a proof set), with
//!    the post-quantum rule: a single classical proof is refused when the
//!    caller requires post-quantum, supplies an ML-DSA-44 key, or the
//!    issuer's DID document publishes one;
//! 4. the delegation chain's signed grants
//!    ([`crate::delegation::verify_delegation_chain_with`]);
//! 5. the credential's status, then each grant's status;
//! 6. the replay key ([`ReplayIdentity`]): the host marks it in its store.

use std::collections::BTreeMap;

use serde_json::{json, Map, Value};

use crate::data_integrity;
use crate::delegation::ChainOptions;
use crate::did_document;
use crate::error::{CoreError, Result};
use crate::grant_chain;
use crate::hybrid;
use crate::keys;
use crate::multikey;
use crate::pq;
use crate::status_list;
use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};

/// The refusal when the issuer's key cannot be established.
pub const REASON_NO_KEY: &str = "no key to check the signature with";
/// The refusal when a chained credential arrives and no trusted roots are
/// known ("<root DID>" is replaced by the chain's starting point, see
/// [`untrusted_root_reason`]).
pub const REASON_UNTRUSTED_START: &str =
    "the chain's starting point is not trusted: run `vouch trust <root DID>`";
/// The refusal when the chain starts somewhere the trusted roots do not name.
pub const REASON_START_NOT_LISTED: &str = "the chain's starting point is not trusted: run \
     `vouch trust <root DID>` (it is not one of the trusted roots)";
/// The refusal when a chain is larger than the verifier's budget.
pub const REASON_BUDGET: &str = "verifier_budget_exceeded";
/// The refusal when the caller named trusted roots and a credential without
/// a delegation chain comes from an issuer that is not one of them.
pub const REASON_CHAIN_REQUIRED: &str = "delegation_chain_required";
/// The refusal a host gives when its replay store already holds the key.
pub const REASON_REPLAYED: &str = "this credential was already used";
/// Credentials valid this long or less (12 hours) are single use.
pub const DEFAULT_MAX_REPLAY_WINDOW_SECONDS: f64 = 12.0 * 60.0 * 60.0;
/// The clock skew the reference verifier allows by default, in seconds.
pub const DEFAULT_CLOCK_SKEW_SECONDS: i64 = 30;
/// The start of the error a caller gets when it handed over the issuer's
/// Ed25519 key, the credential carries a post-quantum proof, and no ML-DSA-44
/// key is known (the reference raises `MissingMLDSA44KeyError`). Bindings
/// raise their own error type when an error starts with this text.
pub const MISSING_MLDSA44_KEY: &str = "missing_mldsa44_key";

const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
const REQUIRED_TYPES: [&str; 2] = ["VerifiableCredential", "VouchCredential"];
const SUPPORTED_VOUCH_VERSIONS: [&str; 1] = ["1.0"];
const ASSERTION: &str = "assertionMethod";
const ROOT_PLACEHOLDER: &str = "<root DID>";
const VALUE_ERROR: &str = "ValueError";
const WEAK_KEY_ERROR: &str = "WeakKeyError";
const NS_PER_SECOND: i128 = 1_000_000_000;

/// The group order L of edwards25519, little-endian (an Ed25519 signature's S
/// must be below it).
const GROUP_ORDER_LE: [u8; 32] = [
    237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 16,
];

// ---------------------------------------------------------------------------
// Inputs and outputs
// ---------------------------------------------------------------------------

/// A key the caller named for a DID. A key that is present but cannot be
/// used is still the only key for that DID: the reference never falls back
/// to another source for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyEntry {
    /// A strict Ed25519 public key (32 raw bytes).
    Ed25519(Vec<u8>),
    /// The caller named something for the DID that is not a usable key.
    Unusable,
}

/// The trusted starting points for a delegation chain, normalized
/// ([`crate::did_web::normalize_root`]): the DIDs, and the keys a `{did: key}`
/// map gave for some of them (used for those issuers too).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustedRoots {
    pub dids: Vec<String>,
    pub keys: BTreeMap<String, KeyEntry>,
}

/// Everything one verification decision needs. The host fetched every
/// document and status list; nothing here is fetched.
#[derive(Debug, Clone)]
pub struct DecisionInput {
    /// The credential as the host received it (an object; anything else is
    /// refused as "the credential is not a JSON object").
    pub credential: Value,
    /// The verifier's clock, a protocol time.
    pub now: String,
    /// Allowed clock drift, 0 to 120 seconds.
    pub clock_skew_seconds: i64,
    /// The issuer's key handed over by the caller (offline verification).
    pub public_key: Option<KeyEntry>,
    /// The issuer's ML-DSA-44 key handed over by the caller: `Some(None)` is
    /// a key that is not a 1312-byte ML-DSA-44 key. Supplying one requires
    /// the post-quantum proof.
    pub mldsa44_public_key: Option<Option<Vec<u8>>>,
    /// The caller's trusted keys by DID (the reference's `trusted_keys`):
    /// for a DID listed here, this is the only key.
    pub trusted_keys: BTreeMap<String, KeyEntry>,
    /// The answers of the caller's key resolver, by DID (a resolver that
    /// answered nothing is left out). Asked after the trusted keys.
    pub resolved_keys: BTreeMap<String, KeyEntry>,
    /// ML-DSA-44 keys (1312 bytes) by DID, from the caller's ML-DSA-44 key
    /// resolver. Asked first for every signer.
    pub mldsa44_keys: BTreeMap<String, Vec<u8>>,
    /// DID documents the host fetched, by DID: did:web documents, and the
    /// latest verified state of did:webvh logs. A DID whose fetch failed is
    /// left out.
    pub documents: BTreeMap<String, Value>,
    /// The trusted starting points for a delegation chain. None (or an empty
    /// list) means none are known, so a chained credential is refused.
    pub trusted_roots: Option<TrustedRoots>,
    /// Require the post-quantum proof on the credential and every grant.
    pub require_post_quantum: bool,
    /// When given, intent.resource must equal it.
    pub expected_resource: Option<String>,
    /// Check credentialStatus (the reference's default is true).
    pub check_status: bool,
    /// The status list credentials the host fetched, by URL. A URL missing
    /// here is a list that could not be fetched (status_unavailable).
    pub status_lists: Map<String, Value>,
    /// An explicit most links a delegation chain may have.
    pub max_depth: Option<usize>,
    /// Credentials valid this long or less are single use (seconds, > 0).
    pub max_replay_window_seconds: f64,
    /// When given, only these issuers are accepted (a verifier that requires
    /// a trusted issuer).
    pub allowed_issuers: Option<Vec<String>>,
    /// With trusted roots named, refuse a credential without a delegation
    /// chain unless a root issued it ([`REASON_CHAIN_REQUIRED`]), so leaving
    /// the chain off never steps outside a grant. The reference applies it
    /// when the caller (or a verifier object) named the roots, and not for
    /// roots read from `VOUCH_TRUSTED_ROOTS` or the saved list.
    pub chain_required_outside_roots: bool,
}

impl DecisionInput {
    /// A decision request with the reference's defaults: 30 seconds of skew,
    /// status checked, a 12-hour replay window, nothing trusted and nothing
    /// fetched.
    pub fn new(credential: Value, now: impl Into<String>) -> Self {
        Self {
            credential,
            now: now.into(),
            clock_skew_seconds: DEFAULT_CLOCK_SKEW_SECONDS,
            public_key: None,
            mldsa44_public_key: None,
            trusted_keys: BTreeMap::new(),
            resolved_keys: BTreeMap::new(),
            mldsa44_keys: BTreeMap::new(),
            documents: BTreeMap::new(),
            trusted_roots: None,
            require_post_quantum: false,
            expected_resource: None,
            check_status: true,
            status_lists: Map::new(),
            max_depth: None,
            max_replay_window_seconds: DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
            allowed_issuers: None,
            chain_required_outside_roots: false,
        }
    }
}

/// What a host keeps in its replay store for an accepted credential.
#[derive(Debug, Clone, PartialEq)]
pub struct ReplayIdentity {
    /// The replay key ([`crate::credentials::replay_key`]).
    pub key: String,
    /// Seconds since the epoch until which the key is kept: validUntil plus
    /// the clock skew.
    pub expires_at: f64,
    /// False when the credential is valid longer than the replay window: it
    /// is meant to be shown many times, so the host neither refuses nor
    /// remembers it.
    pub single_use: bool,
}

/// The verdict.
#[derive(Debug, Clone, PartialEq)]
pub struct Decision {
    pub valid: bool,
    /// None when valid, else the reference's refusal text.
    pub reason: Option<String>,
    /// The verified passport (only when valid), in the JSON shape
    /// [`passport`] gives.
    pub passport: Option<Value>,
    /// The replay identity (only when valid).
    pub replay: Option<ReplayIdentity>,
}

impl Decision {
    fn refuse(reason: impl Into<String>) -> Self {
        Self {
            valid: false,
            reason: Some(reason.into()),
            passport: None,
            replay: None,
        }
    }
}

// ---------------------------------------------------------------------------
// Small rules
// ---------------------------------------------------------------------------

/// The refusal for a delegation chain whose starting point is not trusted. It
/// names the chain's starting point in the `vouch trust` command when that is
/// a DID made of plain characters (`did:[a-z0-9]+:[A-Za-z0-9._:%-]{1,200}`),
/// otherwise it says "<root DID>".
pub fn untrusted_root_reason(root: Option<&str>, roots_given: bool) -> String {
    let template = if roots_given {
        REASON_START_NOT_LISTED
    } else {
        REASON_UNTRUSTED_START
    };
    match root {
        Some(r) if showable_did(r) => template.replace(ROOT_PLACEHOLDER, r),
        _ => template.to_string(),
    }
}

fn showable_did(s: &str) -> bool {
    let Some(rest) = s.strip_prefix("did:") else {
        return false;
    };
    let Some((method, id)) = rest.split_once(':') else {
        return false;
    };
    !method.is_empty()
        && method
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
        && (1..=200).contains(&id.len())
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"._:%-".contains(&b))
}

/// The issuer DID the reference reads: a string, or the `id` of an issuer
/// object, that starts with "did:" and is longer than "did:".
pub fn issuer_did(credential: &Value) -> Option<&str> {
    let issuer = match credential.get("issuer") {
        Some(Value::Object(o)) => o.get("id"),
        other => other,
    };
    issuer
        .and_then(Value::as_str)
        .filter(|s| s.starts_with("did:") && s.len() > 4)
}

fn has_did_document(did: &str) -> bool {
    did.starts_with("did:web:") || did.starts_with("did:webvh:")
}

/// A protocol time, or None when the value is not one.
fn protocol_time(v: &Value) -> Option<i128> {
    v.as_str().and_then(|s| parse_protocol_time_ns(s).ok())
}

/// The first rule of a Vouch Credential's shape that `cred` breaks, in the
/// reference's words, or None.
pub fn structure_problem(
    credential: &Value,
    now: i128,
    skew: i128,
    expected_resource: Option<&str>,
) -> Option<String> {
    let Some(cred) = credential.as_object() else {
        return Some("the credential is not a JSON object".into());
    };
    let first_context = cred
        .get("@context")
        .and_then(Value::as_array)
        .and_then(|c| c.first());
    if first_context.and_then(Value::as_str) != Some(VC_CONTEXT_V2) {
        return Some("the credential's @context does not start with the VC 2.0 context".into());
    }
    let types_ok = cred.get("type").and_then(Value::as_array).is_some_and(|t| {
        REQUIRED_TYPES
            .iter()
            .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
    });
    if !types_ok {
        return Some(
            "the credential's type must include VerifiableCredential and VouchCredential".into(),
        );
    }
    if issuer_did(credential).is_none() {
        return Some("the credential's issuer is not a DID".into());
    }
    let Some(subject) = cred.get("credentialSubject").and_then(Value::as_object) else {
        return Some("credentialSubject is not an object".into());
    };
    let version_ok = subject
        .get("vouchVersion")
        .and_then(Value::as_str)
        .is_some_and(|v| SUPPORTED_VOUCH_VERSIONS.contains(&v));
    if !version_ok {
        return Some("credentialSubject.vouchVersion is missing or not supported".into());
    }
    let Some(intent) = subject.get("intent").and_then(Value::as_object) else {
        return Some("credentialSubject.intent is not an object".into());
    };
    let resource = match intent.get("resource").and_then(Value::as_str) {
        Some(r) if !r.is_empty() => r,
        _ => return Some("intent.resource is missing or is not a non-empty string".into()),
    };
    if expected_resource.is_some_and(|want| want != resource) {
        return Some("intent.resource is not the expected resource".into());
    }
    let (Some(Value::String(vf)), Some(Value::String(vu))) =
        (cred.get("validFrom"), cred.get("validUntil"))
    else {
        return Some("the credential has no validity window".into());
    };
    let (Ok(from), Ok(until)) = (parse_protocol_time_ns(vf), parse_protocol_time_ns(vu)) else {
        return Some("the credential's validity window is not valid times".into());
    };
    match window_state_ns(now, Some(from), Some(until), skew) {
        WindowState::Inverted => {
            return Some("the credential's validity window ends before it starts".into())
        }
        WindowState::Expired => return Some("the credential expired".into()),
        WindowState::NotYetValid => return Some("the credential is not yet valid".into()),
        WindowState::Ok => {}
    }
    grant_chain::binding_fields_problem(&credential["credentialSubject"]).map(String::from)
}

/// A credential's proofs, sorted by kind.
#[derive(Debug, Clone)]
pub struct Proofs {
    /// "single" or "set".
    pub kind: &'static str,
    pub eddsa: Option<Value>,
    pub mldsa: Option<Value>,
}

impl Proofs {
    fn vm_of(p: Option<&Value>) -> Option<String> {
        p.and_then(|p| p.get("verificationMethod"))
            .and_then(Value::as_str)
            .map(String::from)
    }

    /// The verificationMethod of the Ed25519 proof.
    pub fn ed_vm(&self) -> Option<String> {
        Self::vm_of(self.eddsa.as_ref())
    }

    /// The verificationMethod of the ML-DSA-44 proof of a set.
    pub fn ml_vm(&self) -> Option<String> {
        Self::vm_of(self.mldsa.as_ref())
    }

    /// The proofValue the replay key is made from: the Ed25519 proof's.
    pub fn replay_proof_value(&self) -> String {
        self.eddsa
            .as_ref()
            .and_then(|p| p.get("proofValue"))
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string()
    }
}

fn is_mldsa_suite(s: &str) -> bool {
    s == hybrid::MLDSA44_CRYPTOSUITE_ID || s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
}

fn proof_problem(proof: &Value, issuer: &str, now: i128, skew: i128) -> Option<&'static str> {
    let Some(p) = proof.as_object() else {
        return Some("a proof is not an object");
    };
    if p.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE) {
        return Some("a proof is not a DataIntegrityProof");
    }
    let suite = p.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
    // The earlier composite proof is refused: the post-quantum profile is
    // the proof set of two separate proofs only.
    if !(suite == hybrid::EDDSA_CRYPTOSUITE_ID || is_mldsa_suite(suite)) {
        return Some("a proof uses an unsupported cryptosuite");
    }
    if p.get("proofPurpose").and_then(Value::as_str) != Some(ASSERTION) {
        return Some("a proof's purpose is not assertionMethod");
    }
    let bound = p
        .get("verificationMethod")
        .and_then(Value::as_str)
        .is_some_and(|vm| vm.split('#').next() == Some(issuer));
    if !bound {
        return Some("a proof's verificationMethod does not belong to the issuer");
    }
    if p.get("proofValue")
        .and_then(Value::as_str)
        .is_none_or(str::is_empty)
    {
        return Some("a proof has no proofValue");
    }
    if let Some(created) = p.get("created") {
        if protocol_time(created).is_none() {
            return Some("a proof's created is not a valid time");
        }
    }
    if let Some(expires) = p.get("expires") {
        let Some(e) = protocol_time(expires) else {
            return Some("a proof's expires is not a valid time");
        };
        if window_state_ns(now, None, Some(e), skew) != WindowState::Ok {
            return Some("a proof expired");
        }
    }
    None
}

/// The credential's proofs, sorted by kind, or the first rule a proof breaks
/// (every proof's type, cryptosuite, purpose, verificationMethod, proofValue,
/// created and expires; then the shape: one eddsa-jcs-2022 proof, or a set of exactly one eddsa-jcs-2022 and one ML-DSA-44
/// proof).
pub fn read_proofs(
    cred: &Value,
    issuer: &str,
    now: i128,
    skew: i128,
) -> std::result::Result<Proofs, &'static str> {
    let suite = |p: &Value| {
        p.get("cryptosuite")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string()
    };
    match cred.get("proof") {
        Some(raw @ Value::Object(_)) => {
            if let Some(problem) = proof_problem(raw, issuer, now, skew) {
                return Err(problem);
            }
            match suite(raw).as_str() {
                hybrid::EDDSA_CRYPTOSUITE_ID => Ok(Proofs {
                    kind: "single",
                    eddsa: Some(raw.clone()),
                    mldsa: None,
                }),
                _ => Err("an ML-DSA-44 proof needs its eddsa-jcs-2022 partner in a proof set"),
            }
        }
        Some(Value::Array(items)) => {
            for p in items {
                if let Some(problem) = proof_problem(p, issuer, now, skew) {
                    return Err(problem);
                }
            }
            let mut suites: Vec<String> = items
                .iter()
                .map(|p| {
                    let s = suite(p);
                    if is_mldsa_suite(&s) {
                        "mldsa".to_string()
                    } else {
                        s
                    }
                })
                .collect();
            suites.sort();
            if suites != [hybrid::EDDSA_CRYPTOSUITE_ID, "mldsa"] {
                return Err(
                    "a proof set must be one eddsa-jcs-2022 proof and one mldsa44-jcs-2024 proof",
                );
            }
            Ok(Proofs {
                kind: "set",
                eddsa: items
                    .iter()
                    .find(|p| suite(p) == hybrid::EDDSA_CRYPTOSUITE_ID)
                    .cloned(),
                mldsa: items.iter().find(|p| is_mldsa_suite(&suite(p))).cloned(),
            })
        }
        _ => Err("the credential has no proof"),
    }
}

// ---------------------------------------------------------------------------
// Keys
// ---------------------------------------------------------------------------

/// The keys found for one signer.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SignerKeys {
    pub ed25519: Option<Vec<u8>>,
    pub mldsa44: Option<Vec<u8>>,
    /// The signer's DID document publishes an ML-DSA-44 assertion key, so
    /// the post-quantum proof is required.
    pub publishes_mldsa44: bool,
}

/// A strict Ed25519 key, or None.
fn strict_ed25519(raw: &[u8]) -> Option<Vec<u8>> {
    keys::strict_verifying_key(raw).ok().map(|_| raw.to_vec())
}

/// The key a did:key DID encodes (strict Ed25519), or None.
fn did_key_key(did: &str) -> Option<Vec<u8>> {
    let mk = did.strip_prefix("did:key:")?;
    let decoded = multikey::decode(mk).ok()?;
    (decoded.algorithm == "Ed25519").then_some(decoded.raw_key)
}

/// The keys of every source in the reference's order, merged: the caller's
/// trusted keys, then the trusted roots' keys, then the key resolver's
/// answers. The first source that names a DID is the only one used for it.
fn effective_keys(input: &DecisionInput) -> BTreeMap<String, KeyEntry> {
    let mut merged = input.resolved_keys.clone();
    if let Some(roots) = &input.trusted_roots {
        for (did, key) in &roots.keys {
            merged.insert(did.clone(), key.clone());
        }
    }
    for (did, key) in &input.trusted_keys {
        merged.insert(did.clone(), key.clone());
    }
    merged
}

struct KeySource<'a> {
    keys: BTreeMap<String, KeyEntry>,
    mldsa44: &'a BTreeMap<String, Vec<u8>>,
    documents: &'a BTreeMap<String, Value>,
}

impl KeySource<'_> {
    /// A signer's keys: the ML-DSA-44 resolver first; then the caller's key
    /// for the DID (the only one used for it; for a did:key it must be the
    /// key the DID encodes); then the did:key itself; then the did:web or
    /// did:webvh document's assertionMethod keys the proof names.
    fn keys(&self, did: &str, ed_vm: Option<&str>, ml_vm: Option<&str>) -> SignerKeys {
        let mut found = SignerKeys {
            mldsa44: self.mldsa44.get(did).cloned(),
            ..Default::default()
        };
        let own = if did.starts_with("did:key:") {
            match did_key_key(did) {
                Some(k) => Some(k),
                None => return found, // a did:key that does not decode has no key
            }
        } else {
            None
        };
        if let Some(entry) = self.keys.get(did) {
            found.ed25519 = match entry {
                KeyEntry::Ed25519(k) => match &own {
                    Some(o) if o != k => None,
                    _ => strict_ed25519(k),
                },
                KeyEntry::Unusable => None,
            };
            return found;
        }
        if let Some(k) = own {
            found.ed25519 = Some(k);
            return found;
        }
        if has_did_document(did) {
            let Some(doc) = self.documents.get(did) else {
                return found;
            };
            if doc.get("id").and_then(Value::as_str) != Some(did) {
                return found;
            }
            found.publishes_mldsa44 = did_document::publishes_mldsa44_assertion_key(doc, did);
            if let Some(vm) = ed_vm {
                found.ed25519 = did_document::assertion_key(doc, did, vm, did_document::ED25519)
                    .ok()
                    .and_then(|k| strict_ed25519(&k));
            }
            if let (Some(vm), None) = (ml_vm, &found.mldsa44) {
                found.mldsa44 =
                    did_document::assertion_key(doc, did, vm, did_document::MLDSA44).ok();
            }
        }
        found
    }
}

/// A JWK member decoded the way the reference's JWK reader decodes it: a
/// length that leaves one character over is refused, padding is optional
/// (it is added when missing), and only trailing padding is read.
fn jwk_base64url_decode(text: &str) -> Option<Vec<u8>> {
    use base64::engine::{
        general_purpose::GeneralPurpose, DecodePaddingMode, GeneralPurposeConfig,
    };
    use base64::{alphabet::URL_SAFE, Engine};
    if text.len() % 4 == 1 {
        return None;
    }
    let body = text.trim_end_matches('=');
    if body.contains('=') {
        return None;
    }
    let engine = GeneralPurpose::new(
        &URL_SAFE,
        GeneralPurposeConfig::new()
            .with_decode_allow_trailing_bits(true)
            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
    );
    engine.decode(body).ok()
}

/// A key the caller wrote as the reference reads it: a Multikey string
/// ("z..."), or a JWK (an object, or its JSON text) of an Ed25519 public key.
/// Every form is checked with the strict Ed25519 rules. Anything else is
/// [`KeyEntry::Unusable`].
pub fn key_entry_from_json(v: &Value) -> KeyEntry {
    let jwk = match v {
        Value::String(s) if s.starts_with('z') => {
            return match multikey::decode(s) {
                Ok(d) if d.algorithm == "Ed25519" => KeyEntry::Ed25519(d.raw_key),
                _ => KeyEntry::Unusable,
            };
        }
        Value::String(s) => match serde_json::from_str::<Value>(s) {
            Ok(Value::Object(o)) => o,
            _ => return KeyEntry::Unusable,
        },
        Value::Object(o) => o.clone(),
        _ => return KeyEntry::Unusable,
    };
    if jwk.get("kty").and_then(Value::as_str) != Some("OKP")
        || jwk.get("crv").and_then(Value::as_str) != Some("Ed25519")
    {
        return KeyEntry::Unusable;
    }
    let Some(x) = jwk.get("x").and_then(Value::as_str) else {
        return KeyEntry::Unusable;
    };
    match jwk_base64url_decode(x).and_then(|raw| strict_ed25519(&raw)) {
        Some(k) => KeyEntry::Ed25519(k),
        None => KeyEntry::Unusable,
    }
}

/// An ML-DSA-44 key as the reference reads one in text: a Multikey string of
/// the ML-DSA-44 codec. None for anything else.
pub fn mldsa44_key_from_json(v: &Value) -> Option<Vec<u8>> {
    let s = v.as_str().filter(|s| s.starts_with('z'))?;
    let d = multikey::decode(s).ok()?;
    (d.algorithm == "ML-DSA-44").then_some(d.raw_key)
}

// ---------------------------------------------------------------------------
// Signatures, with the reference's malformed-input answers
// ---------------------------------------------------------------------------

/// The reference's strict Ed25519 signature rule: R is a canonical encoding
/// of a curve point that is not of small order, and S is below L.
fn strict_signature(sig: &[u8]) -> bool {
    if sig.len() != keys::ED25519_SIGNATURE_LEN {
        return false;
    }
    let mut r = [0u8; 32];
    r.copy_from_slice(&sig[..32]);
    if !keys::is_canonical_point_encoding(&r) {
        return false;
    }
    match ed25519_dalek::VerifyingKey::from_bytes(&r) {
        Ok(point) if !point.is_weak() => {}
        _ => return false,
    }
    // S < L, comparing little-endian from the most significant byte.
    for i in (0..32).rev() {
        let s = sig[32 + i];
        if s != GROUP_ORDER_LE[i] {
            return s < GROUP_ORDER_LE[i];
        }
    }
    false
}

/// `Err(exception name)` where the reference raises on a malformed proof
/// (the verifier then answers "the credential is malformed (<name>)").
type Checked = std::result::Result<bool, &'static str>;

fn context_matches(document: &Value, proof: &Value) -> bool {
    proof
        .as_object()
        .is_none_or(|p| data_integrity::proof_context_matches(document, p))
}

fn without_proof(cred: &Value) -> Value {
    let mut base = cred.clone();
    if let Some(o) = base.as_object_mut() {
        o.remove("proof");
    }
    base
}

/// One eddsa-jcs-2022 proof, as `vouch.data_integrity.verify_proof` checks it.
fn verify_ed25519_proof(cred: &Value, key: &[u8]) -> Checked {
    let pv = cred
        .get("proof")
        .and_then(|p| p.get("proofValue"))
        .and_then(Value::as_str)
        .unwrap_or("");
    let Some(body) = pv.strip_prefix('z') else {
        return Err(VALUE_ERROR);
    };
    let sig = match multikey::decode_base58_bounded(body) {
        Ok(s) if s.len() == keys::ED25519_SIGNATURE_LEN => s,
        _ => return Err(VALUE_ERROR),
    };
    if !strict_signature(&sig) {
        return Err(WEAK_KEY_ERROR);
    }
    if !context_matches(&without_proof(cred), &cred["proof"]) {
        return Err(VALUE_ERROR);
    }
    data_integrity::verify_proof(cred, key).map_err(|_| VALUE_ERROR)
}

/// A proof set, as `vouch.data_integrity_hybrid.verify_dual` checks it: the
/// members in order, each recognized one verified, both kinds present.
fn verify_proof_set(cred: &Value, ed: &[u8], ml: &[u8]) -> Checked {
    let Some(items) = cred.get("proof").and_then(Value::as_array) else {
        return Err(VALUE_ERROR);
    };
    let base = without_proof(cred);
    let (mut ed_ok, mut ml_ok) = (false, false);
    for p in items {
        let Some(obj) = p.as_object() else { continue };
        let suite = obj.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
        if suite == hybrid::EDDSA_CRYPTOSUITE_ID {
            let mut candidate = base.clone();
            candidate["proof"] = p.clone();
            if !verify_ed25519_proof(&candidate, ed)? {
                return Ok(false);
            }
            ed_ok = true;
        } else if is_mldsa_suite(suite) {
            if obj.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE)
                || ml.len() != pq::MLDSA44_PUBLIC_LEN
            {
                return Err(VALUE_ERROR);
            }
            let pv = obj.get("proofValue").and_then(Value::as_str).unwrap_or("");
            let sig = hybrid::decode_mldsa44_proof_value(pv).map_err(|_| VALUE_ERROR)?;
            if !data_integrity::proof_context_matches(&base, obj) {
                return Err(VALUE_ERROR);
            }
            let mut unsigned = obj.clone();
            unsigned.remove("proofValue");
            let input = data_integrity::hash_data(&base, &unsigned).map_err(|_| VALUE_ERROR)?;
            let mut ok = pq::verify(ml, &input, &sig).map_err(|_| VALUE_ERROR)?;
            if !ok {
                let legacy = data_integrity::legacy_proof_digest(&base, &unsigned)
                    .map_err(|_| VALUE_ERROR)?;
                ok = pq::verify(ml, &legacy, &sig).map_err(|_| VALUE_ERROR)?;
            }
            if !ok {
                return Ok(false);
            }
            ml_ok = true;
        }
    }
    Ok(ed_ok && ml_ok)
}

enum ProofCheck {
    Ok,
    Refused(String),
    MissingMldsa44Key,
}

/// The credential's proof (or both proofs) with the signer's keys.
fn check_proofs(
    cred: &Value,
    proofs: &Proofs,
    keys: &SignerKeys,
    post_quantum: bool,
    explicit: bool,
) -> ProofCheck {
    let ed = keys.ed25519.as_deref().unwrap_or_default();
    let verdict = if proofs.kind == "single" {
        if post_quantum {
            return ProofCheck::Refused("a post-quantum proof is required".into());
        }
        verify_ed25519_proof(cred, ed)
    } else {
        let Some(ml) = keys.mldsa44.as_deref() else {
            if explicit {
                return ProofCheck::MissingMldsa44Key;
            }
            return ProofCheck::Refused(
                "no ML-DSA-44 key to check the post-quantum proof with".into(),
            );
        };
        verify_proof_set(cred, ed, ml)
    };
    match verdict {
        Ok(true) => ProofCheck::Ok,
        Ok(false) => ProofCheck::Refused("the signature does not verify".into()),
        Err(name) => ProofCheck::Refused(format!("the credential is malformed ({name})")),
    }
}

// ---------------------------------------------------------------------------
// Status
// ---------------------------------------------------------------------------

/// The verificationMethods a status list's proof names: (its eddsa-jcs-2022
/// proof's, its ML-DSA-44 proof's).
fn list_proof_methods(list: &Value) -> (Option<String>, Option<String>) {
    let vm = |p: &Value| {
        p.get("verificationMethod")
            .and_then(Value::as_str)
            .map(String::from)
    };
    let suite = |p: &Value| {
        p.get("cryptosuite")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string()
    };
    match list.get("proof") {
        Some(p @ Value::Object(_)) => (vm(p), None),
        Some(Value::Array(items)) => (
            items
                .iter()
                .find(|p| suite(p) == hybrid::EDDSA_CRYPTOSUITE_ID)
                .and_then(vm),
            items
                .iter()
                .find(|p| suite(p) == hybrid::MLDSA44_CRYPTOSUITE_ID)
                .and_then(vm),
        ),
        _ => (None, None),
    }
}

/// The keys for one status list's proofs, as the reference's resolver gives
/// them: for each proof, the verificationMethod it names is resolved on its
/// own (the issuer's key already found for the same method, else the
/// issuer's key from the same sources), and the answer must be a key of the
/// proof's kind.
fn list_keys(
    list: Option<&Value>,
    issuer: &str,
    known: Option<(&Proofs, &SignerKeys)>,
    source: &KeySource,
) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
    let Some(list) = list else {
        return (None, None);
    };
    let resolve = |vm: &str| -> Option<Vec<u8>> {
        if let Some((proofs, keys)) = known {
            if Some(vm) == proofs.ed_vm().as_deref() && keys.ed25519.is_some() {
                return keys.ed25519.clone();
            }
            if Some(vm) == proofs.ml_vm().as_deref() && keys.mldsa44.is_some() {
                return keys.mldsa44.clone();
            }
        }
        let found = source.keys(issuer, Some(vm), Some(vm));
        found.ed25519.or(found.mldsa44)
    };
    let (ed_vm, ml_vm) = list_proof_methods(list);
    // Only a method of the issuer's own DID resolves.
    let own = |vm: Option<String>| vm.filter(|v| v.split('#').next() == Some(issuer));
    let ed = own(ed_vm)
        .and_then(|vm| resolve(&vm))
        .and_then(|k| strict_ed25519(&k));
    let ml = own(ml_vm)
        .and_then(|vm| resolve(&vm))
        .filter(|k| k.len() == pq::MLDSA44_PUBLIC_LEN);
    (ed, ml)
}

/// The status reason for one credential (the verifier's own credential, or
/// a grant), or None when its status is good. `known` carries the keys and
/// proofs already found for the verifier's own credential.
///
/// The entries are checked in order, as the reference checks them, and each
/// list is checked with the keys its own proofs name (two lists may be
/// signed with different keys of the issuer).
fn status_reason(
    checked: &Value,
    known: Option<(&Proofs, &SignerKeys)>,
    source: &KeySource,
    input: &DecisionInput,
) -> Result<Option<String>> {
    let Some(raw) = checked.get("credentialStatus") else {
        return Ok(None);
    };
    let unavailable = || Ok(Some(status_list::STATUS_UNAVAILABLE.to_string()));
    let entries: Vec<&Value> = match raw {
        Value::Object(_) => vec![raw],
        Value::Array(items) => items.iter().collect(),
        _ => Vec::new(),
    };
    if entries.is_empty() || entries.len() > status_list::MAX_STATUS_ENTRIES {
        return unavailable();
    }
    let issuer = issuer_did(checked).unwrap_or_default().to_string();
    for entry in entries {
        let list = entry
            .get("statusListCredential")
            .and_then(Value::as_str)
            .and_then(|url| input.status_lists.get(url));
        let (ed_key, ml_key) = list_keys(list, &issuer, known, source);
        let mut one = checked.clone();
        one["credentialStatus"] = entry.clone();
        let result = status_list::check_credential_status(
            &one,
            &input.status_lists,
            ed_key.as_deref(),
            ml_key.as_deref(),
            &input.now,
            input.clock_skew_seconds,
        )?;
        if !result.ok {
            return Ok(Some(result.reason.to_string()));
        }
    }
    Ok(None)
}

// ---------------------------------------------------------------------------
// Replay
// ---------------------------------------------------------------------------

fn check_replay_window(seconds: f64) -> Result<f64> {
    if !seconds.is_finite() || seconds <= 0.0 {
        return Err(CoreError::Json(
            "max_replay_window must be a positive, finite number of seconds".into(),
        ));
    }
    Ok(seconds)
}

fn window_seconds(cred: &Value) -> Result<f64> {
    let t = |k: &str| {
        cred.get(k)
            .and_then(Value::as_str)
            .ok_or_else(|| CoreError::Json(format!("credential missing {k}")))
            .and_then(parse_protocol_time_ns)
    };
    Ok((t("validUntil")? - t("validFrom")?) as f64 / NS_PER_SECOND as f64)
}

/// True when a credential's validity window is longer than the replay
/// window: it is meant to be shown many times, so it is not tracked.
pub fn replay_window_too_long(credential: &Value, max_replay_window_seconds: f64) -> Result<bool> {
    Ok(window_seconds(credential)? > check_replay_window(max_replay_window_seconds)?)
}

fn identity_from(
    cred: &Value,
    proofs: &Proofs,
    skew_seconds: i64,
    max_window: f64,
) -> Result<ReplayIdentity> {
    let issuer = issuer_did(cred).unwrap_or_default();
    let key = crate::credentials::replay_key(issuer, &proofs.replay_proof_value())?;
    let until = cred
        .get("validUntil")
        .and_then(Value::as_str)
        .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
    // As the reference computes it: validUntil read to the microsecond, as
    // seconds (micros / 10^6, one correctly rounded division), plus the skew.
    let until_micros = parse_protocol_time_ns(until)?.div_euclid(1000);
    Ok(ReplayIdentity {
        key,
        expires_at: until_micros as f64 / 1e6 + skew_seconds as f64,
        single_use: !replay_window_too_long(cred, max_window)?,
    })
}

/// `(replay key, keep-until)` for a credential that has already verified
/// (the reference's `vouch.verifier.replay_identity`), with whether it is
/// single use under `max_replay_window_seconds`.
///
/// Errors: a skew outside 0..120, a malformed `now` or validity window, a
/// replay window that is not a positive number, or proofs of a shape the
/// verifier refuses (the error is that refusal).
pub fn replay_identity(
    credential: &Value,
    now_iso: &str,
    clock_skew_seconds: i64,
    max_replay_window_seconds: f64,
) -> Result<ReplayIdentity> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    let now = parse_protocol_time_ns(now_iso)?.div_euclid(1000) * 1000;
    check_replay_window(max_replay_window_seconds)?;
    let issuer = issuer_did(credential).unwrap_or_default();
    let proofs =
        read_proofs(credential, issuer, now, skew).map_err(|p| CoreError::Json(p.into()))?;
    identity_from(
        credential,
        &proofs,
        clock_skew_seconds,
        max_replay_window_seconds,
    )
}

// ---------------------------------------------------------------------------
// The passport
// ---------------------------------------------------------------------------

/// The verified passport: who signed what, for how long, and the grants of
/// its delegation chain, each read from the signed grant itself.
pub fn passport(cred: &Value, grants: &[&Value]) -> Value {
    let chain: Vec<Value> = grants
        .iter()
        .map(|g| {
            let intent = g["credentialSubject"]["intent"].clone();
            let bound: String = crate::delegation::parent_proof_binding_value(g)
                .chars()
                .take(64)
                .collect();
            json!({
                "issuer": issuer_did(g).unwrap_or_default(),
                "subject": intent.get("delegatee").cloned().unwrap_or(json!("")),
                "intent": intent,
                "validFrom": g.get("validFrom").cloned().unwrap_or(Value::Null),
                "validUntil": g.get("validUntil").cloned().unwrap_or(Value::Null),
                "parentProofValue": bound,
            })
        })
        .collect();
    let subject = &cred["credentialSubject"];
    let rep = subject
        .get("reputationScore")
        .and_then(|v| {
            if v.is_i64() || v.is_u64() {
                v.as_i64()
            } else {
                None
            }
        })
        .filter(|r| (0..=100).contains(r));
    let text = |v: Option<&Value>| v.and_then(Value::as_str).unwrap_or_default().to_string();
    json!({
        "sub": text(subject.get("id")),
        "iss": issuer_did(cred).unwrap_or_default(),
        "validFrom": cred["validFrom"],
        "validUntil": cred["validUntil"],
        "credentialId": text(cred.get("id")),
        "intent": subject["intent"],
        "reputationScore": rep,
        "delegationChain": chain,
        "parentGrantDigest": subject.get(grant_chain::PARENT_GRANT_DIGEST).filter(|d| d.is_string()),
    })
}

// ---------------------------------------------------------------------------
// The decision
// ---------------------------------------------------------------------------

fn chain_root(chain: &[Value]) -> Option<&str> {
    chain.first()?.get("issuer")?.as_str()
}

/// What the link fields alone say about a chain, before any key or document
/// is looked up (the reference's `_chain_prefilter`).
fn chain_prefilter(cred: &Value, chain: &[Value], root_dids: &[String]) -> Option<&'static str> {
    for link in chain {
        let ok = link.get("issuer").is_some_and(Value::is_string)
            && link.get("subject").is_some_and(Value::is_string);
        if !ok {
            return Some(grant_chain::REASON_MALFORMED);
        }
    }
    for i in 1..chain.len() {
        if chain[i - 1]["subject"] != chain[i]["issuer"] {
            return Some("delegation_subject_issuer_mismatch");
        }
    }
    if chain[chain.len() - 1]["subject"].as_str() != issuer_did(cred) {
        return Some("delegation_subject_issuer_mismatch");
    }
    let root = chain[0]["issuer"].as_str().unwrap_or_default();
    if !root_dids.iter().any(|d| d == root) {
        return Some("untrusted_principal");
    }
    if chain
        .iter()
        .all(|l| matches!(l.get("parentCredential"), Some(Value::Object(_))))
    {
        return grant_chain::chain_binding_problem(chain);
    }
    None
}

/// The reference reads the verifier's clock as a Python `datetime`, which
/// holds microseconds: digits past the sixth are dropped (toward the past).
/// The validity bounds are still compared at full precision.
fn at_microseconds(input: &DecisionInput) -> Result<DecisionInput> {
    let ns = parse_protocol_time_ns(&input.now)?;
    let micros = ns.div_euclid(1000) * 1000;
    let mut out = input.clone();
    out.now = format_time_micros(micros)?;
    Ok(out)
}

/// A protocol time with exactly six fraction digits.
pub(crate) fn format_time_micros(ns: i128) -> Result<String> {
    let whole = crate::issuance::format_protocol_time(ns)?;
    let micros = ns.rem_euclid(NS_PER_SECOND) / 1000;
    Ok(format!("{}.{micros:06}Z", whole.trim_end_matches('Z')))
}

type Precheck<'a> = (Proofs, Option<&'a Vec<Value>>, Vec<String>);

/// The checks that need nothing fetched, in the reference's order: the
/// shape, the trusted issuers, every proof's own fields, and for a
/// delegation chain the size guard and depth budget, the trusted roots and
/// the link fields. `Ok(Err(reason))` is a refusal.
fn precheck(input: &DecisionInput) -> Result<std::result::Result<Precheck<'_>, String>> {
    let skew = check_clock_skew(input.clock_skew_seconds)?;
    let now = parse_protocol_time_ns(&input.now)?;
    if !input.credential.is_object() {
        return Ok(Err("the credential is not a JSON object".into()));
    }
    check_replay_window(input.max_replay_window_seconds)?;
    let cred = &input.credential;
    let root_dids: Vec<String> = input
        .trusted_roots
        .as_ref()
        .map(|r| r.dids.clone())
        .unwrap_or_default();
    if let Some(problem) = structure_problem(cred, now, skew, input.expected_resource.as_deref()) {
        return Ok(Err(problem));
    }
    let issuer = issuer_did(cred).unwrap_or_default().to_string();
    if let Some(allowed) = &input.allowed_issuers {
        if !allowed.contains(&issuer) {
            return Ok(Err("the issuer is not one of the trusted keys".into()));
        }
    }
    let proofs = match read_proofs(cred, &issuer, now, skew) {
        Ok(p) => p,
        Err(problem) => return Ok(Err(problem.into())),
    };
    let chain = cred["credentialSubject"]
        .get("delegationChain")
        .and_then(Value::as_array)
        .filter(|c| !c.is_empty());
    if chain.is_none()
        && input.chain_required_outside_roots
        && !root_dids.is_empty()
        && !root_dids.contains(&issuer)
    {
        return Ok(Err(REASON_CHAIN_REQUIRED.into()));
    }
    if let Some(chain) = chain {
        let as_value = Value::Array(chain.clone());
        match crate::attenuation::chain_budget_exceeded(&as_value, input.max_depth) {
            Ok(None) => {}
            Ok(Some(_)) => return Ok(Err(REASON_BUDGET.into())),
            Err(_) => return Ok(Err(grant_chain::REASON_MALFORMED.into())),
        }
        if root_dids.is_empty() {
            return Ok(Err(untrusted_root_reason(chain_root(chain), false)));
        }
        if let Some(early) = chain_prefilter(cred, chain, &root_dids) {
            if early == "untrusted_principal" {
                return Ok(Err(untrusted_root_reason(chain_root(chain), true)));
            }
            return Ok(Err(early.into()));
        }
    }
    Ok(Ok((proofs, chain, root_dids)))
}

/// Decide whether to accept a credential, as `vouch.verifier.Verifier.verify`
/// decides it, with everything the host fetched in `input`.
///
/// Errors (a caller mistake, never a verdict): a skew outside 0..120, a
/// malformed `now`, a replay window that is not a positive number, and
/// [`MISSING_MLDSA44_KEY`] when the caller handed over the issuer's Ed25519
/// key, the credential carries a post-quantum proof, and no ML-DSA-44 key is
/// known.
pub fn decide(input: &DecisionInput) -> Result<Decision> {
    let input = &at_microseconds(input)?;
    let (proofs, chain, root_dids) = match precheck(input)? {
        Ok(pre) => pre,
        Err(reason) => return Ok(Decision::refuse(reason)),
    };
    let cred = &input.credential;
    let issuer = issuer_did(cred).unwrap_or_default().to_string();

    let source = KeySource {
        keys: effective_keys(input),
        mldsa44: &input.mldsa44_keys,
        documents: &input.documents,
    };

    // The delegation chain's signed grants, from the trusted root down,
    // before the credential issuer's own key is looked up (as the reference
    // verifier does).
    let mut grants: Vec<&Value> = Vec::new();
    if let Some(chain) = chain {
        let grant_keys: BTreeMap<String, Vec<u8>> = source
            .keys
            .iter()
            .map(|(did, entry)| {
                let raw = match entry {
                    KeyEntry::Ed25519(k) => k.clone(),
                    // Present but unusable: the only key for the DID, and no key.
                    KeyEntry::Unusable => Vec::new(),
                };
                (did.clone(), raw)
            })
            .collect();
        let documents: BTreeMap<String, Value> = input
            .documents
            .iter()
            .filter(|(did, _)| has_did_document(did))
            .map(|(d, v)| (d.clone(), v.clone()))
            .collect();
        let opts = ChainOptions {
            trusted_roots: Some(&root_dids),
            grant_keys: Some(&grant_keys),
            mldsa_keys: Some(&input.mldsa44_keys),
            grant_documents: Some(&documents),
            require_pq: input.require_post_quantum,
            max_depth: input.max_depth,
            ..Default::default()
        };
        if let Some(reason) = crate::delegation::verify_delegation_chain_with(
            cred,
            &input.now,
            input.clock_skew_seconds,
            &opts,
        ) {
            if reason == "untrusted_principal" {
                return Ok(Decision::refuse(untrusted_root_reason(
                    chain_root(chain),
                    true,
                )));
            }
            return Ok(Decision::refuse(reason));
        }
        grants = chain.iter().map(|l| &l["parentCredential"]).collect();
    }

    // The issuer's keys.
    let explicit = input.public_key.is_some();
    let mut keys = match &input.public_key {
        Some(KeyEntry::Unusable) => {
            return Ok(Decision::refuse(
                "the public key given is not a usable Ed25519 key",
            ))
        }
        Some(KeyEntry::Ed25519(k)) => {
            let Some(pinned) = strict_ed25519(k) else {
                return Ok(Decision::refuse(
                    "the public key given is not a usable Ed25519 key",
                ));
            };
            if issuer.starts_with("did:key:") && did_key_key(&issuer).as_ref() != Some(&pinned) {
                return Ok(Decision::refuse(
                    "the public key given is not the did:key issuer's key",
                ));
            }
            SignerKeys {
                ed25519: Some(pinned),
                ..Default::default()
            }
        }
        None => {
            let ml_vm = if proofs.kind != "single" {
                proofs.ml_vm()
            } else {
                None
            };
            let found = source.keys(&issuer, proofs.ed_vm().as_deref(), ml_vm.as_deref());
            if found.ed25519.is_none() {
                return Ok(Decision::refuse(REASON_NO_KEY));
            }
            found
        }
    };
    if let Some(given) = &input.mldsa44_public_key {
        match given {
            Some(k) if k.len() == pq::MLDSA44_PUBLIC_LEN => keys.mldsa44 = Some(k.clone()),
            _ => {
                return Ok(Decision::refuse(
                    "the ML-DSA-44 public key given is not a 1312-byte key",
                ))
            }
        }
    }
    let post_quantum =
        input.require_post_quantum || input.mldsa44_public_key.is_some() || keys.publishes_mldsa44;
    match check_proofs(cred, &proofs, &keys, post_quantum, explicit) {
        ProofCheck::Ok => {}
        ProofCheck::Refused(reason) => return Ok(Decision::refuse(reason)),
        ProofCheck::MissingMldsa44Key => {
            return Err(CoreError::Json(format!(
                "{MISSING_MLDSA44_KEY}: this credential carries an ML-DSA-44 post-quantum \
                 proof; pass the ML-DSA-44 public key or publish it in the issuer's DID \
                 document. A did:key identifier encodes only the Ed25519 key."
            )))
        }
    }

    // The credential's own status, then every grant's, each against a list
    // signed by that credential's issuer.
    if input.check_status {
        if let Some(reason) = status_reason(cred, Some((&proofs, &keys)), &source, input)? {
            return Ok(Decision::refuse(reason));
        }
        for grant in &grants {
            if let Some(reason) = status_reason(grant, None, &source, input)? {
                return Ok(Decision::refuse(format!("delegation_{reason}")));
            }
        }
    }

    Ok(Decision {
        valid: true,
        reason: None,
        passport: Some(passport(cred, &grants)),
        replay: Some(identity_from(
            cred,
            &proofs,
            input.clock_skew_seconds,
            input.max_replay_window_seconds,
        )?),
    })
}

/// The most DIDs a fetch plan names (the issuer and the chain's grant
/// issuers whose keys come from a DID document or log).
pub const MAX_FETCH_DIDS: usize = 32;
/// The most status list URLs a fetch plan names (the credential's and its
/// verified grants').
pub const MAX_FETCH_STATUS_LISTS: usize = 32;

/// Which fetches a plan is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FetchPhase {
    /// Before anything is fetched: the DID documents and did:webvh logs the
    /// keys come from.
    Documents,
    /// After the documents are in: the status lists, named only once every
    /// signature has verified.
    StatusLists,
}

/// What a host fetches before [`decide`], and whether it needs to.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FetchPlan {
    /// The verdict, when the checks that need nothing fetched already refuse
    /// the credential (or, for [`FetchPhase::StatusLists`], when the
    /// signatures or the chain refuse it). The host fetches nothing and
    /// gives this refusal.
    pub refusal: Option<String>,
    /// DIDs whose DID document (did:web) or log (did:webvh) to fetch.
    pub dids: Vec<String>,
    /// Status list URLs to fetch.
    pub status_lists: Vec<String>,
    /// True when more were needed than the plan names (see
    /// [`MAX_FETCH_DIDS`], [`MAX_FETCH_STATUS_LISTS`]); what is left out is
    /// simply not there, as a failed fetch.
    pub truncated: bool,
}

fn push_unique(
    list: &mut Vec<String>,
    seen: &mut std::collections::BTreeSet<String>,
    item: &str,
    cap: usize,
    truncated: &mut bool,
) {
    if item.is_empty() || seen.contains(item) {
        return;
    }
    if list.len() >= cap {
        *truncated = true;
        return;
    }
    seen.insert(item.to_string());
    list.push(item.to_string());
}

fn status_urls(c: &Value) -> Vec<&str> {
    let entries: Vec<&Value> = match c.get("credentialStatus") {
        Some(e @ Value::Object(_)) => vec![e],
        Some(Value::Array(a)) => a.iter().take(status_list::MAX_STATUS_ENTRIES).collect(),
        _ => Vec::new(),
    };
    entries
        .iter()
        .filter_map(|e| e.get("statusListCredential").and_then(Value::as_str))
        .collect()
}

/// What a host has to fetch for [`decide`], in two phases, from the same
/// input it will decide with (the trust settings included).
///
/// [`FetchPhase::Documents`] first runs every check that needs nothing
/// fetched (the shape, the trusted issuers, the proofs' own fields, and for a
/// delegation chain the 1 MiB size guard, the depth budget, the trusted roots
/// and the link fields). When they refuse, the plan is that refusal and
/// nothing to fetch. Otherwise it names the did:web and did:webvh DIDs whose
/// keys are not already known: the issuer (unless its key was handed over)
/// and each grant issuer of the chain.
///
/// [`FetchPhase::StatusLists`] runs [`decide`] with the documents the host
/// put in `input` and the status check off. When the credential is refused
/// (a signature, a key, or the chain), the plan is that refusal. Otherwise it
/// names the status lists of the credential and of its verified grants.
///
/// Every list is deduplicated and capped. The host stays in charge of its
/// own fetch budget, as the reference is: one time budget for every fetch of
/// a verification (the reference's default is 20 seconds, at most 10 per
/// fetch), SSRF rules for every URL, and a size cap on every response. A
/// fetch that fails or runs out of time is left out of the input, which the
/// decision reads as "no key" or "status_unavailable".
pub fn fetch_plan(input: &DecisionInput, phase: FetchPhase) -> Result<FetchPlan> {
    let input = &at_microseconds(input)?;
    let mut plan = FetchPlan::default();
    match phase {
        FetchPhase::Documents => {
            let (_, chain, _) = match precheck(input)? {
                Ok(pre) => pre,
                Err(reason) => {
                    plan.refusal = Some(reason);
                    return Ok(plan);
                }
            };
            let known = effective_keys(input);
            let mut seen = std::collections::BTreeSet::new();
            let mut wanted: Vec<&str> = Vec::new();
            if input.public_key.is_none() {
                wanted.extend(issuer_did(&input.credential));
            }
            for link in chain.into_iter().flatten() {
                wanted.extend(link.get("issuer").and_then(Value::as_str));
            }
            for did in wanted {
                if has_did_document(did) && !known.contains_key(did) {
                    push_unique(
                        &mut plan.dids,
                        &mut seen,
                        did,
                        MAX_FETCH_DIDS,
                        &mut plan.truncated,
                    );
                }
            }
        }
        FetchPhase::StatusLists => {
            let mut without_status = input.clone();
            without_status.check_status = false;
            // A caller error (a post-quantum proof with no ML-DSA-44 key
            // handed over) is the same error decide gives.
            let decision = decide(&without_status)?;
            if !decision.valid {
                plan.refusal = decision.reason;
                return Ok(plan);
            }
            if !input.check_status {
                return Ok(plan);
            }
            let mut seen = std::collections::BTreeSet::new();
            let cred = &input.credential;
            let mut urls = status_urls(cred);
            if let Some(chain) = cred["credentialSubject"]
                .get("delegationChain")
                .and_then(Value::as_array)
            {
                for link in chain {
                    urls.extend(status_urls(&link["parentCredential"]));
                }
            }
            for url in urls {
                push_unique(
                    &mut plan.status_lists,
                    &mut seen,
                    url,
                    MAX_FETCH_STATUS_LISTS,
                    &mut plan.truncated,
                );
            }
        }
    }
    Ok(plan)
}

// ---------------------------------------------------------------------------
// JSON in, JSON out (for the bindings)
// ---------------------------------------------------------------------------

const REQUEST_MEMBERS: [&str; 23] = [
    "credential",
    "now",
    "clockSkewSeconds",
    "publicKey",
    "mldsa44PublicKey",
    "trustedKeys",
    "resolvedKeys",
    "mldsa44Keys",
    "documents",
    "didLogs",
    "didLogsB64",
    "seenVersionIds",
    "limits",
    "logNow",
    "trustedRoots",
    "requirePostQuantum",
    "expectedResource",
    "checkStatus",
    "statusLists",
    "maxDepth",
    "maxReplayWindowSeconds",
    "requireTrustedIssuer",
    "rootsFromDefaults",
];

fn bad(msg: impl Into<String>) -> CoreError {
    CoreError::Json(msg.into())
}

fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
    obj.get(name).filter(|v| !v.is_null())
}

fn bool_member(obj: &Map<String, Value>, name: &str, default: bool) -> Result<bool> {
    match present(obj, name) {
        None => Ok(default),
        Some(Value::Bool(b)) => Ok(*b),
        Some(_) => Err(bad(format!("{name} must be true or false"))),
    }
}

fn object_member<'a>(
    obj: &'a Map<String, Value>,
    name: &str,
) -> Result<Option<&'a Map<String, Value>>> {
    match present(obj, name) {
        None => Ok(None),
        Some(Value::Object(m)) => Ok(Some(m)),
        Some(_) => Err(bad(format!("{name} must be a JSON object"))),
    }
}

fn string_list(v: &Value, name: &str) -> Result<Vec<String>> {
    v.as_array()
        .and_then(|a| {
            a.iter()
                .map(|x| x.as_str().map(String::from))
                .collect::<Option<Vec<_>>>()
        })
        .ok_or_else(|| bad(format!("{name} must be a list of strings")))
}

/// Trusted roots as the reference reads them: a DID or domain, a list of
/// them, or a `{did: key}` map (its keys are also used for those issuers).
/// Every root is normalized ([`crate::did_web::normalize_root`]).
pub fn trusted_roots_from_json(v: &Value) -> Result<Option<TrustedRoots>> {
    let norm = crate::did_web::normalize_root;
    match v {
        Value::Null => Ok(None),
        Value::String(s) => Ok(Some(TrustedRoots {
            dids: vec![norm(s)?],
            keys: BTreeMap::new(),
        })),
        Value::Array(_) => Ok(Some(TrustedRoots {
            dids: string_list(v, "trustedRoots")?
                .iter()
                .map(|s| norm(s))
                .collect::<Result<_>>()?,
            keys: BTreeMap::new(),
        })),
        Value::Object(m) => {
            let mut roots = TrustedRoots::default();
            for (did, key) in m {
                let did = norm(did)?;
                if !roots.dids.contains(&did) {
                    roots.dids.push(did.clone());
                }
                roots.keys.insert(did, key_entry_from_json(key));
            }
            Ok(Some(roots))
        }
        _ => Err(bad(
            "trustedRoots must be a {did: key} map or a list of DIDs",
        )),
    }
}

/// The caller's trusted keys as the reference's `Verifier(trusted_roots=...)`
/// reads them: each DID (or bare domain) normalized, each key a JWK in JSON
/// text. An entry whose DID does not normalize, or whose key is not JWK text
/// (a JSON object with a `kty`), is dropped, so the DID falls back to the
/// other sources. A JWK that is not a usable Ed25519 key stays, as no key.
fn trusted_key_map(obj: &Map<String, Value>) -> Result<BTreeMap<String, KeyEntry>> {
    let mut out = BTreeMap::new();
    for (did, v) in object_member(obj, "trustedKeys")?.into_iter().flatten() {
        let Ok(did) = crate::did_web::normalize_root(did) else {
            continue;
        };
        let is_jwk_text = v.as_str().is_some_and(|t| {
            matches!(serde_json::from_str::<Value>(t), Ok(Value::Object(o))
                if o.get("kty").is_some_and(Value::is_string))
        });
        if is_jwk_text {
            out.insert(did, key_entry_from_json(v));
        }
    }
    Ok(out)
}

fn key_map(obj: &Map<String, Value>, name: &str) -> Result<BTreeMap<String, KeyEntry>> {
    Ok(object_member(obj, name)?
        .map(|m| {
            m.iter()
                // A resolver that answered nothing (null) is left out.
                .filter(|(_, v)| !v.is_null())
                .map(|(did, v)| (did.clone(), key_entry_from_json(v)))
                .collect()
        })
        .unwrap_or_default())
}

/// [`decide`] as one JSON request, for the bindings. The did:webvh logs in
/// the request are checked against `clock` unless it gives `logNow`.
///
/// The request is an object with:
///
/// - `credential`: the credential (an object, or its JSON text);
/// - `now` (required): the verifier's clock; `clockSkewSeconds` (default 30);
/// - `publicKey`: the issuer's key handed over (a Multikey, or a JWK object
///   or text); `mldsa44PublicKey`: the issuer's ML-DSA-44 Multikey;
/// - `trustedKeys`, `resolvedKeys`: keys by DID (the caller's trusted keys,
///   and the key resolver's answers; null means "no answer");
///   `mldsa44Keys`: ML-DSA-44 Multikeys by DID;
/// - `documents`: did:web (or did:webvh) DID documents by DID, as fetched;
/// - `didLogs` / `didLogsB64`: did:webvh logs (`did.jsonl`) by DID, as text
///   or base64; `seenVersionIds`: the latest versionId seen before, by DID;
///   `limits`, `logNow`: as for the did:webvh requests;
/// - `trustedRoots`: a DID or domain, a list, or a `{did: key}` map;
/// - `requirePostQuantum`, `expectedResource`, `checkStatus` (default
///   true), `statusLists` (URL to the fetched list), `maxDepth`,
///   `maxReplayWindowSeconds` (default 43200), `requireTrustedIssuer`
///   (accept only issuers `trustedKeys` names; with no `trustedRoots`, the
///   `trustedKeys` DIDs are also the chain's trusted roots),
///   `rootsFromDefaults` (true when the host read `trustedRoots` from
///   `VOUCH_TRUSTED_ROOTS` or the saved list: those roots do not require a
///   chain from other issuers, as named roots do).
///
/// Returns `{"valid", "reason", "passport", "replay": {"key", "expiresAt",
/// "singleUse"}, "didLogVersions", "didLogErrors"}`. Errors on a malformed
/// request and as [`decide`] does.
pub fn decide_json_with_clock(request: &Value, clock: crate::did_webvh::LogClock) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| bad("the request must be a JSON object"))?;
    let (input, logs) = read_request(obj, clock, &[])?;
    let decision = decide(&input)?;
    let (versions, errors) = match &logs {
        Some(set) => crate::did_webvh::grant_log_json(&set.outcomes()),
        None => (json!({}), json!({})),
    };
    Ok(json!({
        "valid": decision.valid,
        "reason": decision.reason,
        "passport": decision.passport,
        "replay": decision.replay.map(|r| json!({
            "key": r.key,
            "expiresAt": r.expires_at,
            "singleUse": r.single_use,
        })),
        "didLogVersions": versions,
        "didLogErrors": errors,
    }))
}

/// Read a decision request (see [`decide_json_with_clock`]); `extra` names
/// members another entry point reads itself.
fn read_request(
    obj: &Map<String, Value>,
    clock: crate::did_webvh::LogClock,
    extra: &[&str],
) -> Result<(DecisionInput, Option<crate::did_webvh::LogSet>)> {
    use crate::did_webvh::{base64_decode, is_did_webvh, LogClock, LogSet};

    if let Some(name) = obj
        .keys()
        .find(|k| !REQUEST_MEMBERS.contains(&k.as_str()) && !extra.contains(&k.as_str()))
    {
        return Err(bad(format!(
            "the request holds an unknown member {:?}",
            name.chars().take(40).collect::<String>()
        )));
    }
    let credential = match obj.get("credential") {
        Some(Value::String(text)) => serde_json::from_str(text).unwrap_or(Value::Null),
        Some(v) => v.clone(),
        None => return Err(bad("credential is required")),
    };
    let now = obj
        .get("now")
        .and_then(Value::as_str)
        .ok_or_else(|| bad("now must be a protocol time"))?;
    let mut input = DecisionInput::new(credential, now);
    match obj.get("clockSkewSeconds") {
        None => {}
        // A skew written as null is not "the default": the reference refuses it.
        Some(Value::Null) => return Err(bad("clockSkewSeconds must be a whole number of seconds")),
        Some(v) => input.clock_skew_seconds = crate::time::clock_skew_from_json(v)?,
    }
    input.public_key = present(obj, "publicKey").map(key_entry_from_json);
    input.mldsa44_public_key = present(obj, "mldsa44PublicKey").map(mldsa44_key_from_json);
    input.trusted_keys = trusted_key_map(obj)?;
    input.resolved_keys = key_map(obj, "resolvedKeys")?;
    if let Some(m) = object_member(obj, "mldsa44Keys")? {
        for (did, v) in m {
            // A key that is not an ML-DSA-44 Multikey is no key.
            if let Some(k) = mldsa44_key_from_json(v) {
                input.mldsa44_keys.insert(did.clone(), k);
            }
        }
    }
    if let Some(m) = object_member(obj, "documents")? {
        for (did, doc) in m {
            if !has_did_document(did) {
                return Err(bad(
                    "documents holds a DID that is not did:web or did:webvh",
                ));
            }
            if !doc.is_null() {
                input.documents.insert(did.clone(), doc.clone());
            }
        }
    }
    // did:webvh logs: each is verified in full, and its latest state is the
    // DID's document.
    let clock = match present(obj, "logNow") {
        None => clock,
        Some(v) => LogClock::At(parse_protocol_time_ns(
            v.as_str()
                .ok_or_else(|| bad("logNow must be a protocol time"))?,
        )?),
    };
    let mut logs: Option<LogSet> = None;
    let texts = object_member(obj, "didLogs")?;
    let b64s = object_member(obj, "didLogsB64")?;
    if texts.is_some() || b64s.is_some() {
        let mut set = LogSet::new(clock)?;
        if let Some(limits) = present(obj, "limits") {
            set = set.with_limits(crate::did_webvh::Limits::from_json(limits)?);
        }
        let mut given: Vec<(String, Vec<u8>)> = Vec::new();
        for (did, v) in texts.into_iter().flatten() {
            let t = v
                .as_str()
                .ok_or_else(|| bad("didLogs must map DIDs to log text"))?;
            given.push((did.clone(), t.as_bytes().to_vec()));
        }
        for (did, v) in b64s.into_iter().flatten() {
            let t = v
                .as_str()
                .ok_or_else(|| bad("didLogsB64 must map DIDs to base64 logs"))?;
            given.push((did.clone(), base64_decode(t, "a didLogsB64 log")?));
        }
        for (did, log) in given {
            if !is_did_webvh(&did) {
                return Err(bad("didLogs holds a DID that is not a did:webvh DID"));
            }
            if set.contains(&did) || input.documents.contains_key(&did) {
                return Err(bad(
                    "give each DID's log once, in didLogs, didLogsB64 or documents",
                ));
            }
            set = set.with_log(&did, log);
        }
        if let Some(m) = object_member(obj, "seenVersionIds")? {
            for (did, v) in m {
                let seen = v
                    .as_str()
                    .ok_or_else(|| bad("seenVersionIds must map DIDs to versionIds"))?;
                set = set.with_seen_version_id(did, seen)?;
            }
        }
        logs = Some(set);
    }
    if let Some(v) = present(obj, "trustedRoots") {
        input.trusted_roots = trusted_roots_from_json(v)?;
    }
    input.require_post_quantum = bool_member(obj, "requirePostQuantum", false)?;
    input.expected_resource = match present(obj, "expectedResource") {
        None => None,
        Some(Value::String(s)) => Some(s.clone()),
        Some(_) => return Err(bad("expectedResource must be a string")),
    };
    input.check_status = bool_member(obj, "checkStatus", true)?;
    if let Some(m) = object_member(obj, "statusLists")? {
        input.status_lists = m.clone();
    }
    input.max_depth = match present(obj, "maxDepth") {
        None => None,
        Some(v) => Some(
            v.as_u64()
                .and_then(|d| usize::try_from(d).ok())
                .ok_or_else(|| bad("maxDepth must be a non-negative whole number"))?,
        ),
    };
    if let Some(v) = present(obj, "maxReplayWindowSeconds") {
        input.max_replay_window_seconds = match v {
            Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
            _ => return Err(bad("max_replay_window must be a number of seconds")),
        };
    }
    // A verifier that requires a trusted issuer accepts only the issuers its
    // trusted keys name; with no trusted roots given, those DIDs are also the
    // chain's trusted starting points (the reference's Verifier object).
    if bool_member(obj, "requireTrustedIssuer", false)? {
        input.allowed_issuers = Some(input.trusted_keys.keys().cloned().collect());
    }
    if present(obj, "trustedRoots").is_none() && !input.trusted_keys.is_empty() {
        input.trusted_roots = Some(TrustedRoots {
            dids: input.trusted_keys.keys().cloned().collect(),
            keys: BTreeMap::new(),
        });
    }
    // Roots the caller named require a chain from any other issuer; roots
    // the host read from VOUCH_TRUSTED_ROOTS or the saved list do not.
    input.chain_required_outside_roots =
        input.trusted_roots.is_some() && !bool_member(obj, "rootsFromDefaults", false)?;

    if let Some(set) = &logs {
        for did in obj
            .get("didLogs")
            .and_then(Value::as_object)
            .into_iter()
            .chain(obj.get("didLogsB64").and_then(Value::as_object))
            .flat_map(|m| m.keys())
        {
            if let Some(Ok(resolution)) = set.resolve(did) {
                input.documents.insert(did.clone(), resolution.document);
            }
        }
    }

    Ok((input, logs))
}

/// [`decide_json_with_clock`] with did:webvh logs checked against the system
/// clock.
pub fn decide_json(request: &Value) -> Result<Value> {
    decide_json_with_clock(request, crate::did_webvh::LogClock::System)
}

/// [`fetch_plan`] as JSON: the request is a decision request (see
/// [`decide_json_with_clock`]) plus `"phase"`: `"documents"` (the default)
/// or `"statusLists"`. Returns `{"refusal", "dids", "statusLists",
/// "truncated"}`.
pub fn fetch_plan_json_with_clock(
    request: &Value,
    clock: crate::did_webvh::LogClock,
) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| bad("the request must be a JSON object"))?;
    let phase = match present(obj, "phase").map(|v| v.as_str()) {
        None | Some(Some("documents")) => FetchPhase::Documents,
        Some(Some("statusLists")) => FetchPhase::StatusLists,
        _ => return Err(bad("phase must be \"documents\" or \"statusLists\"")),
    };
    let (input, _logs) = read_request(obj, clock, &["phase"])?;
    let plan = fetch_plan(&input, phase)?;
    Ok(json!({
        "refusal": plan.refusal,
        "dids": plan.dids,
        "statusLists": plan.status_lists,
        "truncated": plan.truncated,
    }))
}

/// [`fetch_plan_json_with_clock`] with did:webvh logs checked against the
/// system clock.
pub fn fetch_plan_json(request: &Value) -> Result<Value> {
    fetch_plan_json_with_clock(request, crate::did_webvh::LogClock::System)
}

/// [`replay_identity`] as JSON: `{"credential", "now", "clockSkewSeconds"
/// (default 30), "maxReplayWindowSeconds" (default 43200)}` to `{"key",
/// "expiresAt", "singleUse"}`.
pub fn replay_identity_json(request: &Value) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| bad("the request must be a JSON object"))?;
    let credential = obj
        .get("credential")
        .filter(|c| c.is_object())
        .ok_or_else(|| bad("credential must be a JSON object"))?;
    let now = obj
        .get("now")
        .and_then(Value::as_str)
        .ok_or_else(|| bad("now must be a protocol time"))?;
    let skew = match present(obj, "clockSkewSeconds") {
        None => DEFAULT_CLOCK_SKEW_SECONDS,
        Some(v) => crate::time::clock_skew_from_json(v)?,
    };
    let window = match present(obj, "maxReplayWindowSeconds") {
        None => DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
        Some(v) => v
            .as_f64()
            .ok_or_else(|| bad("max_replay_window must be a number of seconds"))?,
    };
    let r = replay_identity(credential, now, skew, window)?;
    Ok(json!({"key": r.key, "expiresAt": r.expires_at, "singleUse": r.single_use}))
}

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

    #[test]
    fn showable_dids() {
        assert!(showable_did("did:web:example.com"));
        assert!(showable_did("did:key:z6Mk"));
        assert!(!showable_did("did:Web:example.com"));
        assert!(!showable_did("did:web:"));
        assert!(!showable_did("did:web:a b"));
        assert!(!showable_did(&format!("did:web:{}", "a".repeat(201))));
        assert_eq!(
            untrusted_root_reason(Some("did:web:root.example"), true),
            "the chain's starting point is not trusted: run `vouch trust did:web:root.example` \
             (it is not one of the trusted roots)"
        );
        assert_eq!(
            untrusted_root_reason(Some("did:web:a b"), false),
            REASON_UNTRUSTED_START
        );
    }

    #[test]
    fn group_order_matches_the_curve() {
        // S = L - 1 is accepted, S = L refused; R is the base point's
        // encoding (y = 4/5), a canonical point of large order.
        let mut sig = [0u8; 64];
        let base = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
        sig[..32].copy_from_slice(base.as_bytes());
        sig[32..].copy_from_slice(&GROUP_ORDER_LE);
        assert!(!strict_signature(&sig));
        sig[32] -= 1;
        assert!(strict_signature(&sig));
    }

    #[test]
    fn bad_requests_are_errors() {
        let cred = json!({});
        let mut input = DecisionInput::new(cred, "2026-01-01T00:00:00Z");
        input.max_replay_window_seconds = 0.0;
        assert!(decide(&input).is_err());
        input.max_replay_window_seconds = 10.0;
        input.clock_skew_seconds = 121;
        assert!(decide(&input).is_err());
        let not_object = DecisionInput::new(json!([1]), "2026-01-01T00:00:00Z");
        assert_eq!(
            decide(&not_object).unwrap().reason.as_deref(),
            Some("the credential is not a JSON object")
        );
    }
}