aph-core 0.2.0

APH (Agent per Human) protocol — envelope wire types, mandates, notarization flow state machines, and signing helpers (spec v0.1.0 + the v0.2 delta)
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
//! Revocation status transport — the parsing and decision half (spec §6.3.3).
//!
//! §6.3.1 makes revocation normative and §6.3.2 makes expiry normative, but
//! only expiry is readable from an envelope alone. This module is the
//! machinery a third-party recipient uses to learn, at verification time,
//! that the parent Delegation Mandate was withdrawn: the status entry that
//! travels on the envelope (§6.3.3.1), the endpoint the verifier DERIVES
//! from the notary's own `did:web` (§6.3.3.2), the status list credential
//! served there (§6.3.3.3), and the three-outcome decision of §6.3.3.4.
//!
//! **The whole security argument is one sentence: the envelope does not get
//! to choose which host answers "is this mandate revoked".** The origin is
//! derived from `credentialSubject.notarization.notaryService.id`; a
//! `statusListCredential` carried in the envelope is bound same-origin
//! against that derivation and REFUSED WITHOUT BEING FETCHED when it is not
//! (§6.3.3.2). Whoever holds an old envelope would otherwise also choose the
//! host, and a host of the attacker's choosing always answers *not revoked*.
//!
//! **Fetching still happens elsewhere.** As with [`crate::discovery`], this
//! crate parses and decides; the one HTTPS GET arrives through
//! [`crate::discovery::ports::StatusCredentialFetch`], the sibling port
//! declared beside the `did:web` document port. That is why every rule below
//! is exercised against fixed strings with no network.
//!
//! **One producer rule lives here too**, against the "parsing and decision"
//! framing above: [`STATUS_REPUBLISH_INTERVAL_SECONDS`] is §6.3.3.3's cadence
//! MUST, and it is held beside the verifier's two bounds because publisher
//! and verifier have to agree on those three numbers to the second. A
//! publisher that re-derives the interval from prose is a second expression
//! of a normative value, which is how the two sides drift apart.
//!
//! ## Two obligations this module deliberately does NOT discharge
//!
//! 1. **⛔ The status list credential's own proof is NOT verified here.**
//!    §6.3.3.3 requires it, and it is load-bearing rather than decorative:
//!    same-origin permits a DIFFERENT PATH (that is how a notary points at a
//!    second list, §6.3.3.6), so a host with any writable path — an upload
//!    directory, a user-content route — lets an attacker publish a forged
//!    list that satisfies same-origin AND simply writes the notary's DID
//!    into its own `issuer`. Only the signature closes that. Verifying it
//!    needs the notary's key, and resolving a key needs the two §8.4
//!    discovery ports and the host's cache — state this crate does not hold,
//!    and a key this crate must not GUESS (the envelope's key is the one
//!    valid at `decisionTimestamp` per §8.4.7, which after a rotation is not
//!    the key the CURRENT list is signed with). The caller therefore owns
//!    the step, and [`status_list_signing_base`] plus
//!    [`StatusListCredential::proof_verification_method`] are provided so it
//!    is a few lines rather than a re-derivation.
//! 2. **The GZIP expansion of `encodedList` is supplied by the caller.**
//!    `aph-core`'s eight dependencies are serde, serde_json, thiserror,
//!    chrono, two signature primitives (`ed25519-dalek`, `p256`) and two
//!    encoders (`bs58`, `base64`) — there is no compression codec among
//!    them, while the pinned vintage (§14.1, W3C Bitstring Status List
//!    v1.0) mandates GZIP. Rather than vendor a decompressor into a
//!    security-critical parse path or mint a second port for what is a pure
//!    codec and not a domain seam, [`check_credential_status`] takes the
//!    expansion as a plain function argument. It is called LAST — after
//!    same-origin binding, issuer binding, purpose and freshness have all
//!    passed — so a caller's decompressor never sees bytes from an origin
//!    the verifier did not derive.

/// `credentialStatus.type` — the pinned entry type of §6.3.3.1.
pub const STATUS_ENTRY_TYPE: &str = "BitstringStatusListEntry";

/// The only `statusPurpose` APH defines (§6.3.3.5).
pub const STATUS_PURPOSE_REVOCATION: &str = "revocation";

/// The `type` a status list credential must carry (§6.3.3.3).
pub const STATUS_LIST_CREDENTIAL_TYPE: &str = "BitstringStatusListCredential";

/// The `type` the status list credential's subject carries, when it carries
/// one (§6.3.3.3 leaves the member to the W3C profile).
pub const STATUS_LIST_SUBJECT_TYPE: &str = "BitstringStatusList";

/// Last path segment of the derived status endpoint (§6.3.3.2 step 2), the
/// counterpart of `did.json` in §8.4.4 step 2.
pub const STATUS_ENDPOINT_LEAF: &str = "aph-status.json";

/// §6.3.3.3 freshness bound: a status list credential issued more than this
/// many seconds before `now` MUST NOT be accepted.
pub const STATUS_MAX_AGE_SECONDS: i64 = 300;

/// §6.3.3.3 clock-skew tolerance, the same 60 seconds §8.3 step 6 allows.
/// Applied in BOTH directions: it widens the staleness bound and it is the
/// only amount by which a credential may be dated into the future.
pub const STATUS_CLOCK_SKEW_SECONDS: i64 = 60;

/// §6.3.3.3 producer cadence: a notary that publishes status MUST re-issue
/// and republish at an interval no greater than this.
///
/// The verifier's two bounds above were already constants here; this one was
/// only ever prose, which left every publisher to copy the number out of the
/// specification — a second expression of a normative value, in the one
/// mechanism where publisher and verifier must agree to the second.
///
/// It is deliberately less than half of [`STATUS_MAX_AGE_SECONDS`], and that
/// margin is what makes the pair a system rather than a coincidence: a
/// publisher that misses a cycle is LATE, not down, and a verifier still
/// finds a credential inside the bound. [`StatusListCredential::seconds_until_republish_due`]
/// is the margin read as a number an operator can watch.
pub const STATUS_REPUBLISH_INTERVAL_SECONDS: i64 = 120;

/// Multibase prefix for base64url-no-pad, the encoding `encodedList` uses.
pub const MULTIBASE_BASE64URL_PREFIX: char = 'u';

/// Hard cap on the expanded bitstring this module will index into.
///
/// 1 MiB addresses 8,388,608 mandates — orders of magnitude past any notary
/// this specification contemplates — so a list larger than this is a
/// malformed or hostile document rather than a big deployment.
///
/// ⛔ WHERE THIS IS AND IS NOT A BOMB DEFENCE. The expansion happens in a
/// caller-supplied decompressor ([`ExpandEncodedList`]), so this constant can
/// only be a real memory bound at the place that produces the bytes: the
/// contract on that alias makes stopping at this cap a MUST on the expander.
/// The check inside [`revocation_bit`] runs on a `Vec` that already exists
/// and therefore refuses an over-long list AFTER the allocation — a
/// correctness backstop, not protection against a decompression bomb. Stating
/// the split matters because the opposite claim was written here first, and a
/// verifier that believed it would run an unbounded codec over unbounded
/// network bytes on the strength of a comment.
pub const MAX_EXPANDED_LIST_BYTES: usize = 1024 * 1024;

/// `credentialStatus.type`, a closed set of exactly one member (§6.3.3.1).
///
/// Modelled as an enum rather than a `String` so an unrecognized value is a
/// hard deserialization error — which is precisely where §6.3.3.1 routes it,
/// §7.1's strict parse at §8.3 step 1.
#[derive(
  std::fmt::Debug,
  std::clone::Clone,
  std::marker::Copy,
  std::cmp::PartialEq,
  std::cmp::Eq,
  serde::Serialize,
  serde::Deserialize,
)]
pub enum StatusEntryType {
  /// The W3C Bitstring Status List v1.0 entry type, the vintage §14.1 pins.
  #[serde(rename = "BitstringStatusListEntry")]
  BitstringStatusListEntry,
}

/// `credentialStatus.statusPurpose`, a closed set of exactly one member
/// (§6.3.3.5).
///
/// `"suspension"` is deliberately absent: suspension is reversible and
/// §6.3.2 forbids re-activation, so admitting it would put a lifecycle in
/// the transport that the mandate itself does not have.
///
/// Modelled as an enum for a security reason §6.3.3.5 states outright: a
/// verifier MUST NOT read a purpose it does not recognize as "no status
/// claim was made", because a producer could then disable the check on any
/// verifier by writing a word that verifier has never seen. An enum makes
/// that opt-out unconstructible — the envelope fails to parse at all.
#[derive(
  std::fmt::Debug,
  std::clone::Clone,
  std::marker::Copy,
  std::cmp::PartialEq,
  std::cmp::Eq,
  serde::Serialize,
  serde::Deserialize,
)]
pub enum StatusPurpose {
  /// The mandate's authority was withdrawn by the human who granted it.
  #[serde(rename = "revocation")]
  Revocation,
}

/// The status reference an envelope carries at top-level `credentialStatus`
/// (spec §6.3.3.1, §7.1.1).
///
/// **Whose status this is.** In W3C VC 2.0 `credentialStatus` describes the
/// credential carrying it. In APH it describes the **parent Delegation
/// Mandate** named by `credentialSubject.policy.delegationMandateId`: an
/// issued envelope stays cryptographically valid whatever happens
/// afterwards, and revocation applies to Delegation Mandates only.
#[derive(
  std::fmt::Debug,
  std::clone::Clone,
  std::cmp::PartialEq,
  std::cmp::Eq,
  serde::Serialize,
  serde::Deserialize,
)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CredentialStatusEntry {
  /// Identifier for this status entry. Omitted when absent.
  #[serde(default, skip_serializing_if = "std::option::Option::is_none")]
  pub id: std::option::Option<String>,
  /// Always [`StatusEntryType::BitstringStatusListEntry`].
  #[serde(rename = "type")]
  pub r#type: StatusEntryType,
  /// Always [`StatusPurpose::Revocation`].
  pub status_purpose: StatusPurpose,
  /// This mandate's position in the list, a base-10 integer **in a JSON
  /// string** (§6.3.3.6).
  ///
  /// A `String` on the wire AND in Rust, never a numeric type. In runtimes
  /// where every JSON number is an IEEE-754 double, an index past 2^53 is
  /// silently rounded — and a rounded index does not raise a parse error, it
  /// reads a DIFFERENT BIT, so the verifier answers a question about some
  /// other mandate with full confidence. Typing the field `String` makes a
  /// JSON number a deserialization failure instead of a wrong answer.
  /// [`Self::index`] is the only way to a number, and it goes through
  /// `u64`.
  pub status_list_index: String,
  /// Absolute `https:` URL of the status list credential. Bound same-origin
  /// against the derived endpoint before it is ever fetched (§6.3.3.2).
  pub status_list_credential: String,
}

impl CredentialStatusEntry {
  /// Parses [`Self::status_list_index`] as a base-10 `u64` (§6.3.3.6).
  ///
  /// # Errors
  ///
  /// `APH_E008` for anything that is not a base-10 integer inside `u64`.
  /// §6.3.3.1 routes a malformed status reference to §8.3 step 1, but the
  /// §11 taxonomy is a CLOSED set of seventeen with no "malformed envelope"
  /// code; `APH_E008` is §6.3.3.4 case 2 — "the verifier could not establish
  /// the status" — which is literally what an unreadable index leaves. The
  /// envelope is refused either way; only the reported code differs.
  pub fn index(&self) -> std::result::Result<u64, crate::errors::AphError> {
    // Rejected explicitly rather than left to `from_str`: `u64::from_str`
    // accepts a leading `+`, and a sign on a bit position is not a base-10
    // integer in the sense §6.3.3.6 means.
    if self.status_list_index.is_empty()
      || !self.status_list_index.bytes().all(|b| b.is_ascii_digit())
    {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
    match self.status_list_index.parse::<u64>() {
      std::result::Result::Ok(index) => std::result::Result::Ok(index),
      // Overflow past u64 is unreachable for any real list but must not
      // wrap or panic: it is simply an index no published list contains.
      std::result::Result::Err(_) => {
        std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable)
      }
    }
  }
}

/// A status list credential fetched from the notary's own origin
/// (spec §6.3.3.3).
///
/// Deliberately NOT `deny_unknown_fields`, for the same reason
/// [`crate::discovery::did_document::DidDocument`] is not: this is a general
/// W3C artifact that legitimately carries more than APH reads (`name`,
/// `description`, `ttl`, `validUntil`, `renderMethod`). Rejecting those
/// would make APH unable to consume ordinary status list credentials. The
/// ENVELOPE's own [`CredentialStatusEntry`] is strict, because that one is
/// APH's wire shape and is covered by a signature.
#[derive(std::fmt::Debug, std::clone::Clone, serde::Serialize, serde::Deserialize)]
pub struct StatusListCredential {
  /// JSON-LD contexts the document declares.
  #[serde(default, rename = "@context")]
  pub context: std::vec::Vec<serde_json::Value>,
  /// The credential's own identifier, when it carries one.
  #[serde(default)]
  pub id: std::option::Option<String>,
  /// JSON-LD type array; MUST include [`STATUS_LIST_CREDENTIAL_TYPE`].
  #[serde(default, rename = "type")]
  pub r#type: std::vec::Vec<String>,
  /// The issuing notary. W3C permits a bare DID string or an object with an
  /// `id`, so both are kept verbatim and read through
  /// [`Self::issuer_did`].
  #[serde(default)]
  pub issuer: serde_json::Value,
  /// RFC 3339 issuance instant. The freshness bound of §6.3.3.3 is measured
  /// from this, so a document without it cannot be accepted.
  #[serde(default, rename = "validFrom")]
  pub valid_from: std::option::Option<String>,
  /// The subject carrying the purpose and the bitstring.
  #[serde(rename = "credentialSubject")]
  pub credential_subject: StatusListSubject,
  /// The notary's proof over this document. Kept verbatim: this module does
  /// not verify it (see the module preamble), it only surfaces the
  /// verification method the caller must resolve.
  #[serde(default)]
  pub proof: serde_json::Value,
}

/// The `credentialSubject` of a status list credential (spec §6.3.3.3).
#[derive(std::fmt::Debug, std::clone::Clone, serde::Serialize, serde::Deserialize)]
pub struct StatusListSubject {
  /// Subject identifier, when present.
  #[serde(default)]
  pub id: std::option::Option<String>,
  /// Subject type; [`STATUS_LIST_SUBJECT_TYPE`] when present.
  #[serde(default, rename = "type")]
  pub r#type: std::option::Option<String>,
  /// The purpose this list expresses. A `String` here, NOT the
  /// [`StatusPurpose`] enum the envelope entry uses, and the asymmetry is
  /// the spec's: an unrecognized purpose on the ENVELOPE is malformed wire
  /// (§6.3.3.5, refused at §8.3 step 1), while an unrecognized purpose in
  /// the fetched DOCUMENT is §6.3.3.4 case 2 — the status could not be
  /// established — and carries `APH_E008`. Parsing it as an enum here would
  /// collapse the second case into the first.
  #[serde(rename = "statusPurpose")]
  pub status_purpose: String,
  /// Multibase base64url of the GZIP-compressed bitstring.
  #[serde(rename = "encodedList")]
  pub encoded_list: String,
}

impl StatusListCredential {
  /// The issuing DID, whether `issuer` is a string or an object with an
  /// `id` — both are W3C-legal and a verifier that read only one form would
  /// refuse conformant notaries.
  pub fn issuer_did(&self) -> std::option::Option<&str> {
    match &self.issuer {
      serde_json::Value::String(did) => std::option::Option::Some(did.as_str()),
      serde_json::Value::Object(object) => object.get("id").and_then(|v| v.as_str()),
      _ => std::option::Option::None,
    }
  }

  /// The `proof.verificationMethod` the caller must resolve through §8.4 to
  /// check this document's signature — the step named in the module
  /// preamble as NOT performed here.
  ///
  /// `None` when the document carries no proof or no method, which the
  /// caller MUST treat as §6.3.3.4 case 2 rather than as "nothing to check".
  pub fn proof_verification_method(&self) -> std::option::Option<&str> {
    match &self.proof {
      serde_json::Value::Object(object) => {
        object.get("verificationMethod").and_then(|v| v.as_str())
      }
      // A proof chain on a status list is not a shape §6.3.3.3 defines, so
      // an array is reported as "no single method" rather than guessed at.
      _ => std::option::Option::None,
    }
  }

  /// Applies every §6.3.3.3 check this crate can make without a key: the
  /// credential type, the issuer binding, the purpose, and the freshness
  /// bound.
  ///
  /// `notary_did` is the DID the endpoint was DERIVED from (§6.3.3.2 step
  /// 1), never a value read out of the document — same-origin alone does not
  /// make a document authoritative, because one host serves many documents.
  ///
  /// # Errors
  ///
  /// `APH_E008` for every failure, per §6.3.3.4 case 2's single-code rule:
  /// the verifier's action (reject) and the operator's remediation (repair
  /// the notary's status surface) are identical for all of them.
  pub fn validate(
    &self,
    notary_did: &str,
    now_rfc3339: &str,
  ) -> std::result::Result<(), crate::errors::AphError> {
    if !self.r#type.iter().any(|t| t == STATUS_LIST_CREDENTIAL_TYPE) {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
    // Checked only when present: §6.3.3.3 names the purpose, the issuer, the
    // proof and the freshness bound as APH's normative checks and leaves the
    // subject's own `type` to the W3C profile, so REQUIRING it here would
    // refuse documents that are conformant as far as APH ever said.
    if self
      .credential_subject
      .r#type
      .as_deref()
      .is_some_and(|subject_type| subject_type != STATUS_LIST_SUBJECT_TYPE)
    {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
    if self.credential_subject.status_purpose != STATUS_PURPOSE_REVOCATION {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
    if self.issuer_did() != std::option::Option::Some(notary_did) {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
    self.check_freshness(now_rfc3339)
  }

  /// The §6.3.3.3 freshness bound, split out so it can be pinned on its own.
  ///
  /// Fails CLOSED in every direction: a missing or unparseable `validFrom`,
  /// an unparseable `now`, a credential older than
  /// [`STATUS_MAX_AGE_SECONDS`] plus the skew allowance, and a credential
  /// dated further into the future than the skew allowance all refuse. A
  /// future-dated document is refused because the alternative is a notary
  /// (or an attacker who reached its publishing pipeline) buying unbounded
  /// staleness by writing tomorrow's date.
  pub fn check_freshness(
    &self,
    now_rfc3339: &str,
  ) -> std::result::Result<(), crate::errors::AphError> {
    let age_seconds = self.age_seconds(now_rfc3339)?;
    if age_seconds > STATUS_MAX_AGE_SECONDS + STATUS_CLOCK_SKEW_SECONDS {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
    if age_seconds < -STATUS_CLOCK_SKEW_SECONDS {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
    std::result::Result::Ok(())
  }

  /// Seconds remaining before this document must have been REPLACED by a
  /// freshly issued one, per [`STATUS_REPUBLISH_INTERVAL_SECONDS`]. Negative
  /// once the producer is late.
  ///
  /// This is the PUBLISHER's line, and it is the one worth alarming on. A
  /// publication pipeline that stops fails closed — correct, and silent: the
  /// first symptom is a stranger's verifier refusing an envelope, which is
  /// the far end of the outage to learn at. The deadline is exposed as a
  /// distance rather than as a verdict so an operator can watch it approach
  /// instead of discovering it has passed.
  ///
  /// # Errors
  ///
  /// `APH_E008` for the same timestamp failures [`Self::check_freshness`]
  /// refuses on — a missing or unparseable `validFrom`, or an unparseable
  /// `now`. A distance is not reported from a clock that could not be read,
  /// because a monitor would display it as time remaining.
  pub fn seconds_until_republish_due(
    &self,
    now_rfc3339: &str,
  ) -> std::result::Result<i64, crate::errors::AphError> {
    std::result::Result::Ok(STATUS_REPUBLISH_INTERVAL_SECONDS - self.age_seconds(now_rfc3339)?)
  }

  /// Seconds remaining before a conformant verifier begins REFUSING this
  /// document under §6.3.3.3's freshness bound. Negative once they do.
  ///
  /// The same bound [`Self::check_freshness`] applies, read as a distance
  /// rather than as a verdict — the outage line, where
  /// [`Self::seconds_until_republish_due`] is the alarm line.
  ///
  /// # Errors
  ///
  /// `APH_E008`, on the same inputs and for the same reason as
  /// [`Self::seconds_until_republish_due`].
  pub fn seconds_until_stale(
    &self,
    now_rfc3339: &str,
  ) -> std::result::Result<i64, crate::errors::AphError> {
    std::result::Result::Ok(
      STATUS_MAX_AGE_SECONDS + STATUS_CLOCK_SKEW_SECONDS - self.age_seconds(now_rfc3339)?,
    )
  }

  /// Age of this document at `now_rfc3339`, in seconds; negative when the
  /// document is dated into the future.
  ///
  /// Every timestamp failure is `APH_E008` because §6.3.3.4 case 2 gives the
  /// whole mechanism one code. Shared by the freshness verdict and the two
  /// deadline distances so those three can never disagree about how old a
  /// document is.
  fn age_seconds(
    &self,
    now_rfc3339: &str,
  ) -> std::result::Result<i64, crate::errors::AphError> {
    let issued = match self.valid_from.as_deref() {
      std::option::Option::Some(value) => value,
      std::option::Option::None => {
        return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
      }
    };
    let issued = match chrono::DateTime::parse_from_rfc3339(issued) {
      std::result::Result::Ok(t) => t,
      std::result::Result::Err(_) => {
        return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
      }
    };
    let now = match chrono::DateTime::parse_from_rfc3339(now_rfc3339) {
      std::result::Result::Ok(t) => t,
      std::result::Result::Err(_) => {
        return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
      }
    };
    std::result::Result::Ok((now - issued).num_seconds())
  }
}

/// Parses a status list credential from the bytes an adapter fetched.
///
/// # Errors
///
/// `APH_E008` — a document that will not parse is indistinguishable, from a
/// verifier's seat, from a status surface that could not be reached
/// (§6.3.3.4 case 2). This mirrors
/// [`crate::discovery::did_document::parse_did_document`].
pub fn parse_status_list_credential(
  json: &str,
) -> std::result::Result<StatusListCredential, crate::errors::AphError> {
  match serde_json::from_str::<StatusListCredential>(json) {
    std::result::Result::Ok(credential) => std::result::Result::Ok(credential),
    std::result::Result::Err(_) => {
      std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable)
    }
  }
}

/// The canonical bytes a status list credential's proof covers: the document
/// with its `proof` member removed, JCS-canonicalized.
///
/// Provided because this module does not verify that proof (module
/// preamble): the caller resolves the notary key through §8.4 and checks the
/// signature over exactly these bytes. Deriving the base a second time in
/// the host is how signer and verifier drift apart, which is the reason
/// [`crate::crypto::proof_base`] exists for envelopes.
///
/// # Errors
///
/// `APH_E008` when the body is not a JSON object.
pub fn status_list_signing_base(
  raw_json: &str,
) -> std::result::Result<String, crate::errors::AphError> {
  let mut value = match serde_json::from_str::<serde_json::Value>(raw_json) {
    std::result::Result::Ok(v) => v,
    std::result::Result::Err(_) => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  match value.as_object_mut() {
    std::option::Option::Some(object) => {
      object.remove("proof");
    }
    std::option::Option::None => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  }
  std::result::Result::Ok(crate::crypto::jcs::canonicalize_rfc8785(&value))
}

/// §6.3.3.3 — verifies the status list's OWN proof against a known key.
///
/// ⛔ WHY THIS IS NOT OPTIONAL, AND WHY THE KEY IS A REQUIRED ARGUMENT RATHER
/// THAN A DOC COMMENT ASKING NICELY: a status list that is not signature-checked
/// is an unauthenticated assertion about whether somebody's authority is still
/// valid. An attacker who can write to the status endpoint — or who can answer
/// for it — would otherwise flip a revoked mandate back to live, and the
/// revocation transport would become the mechanism by which a revoked agent
/// proves it is fine. Earlier drafts documented this as "the caller's step";
/// documentation is prose, and prose is the weakest rung of
/// `type > sealed port > tripwire > prose`. Taking the key by value makes the
/// check unskippable: there is no way to reach a verdict without supplying the
/// key that authenticates it.
///
/// The caller already HAS this key. It must resolve the issuer's key through
/// §8.4 to verify the envelope itself before a status question is even
/// meaningful, so this consumes that resolution rather than performing a second
/// one (§3.4) — and no new port is introduced to fetch it.
///
/// # Errors
///
/// `APH_E008` when the document carries no proof, when the proof value is
/// malformed, or when the signature does not verify — all §6.3.3.4 case-2
/// outcomes, which the caller REFUSES rather than admits.
pub fn verify_status_list_proof(
  raw_json: &str,
  credential: &StatusListCredential,
  key: &ed25519_dalek::VerifyingKey,
) -> std::result::Result<(), crate::errors::AphError> {
  let proof_value = match &credential.proof {
    serde_json::Value::Object(object) => match object.get("proofValue").and_then(|v| v.as_str()) {
      std::option::Option::Some(value) if !value.is_empty() => value,
      // No proof, or an empty one, is an UNSIGNED document. §6.3.3.4 case 2
      // names it explicitly; it is never "nothing to check".
      _ => return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable),
    },
    // A proof chain is not a shape §6.3.3.3 defines for a status list. Refusing
    // beats guessing which link would have been authoritative.
    _ => return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable),
  };
  let raw = match crate::crypto::multibase::base58btc_decode(proof_value) {
    std::result::Result::Ok(bytes) => bytes,
    std::result::Result::Err(_) => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  let bytes: [u8; 64] = match raw.as_slice().try_into() {
    std::result::Result::Ok(b) => b,
    std::result::Result::Err(_) => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  let signature = ed25519_dalek::Signature::from_bytes(&bytes);
  // Signed over the SAME canonical base the issuer signed: the document with
  // its own `proof` member removed, JCS-canonicalised.
  let canonical = status_list_signing_base(raw_json)?;
  match ed25519_dalek::Verifier::verify(key, canonical.as_bytes(), &signature) {
    std::result::Result::Ok(()) => std::result::Result::Ok(()),
    std::result::Result::Err(_) => {
      std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable)
    }
  }
}

/// Decodes `encodedList` to the GZIP stream it wraps (§6.3.3.3).
///
/// The value is MULTIBASE — a `u` prefix naming base64url-no-pad — and the
/// prefix is REQUIRED rather than tolerated as optional. §14.1 pins the
/// vintage precisely because a value that two vintages read differently
/// looks conformant to both and interoperates with neither; the earlier
/// Status List 2021 shape wrote bare base64url at this position, and quietly
/// accepting it would mean silently reading a different specification's
/// document.
///
/// The GZIP magic is checked here, before the bytes are handed to a
/// caller-supplied decompressor, so that codec is never asked to read a
/// format nobody agreed on.
///
/// # Errors
///
/// `APH_E008` for a missing prefix, an undecodable body, or bytes that are
/// not a GZIP stream.
pub fn decode_encoded_list(
  encoded: &str,
) -> std::result::Result<std::vec::Vec<u8>, crate::errors::AphError> {
  let body = match encoded.strip_prefix(MULTIBASE_BASE64URL_PREFIX) {
    std::option::Option::Some(body) => body,
    std::option::Option::None => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  let bytes = match crate::crypto::base64url::decode(body) {
    std::result::Result::Ok(bytes) => bytes,
    std::result::Result::Err(_) => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  // RFC 1952 §2.3.1: every GZIP member begins 0x1f 0x8b.
  if bytes.len() < 2 || bytes[0] != 0x1f || bytes[1] != 0x8b {
    return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
  }
  std::result::Result::Ok(bytes)
}

/// Reads the revocation bit at `index` from an EXPANDED bitstring
/// (§6.3.3.4 case 3).
///
/// Bit order is the W3C profile's: index 0 is the MOST significant bit of
/// the first byte. Getting this backwards reads a real bit belonging to a
/// different mandate rather than failing, so it is pinned by test.
///
/// # Errors
///
/// `APH_E008` when the list is too short to contain `index`, or larger than
/// [`MAX_EXPANDED_LIST_BYTES`]. §6.3.3.4 case 2 names "its list is too short
/// to contain `statusListIndex`" explicitly: a verifier that read a missing
/// bit as `0` would treat a truncated list as a blanket "nothing is
/// revoked".
///
/// The over-long half of that is a BACKSTOP and nothing more: `expanded_list`
/// is already allocated by the time this function sees it, so the memory
/// bound has to be honoured by the expander ([`ExpandEncodedList`]) and this
/// check only stops an implausible list from being indexed.
pub fn revocation_bit(
  expanded_list: &[u8],
  index: u64,
) -> std::result::Result<bool, crate::errors::AphError> {
  if expanded_list.len() > MAX_EXPANDED_LIST_BYTES {
    return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
  }
  let byte_offset = index / 8;
  // `u64 -> usize` is lossy on a 32-bit target, and a wrapped offset would
  // index the WRONG mandate rather than fail, so the conversion is checked.
  let byte_offset = match usize::try_from(byte_offset) {
    std::result::Result::Ok(offset) => offset,
    std::result::Result::Err(_) => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  let byte = match expanded_list.get(byte_offset) {
    std::option::Option::Some(byte) => *byte,
    std::option::Option::None => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  let bit_in_byte = (index % 8) as u32;
  let mask = 0x80u8 >> bit_in_byte;
  std::result::Result::Ok(byte & mask != 0)
}

/// The two non-refusing outcomes of §6.3.3.4. The third outcome — revoked —
/// is an `APH_E015` error, not a value, because a verifier that could hold
/// "revoked" as a success value could forget to act on it.
#[derive(std::fmt::Debug, std::clone::Clone, std::marker::Copy, std::cmp::PartialEq, std::cmp::Eq)]
pub enum StatusCheck {
  /// §6.3.3.4 case 1 — the envelope carried no `credentialStatus`, so no
  /// claim was offered and none was checked. NOT the same as "not revoked".
  Skipped,
  /// §6.3.3.4 case 3, negative — the bit at `statusListIndex` was `0` **in a
  /// document whose proof this crate did NOT check**.
  ///
  /// ⛔ The qualifier is part of the value, not a footnote, because this is
  /// the exact variant a caller branches on to ADMIT an envelope. §6.3.3.3's
  /// proof check is the only thing standing between "a bit was clear" and
  /// "the notary says this mandate is live": same-origin deliberately permits
  /// a DIFFERENT PATH (§6.3.3.2), so any writable path on the notary's origin
  /// can serve a forged list that satisfies same-origin and writes the
  /// notary's DID into its own `issuer`. Verifying the proof is the caller's
  /// step for the reasons in the module preamble; until it has run,
  /// `NotRevoked` means only that the document the caller was handed said so.
  /// [`check_envelope_status`] carries the obligation in full.
  NotRevoked,
}

/// The GZIP-then-base64url expansion of a status list's `encodedList`,
/// supplied by the caller rather than performed here.
///
/// WHY A CALLER-SUPPLIED CLOSURE AND NOT A DEPENDENCY: this crate has no
/// compression dependency and deliberately keeps none — it is linked into a
/// wasm binding and into a kernel that both pay for every byte. The expansion
/// is a pure `&[u8] -> Vec<u8>` transform with no protocol content, so it
/// belongs to whoever already has an inflate implementation.
///
/// WHY AN ALIAS: the same signature appeared inline in two public functions,
/// which is the duplication `clippy::type_complexity` exists to catch —
/// spelling one contract twice invites the two spellings to drift (§3.4).
///
/// ⛔ THE CALLER'S OBLIGATION — the byte cap lives HERE, not downstream. An
/// implementation of this contract MUST stop and return `APH_E008` as soon
/// as the output it would produce exceeds [`MAX_EXPANDED_LIST_BYTES`],
/// rather than expanding fully and letting a caller measure afterwards. This
/// is the only place the cap can actually bound anything: by the time
/// [`check_credential_status`] holds a `Vec`, the allocation has already
/// happened, so the length check inside [`revocation_bit`] is a backstop
/// against an over-long list and NOT a defence against a decompression bomb.
/// The shape that satisfies this is an inflate reader with a budget on the
/// DECOMPRESSED side (`std::io::Read::take` over the decoder, never over the
/// compressed input, whose length says nothing about the expansion).
///
/// `Send + Sync` for exactly the reason
/// [`crate::discovery::ports::DiscoveryFuture`] carries `+ Send`: adapters
/// run under a host executor that moves tasks between threads and
/// `tokio::spawn` demands it. A bare `dyn Fn` has neither auto trait, and a
/// `&ExpandEncodedList<'_>` without them makes the futures of BOTH public
/// entry points below `!Send` — unspawnable by every real caller, and broken
/// in the host crate far from the line that caused it.
pub type ExpandEncodedList<'a> =
  dyn std::ops::Fn(&[u8]) -> std::result::Result<std::vec::Vec<u8>, crate::errors::AphError>
    + std::marker::Send
    + std::marker::Sync
    + 'a;

/// §8.3 step 8a over a whole envelope: the §6.3.3.4 trichotomy MINUS the
/// §6.3.3.3 proof check, which is the caller's — read the ⛔ below BEFORE
/// wiring this into a verifier.
///
/// Absent ⇒ [`StatusCheck::Skipped`] with no error and no I/O. Present ⇒ the
/// derived endpoint is computed from the envelope's OWN notary DID, the
/// carried `statusListCredential` is bound same-origin against it, the
/// document is fetched, checked as far as a KEYLESS check reaches
/// ([`StatusListCredential::validate`]) and indexed, and a set bit is
/// `APH_E015`. Every case-2 outcome reachable without a key — no derivable
/// origin, an unreachable, oversized or unparseable document, a wrong
/// `issuer`, `statusPurpose`, freshness or index — is `APH_E008`.
///
/// ⛔ THE §6.3.3.3 PROOF CHECK IS NOT PERFORMED HERE. This function never
/// reads `proof`: an entirely UNSIGNED status list whose other members are
/// well formed returns `Ok(StatusCheck::NotRevoked)`, and the test
/// `a_clear_bit_admits_the_envelope` pins exactly that. §6.3.3.4 case 2
/// enumerates "its proof did not verify" among its `APH_E008` outcomes, so
/// **a caller that admits an envelope on this function's `Ok` without
/// verifying that proof has NOT implemented §6.3.3.4 case 2.** The
/// gap is exploitable rather than theoretical: same-origin deliberately
/// permits a DIFFERENT PATH (§6.3.3.2), so any writable path on the notary's
/// origin serves a forged list that satisfies same-origin and writes the
/// notary's DID into its own `issuer`, and only the signature closes it. The
/// module preamble states why the step lives in the caller (it needs a §8.4
/// key resolution and a rotation-aware cache this crate must not hold);
/// [`status_list_signing_base`] yields the exact bytes the signature covers
/// and [`StatusListCredential::proof_verification_method`] the method to
/// resolve, so discharging it is a few lines rather than a re-derivation.
/// Note what this arm hands back: a decision, never the document, so the
/// check cannot be bolted onto this signature after the fact — the caller
/// needs the body in its own hands. Nor may it be hidden inside the
/// fetch adapter: [`crate::discovery::ports::StatusCredentialFetch`]
/// contracts an adapter to form no opinion about which document is
/// authoritative, and a proof check is exactly that opinion.
///
/// `expand_encoded_list` decompresses the GZIP stream — see the module
/// preamble for why the codec is the caller's, and [`ExpandEncodedList`] for
/// the byte cap the caller owes along with it. It is invoked only after
/// every other check has passed.
///
/// # Errors
///
/// `APH_E015` when the parent mandate's bit is set; `APH_E008` for every
/// §6.3.3.4 case-2 outcome this function can detect WITHOUT a key — the
/// proof is NOT among them, per the ⛔ above — including an envelope that
/// carries a status reference but no `delegationMandateId` for it to be the
/// status OF (§6.3.3.1).
pub async fn check_envelope_status(
  envelope: &crate::envelope::NotarizationEnvelope,
  fetch: &dyn crate::discovery::ports::StatusCredentialFetch,
  expand_encoded_list: &ExpandEncodedList<'_>,
  issuer_key: &ed25519_dalek::VerifyingKey,
  now_rfc3339: &str,
) -> std::result::Result<StatusCheck, crate::errors::AphError> {
  let entry = match envelope.credential_status.as_ref() {
    std::option::Option::Some(entry) => entry,
    // §6.3.3.4 case 1. Returning BEFORE touching the port is the whole
    // point: enforcing a claim nobody made is not fail-closed, it is
    // fail-arbitrary, and it would refuse every conformant pre-revision
    // envelope.
    std::option::Option::None => return std::result::Result::Ok(StatusCheck::Skipped),
  };
  let mandate_id = match envelope
    .credential_subject
    .policy
    .delegation_mandate_id
    .as_deref()
  {
    std::option::Option::Some(id) => id,
    // §6.3.3.1: an envelope carrying `credentialStatus` MUST also carry a
    // non-null `delegationMandateId`. The spec routes this to §8.3 step 1 as
    // malformed wire; the §11 taxonomy has no malformed-envelope code, so it
    // lands as case 2 — a status reference with no subject leaves the status
    // unestablished, which is what `APH_E008` says.
    std::option::Option::None => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };
  check_credential_status(
    entry,
    mandate_id,
    envelope
      .credential_subject
      .notarization
      .notary_service
      .id
      .as_str(),
    fetch,
    expand_encoded_list,
    issuer_key,
    now_rfc3339,
  )
  .await
}

/// [`check_envelope_status`] with the three envelope-derived inputs passed
/// explicitly, for a caller that holds them without holding an envelope.
///
/// `notary_service_id` MUST be the notary DID from
/// `credentialSubject.notarization.notaryService.id` (§6.3.3.2 step 1) — the
/// party whose key signed the mandate. Passing anything the envelope's
/// status entry influenced would hand the attacker back the origin choice
/// this whole module exists to take away.
///
/// # Errors
///
/// As [`check_envelope_status`] — INCLUDING its ⛔: the status list's
/// §6.3.3.3 proof is not verified here either, so a caller that admits on
/// this function's `Ok` without checking that proof has not implemented
/// §6.3.3.4 case 2.
pub async fn check_credential_status(
  entry: &CredentialStatusEntry,
  delegation_mandate_id: &str,
  notary_service_id: &str,
  fetch: &dyn crate::discovery::ports::StatusCredentialFetch,
  expand_encoded_list: &ExpandEncodedList<'_>,
  issuer_key: &ed25519_dalek::VerifyingKey,
  now_rfc3339: &str,
) -> std::result::Result<StatusCheck, crate::errors::AphError> {
  // Read the index BEFORE any network work: an unreadable index makes the
  // fetch pointless, and §6.3.3.6's whole argument is that a bad index must
  // never reach a bit lookup.
  let index = entry.index()?;

  // §6.3.3.2 step 1-2. A notary whose id is not a `did:web` derives no
  // origin, so the same-origin rule cannot be satisfied and case 2 applies.
  let derived = match crate::discovery::DidUrl::parse(notary_service_id).web_status_url() {
    std::option::Option::Some(url) => url,
    std::option::Option::None => {
      return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
    }
  };

  // §6.3.3.2 same-origin binding. This runs BEFORE the port is touched and
  // the function returns without touching it — "MUST reject the envelope and
  // MUST NOT fetch the named URL". `same_origin` also refuses a non-`https:`
  // URL, which is the other half of the same sentence.
  if !crate::discovery::same_origin(&derived, &entry.status_list_credential) {
    return std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
  }

  // The bound URL is fetched, not the derived one: §6.3.3.2 permits a
  // DIFFERENT PATH on the same origin, which is how a notary with an
  // exhausted list points at its successor (§6.3.3.6).
  let body = fetch
    .fetch_status_credential(&entry.status_list_credential)
    .await?;
  let credential = parse_status_list_credential(&body)?;
  credential.validate(notary_service_id, now_rfc3339)?;
  // ⛔ §6.3.3.3 — AUTHENTICATE THE DOCUMENT BEFORE BELIEVING ONE BIT OF IT.
  // Everything above proves the bytes came from the right ORIGIN; nothing
  // above proves the right PARTY wrote them. Without this step an attacker
  // who can write to the status endpoint flips a revoked mandate back to
  // live, and the transport built to enforce revocation becomes the way a
  // revoked agent proves it is fine. It runs BEFORE the bit lookup so a
  // forged document can never reach an admit.
  verify_status_list_proof(&body, &credential, issuer_key)?;

  let compressed = decode_encoded_list(&credential.credential_subject.encoded_list)?;
  let expanded = expand_encoded_list(&compressed)?;
  if revocation_bit(&expanded, index)? {
    return std::result::Result::Err(crate::errors::AphError::mandate_revoked(
      delegation_mandate_id,
    ));
  }
  std::result::Result::Ok(StatusCheck::NotRevoked)
}

#[cfg(test)]
mod tests {
  /// The notary every fixture below is issued by, and the origin every
  /// derived endpoint therefore lands on.
  const NOTARY_DID: &str = "did:web:aph-notary.squillo.com";
  /// The derived endpoint for [`NOTARY_DID`] under §6.3.3.2.
  const DERIVED_ENDPOINT: &str =
    "https://aph-notary.squillo.com/.well-known/aph-status.json";
  /// `validFrom` of every fresh fixture, paired with [`NOW`].
  const ISSUED_AT: &str = "2026-05-28T00:00:00Z";
  /// The verification instant: 30 seconds after [`ISSUED_AT`], comfortably
  /// inside the §6.3.3.3 bound.
  const NOW: &str = "2026-05-28T00:00:30Z";

  /// A fetch port double that records every URL it was asked for, so a test
  /// can prove a refusal happened WITHOUT a fetch rather than merely
  /// assert an error code.
  struct RecordingFetch {
    body: String,
    urls: std::sync::Mutex<std::vec::Vec<String>>,
  }

  impl RecordingFetch {
    fn new(body: &str) -> Self {
      Self {
        body: String::from(body),
        urls: std::sync::Mutex::new(std::vec::Vec::new()),
      }
    }

    fn calls(&self) -> usize {
      self.urls.lock().expect("test mutex is uncontended").len()
    }
  }

  impl crate::discovery::ports::StatusCredentialFetch for RecordingFetch {
    fn fetch_status_credential<'a>(
      &'a self,
      url: &'a str,
    ) -> crate::discovery::ports::DiscoveryFuture<'a, String> {
      std::boxed::Box::pin(async move {
        self
          .urls
          .lock()
          .expect("test mutex is uncontended")
          .push(String::from(url));
        let out: std::result::Result<String, crate::errors::AphError> =
          std::result::Result::Ok(self.body.clone());
        out
      })
    }
  }

  /// A port that always fails the way a dead origin does.
  struct UnreachableFetch {
    calls: std::sync::atomic::AtomicUsize,
  }

  impl crate::discovery::ports::StatusCredentialFetch for UnreachableFetch {
    fn fetch_status_credential<'a>(
      &'a self,
      _url: &'a str,
    ) -> crate::discovery::ports::DiscoveryFuture<'a, String> {
      std::boxed::Box::pin(async move {
        self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let out: std::result::Result<String, crate::errors::AphError> =
          std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable);
        out
      })
    }
  }

  /// The stand-in for the caller's GZIP decompressor.
  ///
  /// Tests do not compress anything: they hand the arm a "compressed" buffer
  /// that is a GZIP header followed by the bitstring, and this expander
  /// strips the header. That keeps every assertion about the §6.3.3.4
  /// DECISION rather than about a codec `aph-core` does not link, and it is
  /// exactly the seam a real caller fills with three lines over a gzip
  /// reader.
  fn test_expander(
    compressed: &[u8],
  ) -> std::result::Result<std::vec::Vec<u8>, crate::errors::AphError> {
    // Sliced through `get` rather than `[..]`: a decompressor handed short
    // input must report a failure, never panic a verifier's task.
    match compressed.get(GZIP_HEADER.len()..) {
      std::option::Option::Some(rest) => std::result::Result::Ok(std::vec::Vec::from(rest)),
      std::option::Option::None => {
        std::result::Result::Err(crate::errors::AphError::NotaryServiceUnreachable)
      }
    }
  }

  /// A ten-byte RFC 1952 header: magic, DEFLATE method, no flags, zero
  /// mtime, no extra flags, unknown OS. Enough to satisfy the magic check
  /// [`super::decode_encoded_list`] performs.
  const GZIP_HEADER: [u8; 10] = [0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x00, 0xff];

  /// Builds the multibase `encodedList` value for a bitstring, wrapping it
  /// in the header [`test_expander`] strips back off.
  fn encoded_list_for(bits: &[u8]) -> String {
    let mut bytes = std::vec::Vec::from(GZIP_HEADER);
    bytes.extend_from_slice(bits);
    std::format!(
      "{}{}",
      super::MULTIBASE_BASE64URL_PREFIX,
      crate::crypto::base64url::encode(&bytes)
    )
  }

  /// A status list credential document with the given bitstring.
  /// The obviously-fake seed every fixture signs with, matching the
  /// `[9u8; 32]`-style convention already used in `crypto::eddsa_jcs`.
  /// NEVER a production-shaped key.
  const FIXTURE_SEED: [u8; 32] = [9u8; 32];

  /// The key a fixture is signed with, and therefore the key a passing check
  /// must be given.
  fn fixture_key() -> ed25519_dalek::VerifyingKey {
    ed25519_dalek::SigningKey::from_bytes(&FIXTURE_SEED).verifying_key()
  }

  /// Signs `unsigned_json` the way a notary does and returns the document
  /// WITH its `proof` member.
  ///
  /// WHY THE FIXTURES ARE REALLY SIGNED: the check refuses an unsigned status
  /// list, so a fixture without a proof would make every admit-path test fail
  /// for the wrong reason — and a fixture whose proof were faked past the
  /// verifier would prove nothing at all. Signing over
  /// `status_list_signing_base` is what makes these tests exercise the same
  /// bytes a real issuer commits to.
  fn sign_document(unsigned_json: &str) -> String {
    let base = super::status_list_signing_base(unsigned_json).expect("fixture is a JSON object");
    let sk = ed25519_dalek::SigningKey::from_bytes(&FIXTURE_SEED);
    let signature = ed25519_dalek::Signer::sign(&sk, base.as_bytes());
    let proof_value = crate::crypto::multibase::base58btc_encode(&signature.to_bytes());
    let mut value: serde_json::Value =
      serde_json::from_str(unsigned_json).expect("fixture is valid JSON");
    let object = value.as_object_mut().expect("fixture is a JSON object");
    object.insert(
      String::from("proof"),
      serde_json::json!({
        "type": "DataIntegrityProof",
        "cryptosuite": "eddsa-jcs-2022",
        "proofPurpose": "assertionMethod",
        "verificationMethod": std::format!("{NOTARY_DID}#k1"),
        "proofValue": proof_value,
      }),
    );
    serde_json::to_string(&value).expect("re-serialising a JSON object cannot fail")
  }

  fn status_document(bits: &[u8]) -> String {
    sign_document(&status_document_unsigned(bits))
  }

  /// The document BEFORE its proof is attached — the shape a signer starts
  /// from, and the shape the unsigned-document refusal test needs.
  fn status_document_unsigned(bits: &[u8]) -> String {
    std::format!(
      r#"{{
  "@context": ["https://www.w3.org/ns/credentials/v2"],
  "id": "{endpoint}",
  "type": ["VerifiableCredential", "BitstringStatusListCredential"],
  "issuer": "{issuer}",
  "validFrom": "{issued}",
  "credentialSubject": {{
    "id": "{endpoint}#list",
    "type": "BitstringStatusList",
    "statusPurpose": "revocation",
    "encodedList": "{encoded}"
  }}
}}"#,
      endpoint = DERIVED_ENDPOINT,
      issuer = NOTARY_DID,
      issued = ISSUED_AT,
      encoded = encoded_list_for(bits)
    )
  }

  /// An entry pointing at `url` for bit `index`.
  fn entry_at(url: &str, index: &str) -> super::CredentialStatusEntry {
    super::CredentialStatusEntry {
      id: std::option::Option::None,
      r#type: super::StatusEntryType::BitstringStatusListEntry,
      status_purpose: super::StatusPurpose::Revocation,
      status_list_index: String::from(index),
      status_list_credential: String::from(url),
    }
  }

  #[test]
  fn entry_round_trips_and_omits_an_absent_id() {
    // Pins the wire shape of §6.3.3.1 in both directions. The `id` member is
    // OPTIONAL and Pattern A, so an entry without one must serialize with no
    // `id` key at all — a `null` there would change the JCS bytes of every
    // envelope carrying a status reference.
    let json = r#"{"type":"BitstringStatusListEntry","statusPurpose":"revocation","statusListIndex":"94567","statusListCredential":"https://aph-notary.squillo.com/.well-known/aph-status.json"}"#;
    let entry: super::CredentialStatusEntry =
      serde_json::from_str(json).expect("the §6.3.3.1 shape parses");
    std::assert_eq!(entry.index().unwrap(), 94567u64);
    let back = serde_json::to_string(&entry).expect("entry serializes");
    std::assert_eq!(back, json);
  }

  #[test]
  fn a_numeric_index_is_a_parse_failure() {
    // §6.3.3.6's entire argument: in runtimes where every JSON number is an
    // IEEE-754 double an index past 2^53 rounds SILENTLY and reads a
    // different mandate's bit. Typing the field `String` must make the
    // numeric form unparseable rather than merely discouraged.
    let json = r#"{"type":"BitstringStatusListEntry","statusPurpose":"revocation","statusListIndex":94567,"statusListCredential":"https://aph-notary.squillo.com/.well-known/aph-status.json"}"#;
    let parsed = serde_json::from_str::<super::CredentialStatusEntry>(json);
    std::assert!(parsed.is_err(), "a JSON number at statusListIndex must not parse");
  }

  #[test]
  fn an_unrecognized_purpose_is_a_parse_failure_not_a_skip() {
    // §6.3.3.5: a verifier that treated an unknown purpose as "no status
    // claim was made" would let any producer disable the check by writing a
    // word that verifier has never seen. The closed enum makes that opt-out
    // unconstructible — the envelope does not parse at all.
    let json = r#"{"type":"BitstringStatusListEntry","statusPurpose":"suspension","statusListIndex":"1","statusListCredential":"https://aph-notary.squillo.com/.well-known/aph-status.json"}"#;
    std::assert!(serde_json::from_str::<super::CredentialStatusEntry>(json).is_err());
    let wrong_type = r#"{"type":"StatusList2021Entry","statusPurpose":"revocation","statusListIndex":"1","statusListCredential":"https://aph-notary.squillo.com/.well-known/aph-status.json"}"#;
    // §14.1 pins ONE vintage: an entry from a different vintage of the same
    // idea must not be read as though it were this one.
    std::assert!(serde_json::from_str::<super::CredentialStatusEntry>(wrong_type).is_err());
  }

  #[test]
  fn entry_rejects_an_unknown_member() {
    // The entry travels inside the signed envelope, which parses strictly
    // (§7.1). A member APH never defined must be a hard error here too, or
    // the strictness stops at the envelope's edge.
    let json = r#"{"type":"BitstringStatusListEntry","statusPurpose":"revocation","statusListIndex":"1","statusListCredential":"https://aph-notary.squillo.com/.well-known/aph-status.json","statusSize":2}"#;
    std::assert!(serde_json::from_str::<super::CredentialStatusEntry>(json).is_err());
  }

  #[test]
  fn index_refuses_signs_and_whitespace() {
    // `u64::from_str` accepts a leading `+`, and a permissive index parse is
    // how "+1" and "1" become two spellings of one bit — a producer could
    // then write an index one verifier reads and another refuses.
    let mut entry = entry_at(DERIVED_ENDPOINT, "+1");
    std::assert!(entry.index().is_err());
    entry.status_list_index = String::from(" 1");
    std::assert!(entry.index().is_err());
    entry.status_list_index = String::from("");
    std::assert!(entry.index().is_err());
    entry.status_list_index = String::from("1_000");
    std::assert!(entry.index().is_err());
  }

  #[test]
  fn revocation_bit_reads_the_most_significant_bit_first() {
    // W3C bit order: index 0 is the MSB of byte 0. Reversing it does not
    // fail, it reads a real bit belonging to a DIFFERENT mandate — a wrong
    // answer delivered with full confidence — so the order is pinned here
    // rather than trusted to the reader.
    let list: [u8; 2] = [0b1000_0001, 0b0000_0010];
    std::assert!(super::revocation_bit(&list, 0).unwrap());
    std::assert!(!super::revocation_bit(&list, 1).unwrap());
    std::assert!(super::revocation_bit(&list, 7).unwrap());
    std::assert!(super::revocation_bit(&list, 14).unwrap());
    std::assert!(!super::revocation_bit(&list, 15).unwrap());
  }

  #[test]
  fn an_index_past_the_list_is_a_refusal_not_a_zero() {
    // §6.3.3.4 case 2 names a too-short list explicitly. Reading a missing
    // bit as `0` would turn a truncated (or maliciously trimmed) list into a
    // blanket "nothing is revoked".
    let list: [u8; 1] = [0x00];
    std::assert_eq!(super::revocation_bit(&list, 8).unwrap_err().code(), "APH_E008");
  }

  #[test]
  fn encoded_list_requires_the_multibase_prefix_and_gzip_magic() {
    // §14.1 pins W3C Bitstring Status List v1.0, whose `encodedList` is
    // multibase. The predecessor vintage wrote bare base64url at the same
    // position, so accepting a missing prefix would mean silently reading a
    // different specification's document and calling it conformant.
    let bare = crate::crypto::base64url::encode(&[0x1f, 0x8b, 0x08]);
    std::assert_eq!(
      super::decode_encoded_list(&bare).unwrap_err().code(),
      "APH_E008"
    );
    // Non-GZIP bytes are refused BEFORE a caller's decompressor sees them.
    let not_gzip = std::format!(
      "{}{}",
      super::MULTIBASE_BASE64URL_PREFIX,
      crate::crypto::base64url::encode(b"plain")
    );
    std::assert_eq!(
      super::decode_encoded_list(&not_gzip).unwrap_err().code(),
      "APH_E008"
    );
    let good = encoded_list_for(&[0x00]);
    std::assert_eq!(super::decode_encoded_list(&good).unwrap()[0], 0x1f);
  }

  #[test]
  fn freshness_bound_is_five_minutes_plus_one_minute_of_skew() {
    // §6.3.3.3 is normative about both numbers and they are the reason the
    // check is worth a network round trip at all: a bound measured in hours
    // would cost a fetch and buy nothing, because the mandate would usually
    // expire before a stale answer changed.
    let document = status_document(&[0x00]);
    let credential = super::parse_status_list_credential(&document).unwrap();
    // 359s old: inside 300 + 60.
    std::assert!(credential.check_freshness("2026-05-28T00:05:59Z").is_ok());
    // 361s old: outside.
    std::assert_eq!(
      credential
        .check_freshness("2026-05-28T00:06:01Z")
        .unwrap_err()
        .code(),
      "APH_E008"
    );
    // Dated further into the future than the skew allowance: refused, or a
    // publisher buys unbounded staleness by writing tomorrow's date.
    std::assert_eq!(
      credential
        .check_freshness("2026-05-27T23:58:00Z")
        .unwrap_err()
        .code(),
      "APH_E008"
    );
  }

  #[test]
  fn the_republish_deadline_falls_due_long_before_the_refusal_cliff() {
    // WHY THIS TEST EXISTS: a publisher that quietly stops fails closed, which
    // is the correct direction and a silent arrival — the first symptom is a
    // stranger's verifier refusing an envelope. These two distances are the
    // earlier warning, and they are only worth exposing if the alarm line
    // genuinely precedes the cliff by a usable margin.
    //
    // WHAT IT PINS: the §6.3.3.3 producer interval and the §6.3.3.3 freshness
    // bound as measured from one issuance instant; that the producer is
    // already late while verifiers still accept; that both distances agree
    // with `check_freshness` on either side of the cliff; that they go
    // NEGATIVE rather than erroring once passed, because a monitor needs "how
    // late am I" and not only "too late"; and that an unreadable clock
    // refuses instead of reporting a distance a dashboard would render as
    // time remaining.
    let document = status_document(&[0x00]);
    let credential = super::parse_status_list_credential(&document).unwrap();

    // 30s after issuance: 90s of republish budget, 330s before refusal.
    std::assert_eq!(credential.seconds_until_republish_due(NOW).unwrap(), 90);
    std::assert_eq!(credential.seconds_until_stale(NOW).unwrap(), 330);

    // Past the producer's line and still accepted. That gap is the mitigation.
    std::assert_eq!(
      credential
        .seconds_until_republish_due("2026-05-28T00:03:00Z")
        .unwrap(),
      -60
    );
    std::assert!(credential.check_freshness("2026-05-28T00:03:00Z").is_ok());

    // The cliff and the verdict agree on both sides of it.
    std::assert_eq!(
      credential.seconds_until_stale("2026-05-28T00:05:59Z").unwrap(),
      1
    );
    std::assert!(credential.check_freshness("2026-05-28T00:05:59Z").is_ok());
    std::assert_eq!(
      credential.seconds_until_stale("2026-05-28T00:06:01Z").unwrap(),
      -1
    );
    std::assert!(credential.check_freshness("2026-05-28T00:06:01Z").is_err());

    std::assert_eq!(
      credential
        .seconds_until_stale("not-a-timestamp")
        .unwrap_err()
        .code(),
      "APH_E008"
    );
    std::assert_eq!(
      credential
        .seconds_until_republish_due("not-a-timestamp")
        .unwrap_err()
        .code(),
      "APH_E008"
    );
  }

  #[test]
  fn validate_binds_the_issuer_to_the_derived_notary() {
    // Same-origin alone does not make a document authoritative: one host
    // serves many documents, and the path is the envelope's to name. The
    // issuer binding is what ties the answer to the party whose key signed
    // the mandate.
    let document = status_document(&[0x00]).replace(NOTARY_DID, "did:web:evil.example");
    let credential = super::parse_status_list_credential(&document).unwrap();
    std::assert_eq!(
      credential.validate(NOTARY_DID, NOW).unwrap_err().code(),
      "APH_E008"
    );
  }

  #[test]
  fn validate_refuses_a_document_whose_purpose_is_not_revocation() {
    // On the fetched DOCUMENT an unrecognized purpose is §6.3.3.4 case 2
    // (APH_E008), not the parse failure the ENVELOPE entry raises. The
    // asymmetry is the spec's and is easy to collapse by accident, so both
    // halves are pinned.
    // The UNSIGNED builder on purpose: `validate` is the keyless half of
    // §6.3.3.3 and never looks at a proof, so signing here would add nothing
    // — and the signed builder re-serialises compactly, which would silently
    // turn the string replace below into a no-op and make this test pass
    // while asserting nothing.
    let document = status_document_unsigned(&[0x00]).replace(
      "\"statusPurpose\": \"revocation\"",
      "\"statusPurpose\": \"suspension\"",
    );
    let credential = super::parse_status_list_credential(&document).unwrap();
    std::assert_eq!(
      credential.validate(NOTARY_DID, NOW).unwrap_err().code(),
      "APH_E008"
    );
  }

  #[test]
  fn a_status_document_may_carry_members_aph_does_not_read() {
    // The status list credential is a general W3C artifact. Parsing it
    // strictly would refuse ordinary documents carrying `name`, `ttl` or a
    // `validUntil` — the same reason `DidDocument` is not strict either.
    let document = status_document(&[0x00]).replace(
      "\"validFrom\":",
      "\"name\": \"Squillo revocation list\", \"ttl\": 300, \"validFrom\":",
    );
    let credential = super::parse_status_list_credential(&document)
      .expect("extra W3C members must not refuse the document");
    std::assert!(credential.validate(NOTARY_DID, NOW).is_ok());
  }

  #[test]
  fn issuer_is_read_from_a_string_or_an_object() {
    // W3C permits both forms and notaries emit both; a verifier that read
    // only one would refuse conformant issuers for a JSON-shape reason.
    let document = status_document(&[0x00]).replace(
      &std::format!("\"issuer\": \"{}\"", NOTARY_DID),
      &std::format!("\"issuer\": {{\"id\": \"{}\"}}", NOTARY_DID),
    );
    let credential = super::parse_status_list_credential(&document).unwrap();
    std::assert_eq!(credential.issuer_did(), std::option::Option::Some(NOTARY_DID));
    std::assert!(credential.validate(NOTARY_DID, NOW).is_ok());
  }

  #[test]
  fn signing_base_drops_the_proof_and_is_stable() {
    // The caller verifies the notary's signature over exactly these bytes
    // (module preamble). Shipping the base here is what keeps the host from
    // re-deriving it and drifting from the signer.
    let signed = status_document(&[0x00]).replace(
      "\n}",
      ",\n  \"proof\": {\"type\": \"DataIntegrityProof\", \"proofValue\": \"zNotChecked\"}\n}",
    );
    let base = super::status_list_signing_base(&signed).unwrap();
    std::assert!(!base.contains("proofValue"));
    // Byte-identical to the base of the same document with no proof at all,
    // which is the property a signer relies on.
    let unsigned = super::status_list_signing_base(&status_document(&[0x00])).unwrap();
    std::assert_eq!(base, unsigned);
  }

  // ── The §6.3.3.4 trichotomy, minus the caller's proof check ─────────

  /// An envelope whose notary is [`NOTARY_DID`], carrying `status` and
  /// naming `mandate` as the parent Delegation Mandate.
  ///
  /// Built from the checked-in Slack golden so the trichotomy is exercised
  /// against a real published wire sample rather than a shape invented for
  /// this test — the golden is also what proves, in
  /// `golden_envelope_bytes_are_unchanged_by_the_new_field`, that an absent
  /// status reference changes nothing.
  fn envelope_with(
    status: std::option::Option<super::CredentialStatusEntry>,
    mandate: std::option::Option<&str>,
  ) -> crate::envelope::NotarizationEnvelope {
    let raw = std::include_str!("../tests/golden/slack_reply_envelope.json");
    let mut envelope: crate::envelope::NotarizationEnvelope =
      serde_json::from_str(raw).expect("golden fixture parses");
    envelope.credential_subject.notarization.notary_service.id = String::from(NOTARY_DID);
    envelope.credential_subject.policy.delegation_mandate_id =
      mandate.map(String::from);
    envelope.credential_status = status;
    envelope
  }

  /// The mandate id every revoked-path assertion expects back in `APH_E015`.
  const MANDATE_ID: &str = "urn:uuid:00000000-0000-4000-8000-0000000000d1";

  #[test]
  fn absent_status_skips_without_error_and_without_touching_the_port() {
    // §6.3.3.4 case 1. Enforcing a claim nobody made is not fail-closed, it
    // is fail-arbitrary: it would refuse every conformant envelope written
    // before this revision. The port call count is the load-bearing
    // assertion — "skip" must mean no I/O at all, not a fetch whose result
    // is discarded.
    let fetch = RecordingFetch::new("");
    let envelope = envelope_with(std::option::Option::None, std::option::Option::Some(MANDATE_ID));
    let outcome = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect("an absent status reference is not an error");
    std::assert_eq!(outcome, super::StatusCheck::Skipped);
    std::assert_eq!(fetch.calls(), 0, "case 1 must perform no fetch");
  }

  #[test]
  fn a_clear_bit_admits_the_envelope() {
    // §6.3.3.4 case 3, negative. The positive control for every refusal
    // below: without it a test suite where everything rejects would pass
    // even if the arm refused unconditionally.
    //
    // ⛔ THE GAP THIS COMMENT USED TO PIN IS CLOSED, and it closed exactly the
    // way the old text predicted it would have to. It read: "if this crate
    // ever starts verifying proofs, THIS TEST MUST FAIL, and the fix is to
    // give the fixture a real signature, never to relax the assertion." It
    // did fail, and the fixture now carries a REAL signature over
    // `status_list_signing_base` (see `sign_document`), verified against the
    // key this call supplies. The earlier design left §6.3.3.3's proof check
    // to the caller on the reasoning that a §8.4-resolved key does not belong
    // in this crate; the key is now an ARGUMENT, which keeps that reasoning
    // (the crate still resolves nothing) while making the check unskippable.
    // A caller cannot obtain a verdict without handing over the key that
    // authenticates it.
    let fetch = RecordingFetch::new(&status_document(&[0b0100_0000]));
    let entry = entry_at(DERIVED_ENDPOINT, "0");
    let envelope = envelope_with(
      std::option::Option::Some(entry),
      std::option::Option::Some(MANDATE_ID),
    );
    let outcome = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect("a clear bit continues verification");
    std::assert_eq!(outcome, super::StatusCheck::NotRevoked);
    std::assert_eq!(fetch.calls(), 1);
  }

  /// WHY THIS TEST EXISTS: same-origin proves the bytes came from the right
  /// ORIGIN; it says nothing about which PARTY wrote them. Without a proof
  /// check, anyone able to write to (or answer for) the status endpoint could
  /// flip a revoked mandate back to live — turning the transport built to
  /// ENFORCE revocation into the way a revoked agent proves it is fine. This
  /// crate shipped with exactly that hole for one commit.
  /// WHAT IT PINS: an UNSIGNED status list is §6.3.3.4 case 2 — refused, never
  /// admitted as "nothing to check" — even when its bit is clear and every
  /// other check passes.
  #[test]
  fn an_unsigned_status_list_is_refused_even_when_the_bit_is_clear() {
    let fetch = RecordingFetch::new(&status_document_unsigned(&[0b0100_0000]));
    let entry = entry_at(DERIVED_ENDPOINT, "0");
    let envelope = envelope_with(
      std::option::Option::Some(entry),
      std::option::Option::Some(MANDATE_ID),
    );
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect_err("an unsigned status list must never be admitted");
    std::assert!(std::matches!(
      error,
      crate::errors::AphError::NotaryServiceUnreachable
    ));
  }

  /// WHY THIS TEST EXISTS: a signature that verifies under the WRONG key is
  /// the forgery case — an attacker signs a document with their own key and
  /// serves it from a host that satisfies same-origin.
  /// WHAT IT PINS: a well-formed proof made by a key other than the issuer's
  /// is refused.
  #[test]
  fn a_status_list_signed_by_the_wrong_key_is_refused() {
    let fetch = RecordingFetch::new(&status_document(&[0b0100_0000]));
    let entry = entry_at(DERIVED_ENDPOINT, "0");
    let envelope = envelope_with(
      std::option::Option::Some(entry),
      std::option::Option::Some(MANDATE_ID),
    );
    // A different obviously-fake seed: the impostor convention already used
    // in `crypto::eddsa_jcs`.
    let impostor = ed25519_dalek::SigningKey::from_bytes(&[13u8; 32]).verifying_key();
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &impostor,
      NOW,
    ))
    .expect_err("a status list signed by a foreign key must be refused");
    std::assert!(std::matches!(
      error,
      crate::errors::AphError::NotaryServiceUnreachable
    ));
  }

  #[test]
  fn a_set_bit_rejects_with_aph_e015_naming_the_mandate() {
    // §6.3.3.4 case 3. The code matters as much as the refusal: E015 says a
    // human WITHDREW the authority, while a signature code would send an
    // operator to inspect key material for a decision no key was involved
    // in. The mandate id has to travel with it or the operator cannot tell
    // WHICH grant was pulled.
    let fetch = RecordingFetch::new(&status_document(&[0b0010_0000]));
    let entry = entry_at(DERIVED_ENDPOINT, "2");
    let envelope = envelope_with(
      std::option::Option::Some(entry),
      std::option::Option::Some(MANDATE_ID),
    );
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect_err("a set bit must refuse the envelope");
    std::assert_eq!(error.code(), "APH_E015");
    std::assert!(
      std::format!("{}", error).contains(MANDATE_ID),
      "APH_E015 must name the revoked mandate"
    );
  }

  #[test]
  fn an_unreachable_status_surface_rejects_rather_than_skipping() {
    // §6.3.3.4 case 2, and the reason it is not case 1: an attacker who can
    // make the status check FAIL must not thereby get to choose that it is
    // SKIPPED. This is §8.4.6's published-and-failed rule one level up.
    let fetch = UnreachableFetch {
      calls: std::sync::atomic::AtomicUsize::new(0),
    };
    let entry = entry_at(DERIVED_ENDPOINT, "0");
    let envelope = envelope_with(
      std::option::Option::Some(entry),
      std::option::Option::Some(MANDATE_ID),
    );
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect_err("an offered-but-unreachable reference must refuse");
    std::assert_eq!(error.code(), "APH_E008");
    std::assert_eq!(
      fetch.calls.load(std::sync::atomic::Ordering::SeqCst),
      1,
      "the derived origin was reached for, and it is the reach that failed"
    );
  }

  #[test]
  fn a_cross_origin_status_url_is_refused_without_being_fetched() {
    // THE security core of §6.3.3.2. The authority for "is this mandate
    // revoked" is the notary that issued it; if the envelope could name the
    // host answering, then whoever holds an old envelope also chooses that
    // host — and a host of the attacker's choosing always answers "not
    // revoked". The spec says MUST reject and MUST NOT fetch, so the CALL
    // COUNT is the assertion. An error code alone would still pass if the
    // implementation fetched first and refused afterwards, by which time the
    // verifier has already made a request an attacker steered.
    let fetch = RecordingFetch::new(&status_document(&[0x00]));
    let entry = entry_at("https://evil.example/.well-known/aph-status.json", "0");
    let envelope = envelope_with(
      std::option::Option::Some(entry),
      std::option::Option::Some(MANDATE_ID),
    );
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect_err("a cross-origin status URL must refuse");
    std::assert_eq!(error.code(), "APH_E008");
    std::assert_eq!(fetch.calls(), 0, "the named URL must never be fetched");
  }

  #[test]
  fn a_same_host_different_port_or_scheme_is_also_cross_origin() {
    // "Same-origin" is scheme + host + PORT, and a verifier that compared
    // only the host would accept `http://` (no TLS anchor at all) and a
    // service on another port that the notary's certificate never covered.
    // Both must refuse unfetched, exactly like a foreign host.
    for url in [
      "http://aph-notary.squillo.com/.well-known/aph-status.json",
      "https://aph-notary.squillo.com:8443/.well-known/aph-status.json",
      // Userinfo is the classic disguise: the HOST here is `evil.example`,
      // and a prefix comparison would call it the notary's own origin.
      "https://aph-notary.squillo.com@evil.example/.well-known/aph-status.json",
    ] {
      let fetch = RecordingFetch::new(&status_document(&[0x00]));
      let envelope = envelope_with(
        std::option::Option::Some(entry_at(url, "0")),
        std::option::Option::Some(MANDATE_ID),
      );
      let error = crate::discovery::test_support::block_on(super::check_envelope_status(
        &envelope,
        &fetch,
        &test_expander,
        &fixture_key(),
        NOW,
      ))
      .expect_err(url);
      std::assert_eq!(error.code(), "APH_E008", "{}", url);
      std::assert_eq!(fetch.calls(), 0, "{}", url);
    }
  }

  #[test]
  fn a_different_path_on_the_derived_origin_is_admitted_and_is_what_gets_fetched() {
    // §6.3.3.2 permits a different PATH deliberately — it is how a notary
    // whose list is exhausted points at the successor list (§6.3.3.6). A
    // verifier that pinned the whole URL instead of the origin would refuse
    // every notary that ever filled a list.
    let fetch = RecordingFetch::new(&status_document(&[0x00]));
    let second_list = "https://aph-notary.squillo.com/status/list-2.json";
    let envelope = envelope_with(
      std::option::Option::Some(entry_at(second_list, "0")),
      std::option::Option::Some(MANDATE_ID),
    );
    let outcome = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect("a same-origin second list is legitimate");
    std::assert_eq!(outcome, super::StatusCheck::NotRevoked);
    let asked = fetch.urls.lock().expect("test mutex is uncontended").clone();
    std::assert_eq!(
      asked,
      std::vec![String::from(second_list)],
      "the BOUND url is fetched, not the derived one"
    );
  }

  #[test]
  fn a_notary_that_is_not_did_web_cannot_be_status_checked() {
    // §6.3.3.4 case 2, first bullet: with no `did:web` there is no origin to
    // derive, so the same-origin rule cannot be satisfied at all. Refusing
    // is the only safe reading — treating it as case 1 would let any
    // producer disable the check by issuing under a `did:key` notary.
    let fetch = RecordingFetch::new(&status_document(&[0x00]));
    let mut envelope = envelope_with(
      std::option::Option::Some(entry_at(DERIVED_ENDPOINT, "0")),
      std::option::Option::Some(MANDATE_ID),
    );
    envelope.credential_subject.notarization.notary_service.id =
      String::from("did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSdoVTwBaPaeT1KhFmkV");
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect_err("no derivable origin must refuse");
    std::assert_eq!(error.code(), "APH_E008");
    std::assert_eq!(fetch.calls(), 0);
  }

  #[test]
  fn a_status_reference_with_no_parent_mandate_is_refused() {
    // §6.3.3.1: an envelope carrying `credentialStatus` MUST also carry a
    // non-null `delegationMandateId`. A status reference with nothing to be
    // the status OF would leave a verifier checking a bit whose subject it
    // cannot name — and `APH_E015` could not name the mandate it refused.
    let fetch = RecordingFetch::new(&status_document(&[0x00]));
    let envelope = envelope_with(
      std::option::Option::Some(entry_at(DERIVED_ENDPOINT, "0")),
      std::option::Option::None,
    );
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      NOW,
    ))
    .expect_err("a subjectless status reference must refuse");
    std::assert_eq!(error.code(), "APH_E008");
    std::assert_eq!(fetch.calls(), 0);
  }

  #[test]
  fn a_stale_document_rejects_even_though_it_fetched_cleanly() {
    // §6.3.3.3's bound is what makes the check worth its round trip. A
    // verifier that fetched successfully and then ignored the age would
    // accept a list frozen at the moment before a revocation.
    let fetch = RecordingFetch::new(&status_document(&[0x00]));
    let envelope = envelope_with(
      std::option::Option::Some(entry_at(DERIVED_ENDPOINT, "0")),
      std::option::Option::Some(MANDATE_ID),
    );
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &test_expander,
      &fixture_key(),
      // 361 seconds after ISSUED_AT: past 300 + 60.
      "2026-05-28T00:06:01Z",
    ))
    .expect_err("a stale status list must refuse");
    std::assert_eq!(error.code(), "APH_E008");
    std::assert_eq!(fetch.calls(), 1);
  }

  #[test]
  fn the_expander_never_runs_on_a_document_that_failed_an_earlier_check() {
    // The decompressor is caller-supplied and runs over network bytes, so
    // the order of operations is a security property: same-origin, issuer,
    // purpose and freshness all pass FIRST, and only then is a codec asked
    // to expand anything. This test would fail if the arm expanded before
    // validating.
    let expanded = std::sync::atomic::AtomicUsize::new(0);
    let counting = |compressed: &[u8]| -> std::result::Result<
      std::vec::Vec<u8>,
      crate::errors::AphError,
    > {
      expanded.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
      test_expander(compressed)
    };
    let fetch = RecordingFetch::new(
      &status_document(&[0x00]).replace(NOTARY_DID, "did:web:evil.example"),
    );
    let envelope = envelope_with(
      std::option::Option::Some(entry_at(DERIVED_ENDPOINT, "0")),
      std::option::Option::Some(MANDATE_ID),
    );
    let error = crate::discovery::test_support::block_on(super::check_envelope_status(
      &envelope,
      &fetch,
      &counting,
      &fixture_key(),
      NOW,
    ))
    .expect_err("a foreign issuer must refuse");
    std::assert_eq!(error.code(), "APH_E008");
    std::assert_eq!(
      expanded.load(std::sync::atomic::Ordering::SeqCst),
      0,
      "the caller's decompressor must not see bytes from a rejected document"
    );
  }

  #[test]
  fn golden_envelope_bytes_are_unchanged_by_the_new_field() {
    // ⛔ PATTERN A, the rule that keeps every fixture and all four real
    // Ed25519 signatures valid without regeneration (§7.1.1, §7.5): an
    // envelope carrying NO status reference must be BYTE-IDENTICAL to one
    // written before the field existed. `#[serde(default)]` alone would emit
    // an explicit `null`, changing the JCS bytes of every golden and
    // invalidating every signature over them. This test reads the
    // checked-in golden, round-trips it through the type that now has the
    // field, and compares the SIGNING BASE — the exact bytes a proof
    // covers — so a regression is caught as the signature breakage it is.
    let raw = std::include_str!("../tests/golden/slack_reply_envelope.json");
    let envelope: crate::envelope::NotarizationEnvelope =
      serde_json::from_str(raw).expect("golden fixture parses");
    std::assert!(
      envelope.credential_status.is_none(),
      "the golden predates the field and must parse with it absent"
    );
    let reserialized = serde_json::to_string(&envelope).expect("envelope serializes");
    std::assert!(
      !reserialized.contains("credentialStatus"),
      "an absent status reference must emit no key at all"
    );
    let from_type: serde_json::Value =
      serde_json::from_str(&reserialized).expect("round-trip parses");
    let from_disk: serde_json::Value = serde_json::from_str(raw).expect("golden parses as JSON");
    std::assert_eq!(
      crate::crypto::jcs::canonicalize_rfc8785(&from_type),
      crate::crypto::jcs::canonicalize_rfc8785(&from_disk),
      "the canonical bytes a signature covers must be unchanged"
    );
  }

  #[test]
  fn proof_verification_method_is_surfaced_for_the_caller() {
    // The accessor still matters after the crate started checking proofs
    // itself: a caller that resolves the key, or an operator diagnosing a
    // refusal, needs to know WHICH key the document claims to be signed by.
    // Both halves now come from the real builders rather than string surgery
    // — `status_document` signs, `status_document_unsigned` does not — so the
    // fixtures cannot drift from what the signer actually emits.
    let credential = super::parse_status_list_credential(&status_document(&[0x00])).unwrap();
    std::assert_eq!(
      credential.proof_verification_method(),
      std::option::Option::Some("did:web:aph-notary.squillo.com#k1")
    );
    let unsigned =
      super::parse_status_list_credential(&status_document_unsigned(&[0x00])).unwrap();
    std::assert_eq!(
      unsigned.proof_verification_method(),
      std::option::Option::None
    );
  }

  #[test]
  fn both_entry_points_return_futures_that_can_cross_a_thread_boundary() {
    // WHY THIS EXISTS: every real caller drives this arm from a host
    // executor — the squillo verifier calls it inside an actor's inbound
    // handler — and `tokio::spawn` demands a `Send` future. Nothing else in
    // this file would notice if that stopped holding, because
    // `test_support::block_on` polls on the calling thread: the whole suite
    // would stay green while no host could compile against the crate.
    //
    // WHAT IT PINS: the `+ Send + Sync` on `super::ExpandEncodedList`.
    // `&dyn StatusCredentialFetch` is already `Send` via that trait's
    // supertraits and the envelope is plain data, so the caller-supplied
    // expander is the ONE capture that can poison the auto trait — a bare
    // `dyn Fn` carries neither. Moving both futures into a scoped thread is
    // the runtime form of the bound, the same shape
    // `discovery::ports::port_futures_can_cross_a_thread_boundary` uses for
    // `DiscoveryFuture`. Awaiting them there rather than merely dropping
    // them also pins that the OUTPUT is `Send`, which is what a spawned task
    // must return.
    let fetch = RecordingFetch::new(&status_document(&[0b0100_0000]));
    let entry = entry_at(DERIVED_ENDPOINT, "0");
    let envelope = envelope_with(
      std::option::Option::Some(entry.clone()),
      std::option::Option::Some(MANDATE_ID),
    );
    // Annotated with the alias rather than inferred: the coercion IS the
    // assertion, so the bound has to be named at the coercion site. Bound to
    // a `let` for a second reason — an inline `&test_expander` would be a
    // temporary dropped at the end of its own statement, and these futures
    // outlive their statement.
    let expander: &super::ExpandEncodedList<'_> = &test_expander;
    let key = fixture_key();
    let envelope_future = super::check_envelope_status(&envelope, &fetch, expander, &key, NOW);
    let direct_future =
      super::check_credential_status(&entry, MANDATE_ID, NOTARY_DID, &fetch, expander, &key, NOW);
    let outcomes = std::thread::scope(|scope| {
      scope
        .spawn(move || {
          (
            crate::discovery::test_support::block_on(envelope_future),
            crate::discovery::test_support::block_on(direct_future),
          )
        })
        .join()
    })
    .expect("the moved futures must complete on the other thread");
    std::assert_eq!(
      outcomes.0.expect("a clear bit admits the envelope"),
      super::StatusCheck::NotRevoked
    );
    std::assert_eq!(
      outcomes.1.expect("a clear bit admits the entry"),
      super::StatusCheck::NotRevoked
    );
  }
}