vta-service 0.8.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
// Each handler's `Result<…, Response>` Err variant is the boxed-axum
// `Response` (~128 bytes). Boxing the entire Result would buy nothing —
// the Response is owned-and-emitted on the same stack frame — so allow
// the lint at the slice level rather than per-fn.
#![allow(clippy::result_large_err)]

//! Vault slice trust-task handlers — M1 + M2A + M2B surface.
//!
//! Handles `spec/vault/{list,get,upsert,delete,release,proxy-login}/0.1`
//! per the canonical
//! [trust-tasks-tf](https://github.com/trustoverip/dtgwg-trust-tasks-tf) specs.
//! `proxy-login`'s DID-self-issued (SIOP) driver lands in M2B.2b; the
//! Password POST driver follows in M2B.5.
//!
//! Auth: gated on derived capabilities for the caller's role —
//! [`vti_common::acl::derived_capabilities_for_role`]. List/get require
//! `VaultRead`; upsert/delete require `VaultWrite`; release requires
//! `FillRelease`; proxy-login requires `ProxyLogin`. Admin/Initiator
//! carry the write capabilities; Application/Reader carry read-only;
//! Monitor carries none.

use affinidi_messaging_didcomm::Message;
use axum::response::Response;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use trust_tasks_rs::TrustTask;
use uuid::Uuid;
use vti_common::acl::{Capability, role_has_capability};
use vti_common::vault::{
    RequestHeader, SecretKind, SessionBlob, SiteTarget, StoredVaultEntry, VaultEntry,
    VaultListFilter, VaultSecret, delete_vault_entry, get_stored_vault_entry, get_vault_entry,
    list_vault_entries as list_entries_store, put_stored_vault_entry,
};

use crate::auth::AuthClaims;
use crate::error::AppError;
use crate::server::AppState;

use super::helpers::{app_error_to_reject, parse_payload, reject_with, success_response};
use trust_tasks_rs::RejectReason;

/// URIs handled by this slice. Aggregated by the dispatcher's parity
/// harness.
#[allow(dead_code)]
pub(super) const DISPATCHED_URIS: &[&str] = &[
    vta_sdk::trust_tasks::TASK_VAULT_LIST_0_1,
    vta_sdk::trust_tasks::TASK_VAULT_GET_0_1,
    vta_sdk::trust_tasks::TASK_VAULT_UPSERT_0_1,
    vta_sdk::trust_tasks::TASK_VAULT_DELETE_0_1,
    vta_sdk::trust_tasks::TASK_VAULT_RELEASE_0_1,
    vta_sdk::trust_tasks::TASK_VAULT_PROXY_LOGIN_0_1,
    vta_sdk::trust_tasks::TASK_VAULT_SIGN_TRUST_TASK_0_1,
];

/// Request body for `vault/list/0.1`. Mirrors the canonical
/// `payload.schema.json` of the spec; field names are camelCase to match
/// the wire form Companions emit from `@openvtc/trust-tasks`.
///
/// Pagination is accepted but currently single-page — the maintainer
/// returns up to `page_size` entries with `truncated: false` and no cursor.
/// Real cursor-based pagination lands when the vault grows past a few
/// thousand entries; for M1 with hand-seeded test data it's overkill.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VaultListBody {
    context_id: Option<String>,
    target_origin_prefix: Option<String>,
    target_did: Option<String>,
    target_ios_bundle_id: Option<String>,
    target_android_package: Option<String>,
    secret_kind: Option<SecretKind>,
    tag: Option<String>,
    used_since: Option<String>,
    never_used: Option<bool>,
    expires_before: Option<String>,
    breached: Option<bool>,
    page_size: Option<u32>,
    // `cursor` accepted on the wire for forward-compat but ignored in M1.
    #[serde(default)]
    #[allow(dead_code)]
    cursor: Option<String>,
}

/// Response body for `vault/list/0.1`. Wraps the entries the
/// canonical schema declares under `$defs.Response`.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct VaultListResponseBody {
    entries: Vec<VaultEntry>,
    truncated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    cursor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    redacted_fields: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VaultGetBody {
    id: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct VaultGetResponseBody {
    entry: VaultEntry,
    #[serde(skip_serializing_if = "Option::is_none")]
    redacted_fields: Option<Vec<String>>,
}

/// Request body for `vault/upsert/0.1`. Mirrors the canonical
/// `payload.schema.json`; field names are camelCase per the wire spec.
///
/// Notes on semantics:
/// - `id` omitted → create with a maintainer-assigned ULID. Provided →
///   update (`expectedVersion` MUST match) or upsert-with-id when the row
///   doesn't yet exist (recommended for client-generated ids).
/// - `sealedSecret` REQUIRED on create except for the two reference kinds
///   (`did-self-issued`, `didcomm-peer`) — those carry only references to
///   maintainer-internal keys and have no extra secret bytes. On update,
///   omit to keep the existing secret; populate to rotate.
/// - `clearFields` distinguishes "don't touch" (field omitted from payload)
///   from "clear" (field listed here). Only safe-to-clear fields are
///   listable; `contextId`, `targets`, `label`, `secretKind` are not.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VaultUpsertBody {
    id: Option<String>,
    expected_version: Option<u32>,
    context_id: String,
    targets: Vec<SiteTarget>,
    label: String,
    secret_kind: SecretKind,
    #[serde(default)]
    tags: Vec<String>,
    notes: Option<String>,
    favicon: Option<String>,
    #[serde(default)]
    selectors: Vec<String>,
    #[serde(default)]
    custom_field_names: Vec<String>,
    expires_at: Option<String>,
    sealed_secret: Option<SealedEnvelope>,
    #[serde(default)]
    clear_fields: Vec<ClearableField>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct VaultUpsertResponseBody {
    entry: VaultEntry,
    created: bool,
}

/// Wire form of `vault/_shared/0.1/sealed-envelope#/$defs/SealedEnvelope`
/// — the pluggable cipher envelope. M2A implements only the
/// `didcomm-authcrypt` variant; `hpke-armored` and `tsp-message` are
/// recognised on the wire (so the consumer gets a clean
/// `envelope_unsupported` reject) but not unsealable here yet.
#[derive(Debug, Deserialize)]
#[serde(tag = "envelope", rename_all = "kebab-case")]
enum SealedEnvelope {
    DidcommAuthcrypt {
        jwe: String,
    },
    HpkeArmored {
        #[serde(default)]
        #[allow(dead_code)]
        armored: String,
        #[serde(default)]
        #[allow(dead_code)]
        recipient_key_id: String,
    },
    TspMessage {
        #[serde(default)]
        #[allow(dead_code)]
        message: String,
    },
}

impl SealedEnvelope {
    fn kind_name(&self) -> &'static str {
        match self {
            SealedEnvelope::DidcommAuthcrypt { .. } => "didcomm-authcrypt",
            SealedEnvelope::HpkeArmored { .. } => "hpke-armored",
            SealedEnvelope::TspMessage { .. } => "tsp-message",
        }
    }
}

/// Subset of metadata fields the upsert spec lets the consumer null out
/// explicitly. `contextId` / `targets` / `label` / `secretKind` are
/// excluded — they're either immutable or always required.
#[derive(Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
enum ClearableField {
    Notes,
    Favicon,
    ExpiresAt,
    Tags,
    Selectors,
    CustomFieldNames,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VaultDeleteBody {
    id: String,
    expected_version: Option<u32>,
    /// Human-readable rationale recorded in the audit trail. M2A.2 doesn't
    /// have audit-log wiring for vault yet, so this field is accepted but
    /// only echoed back; full audit landed when the audit module gains a
    /// vault.delete event type.
    #[serde(default)]
    #[allow(dead_code)]
    reason: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct VaultDeleteResponseBody {
    id: String,
    deleted_at: String,
    /// M2A.2 performs a hard delete (no multi-device sync clients exist
    /// yet, so there's nothing to fan tombstones to). `graceUntil ==
    /// deletedAt` indicates "no grace window". When sync (M5) lands, this
    /// gains a real grace window and the storage layer keeps a tombstone
    /// record until then.
    grace_until: String,
}

/// Request body for `vault/release/0.1`. Mirrors the canonical schema.
/// `target` / `consumerContext` / `stepUpProof` are accepted but only
/// consulted by the policy engine in M3; M2A.3's policy is "allow if
/// FillRelease capability".
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VaultReleaseBody {
    entry_id: String,
    #[serde(default)]
    #[allow(dead_code)]
    target: Option<SiteTarget>,
    #[serde(default)]
    #[allow(dead_code)]
    consumer_context: Option<Value>,
    #[serde(default)]
    #[allow(dead_code)]
    step_up_proof: Option<Value>,
    #[serde(default)]
    ttl_seconds_hint: Option<u32>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct VaultReleaseResponseBody {
    /// Pluggable cipher envelope — M2A.3 emits only the `didcomm-authcrypt`
    /// variant. The cleartext inside the JWE is the VaultSecret JSON
    /// (see `vault/_shared/0.1/vault-secret`).
    sealed_secret: SealedEnvelopeWire,
    secret_kind: SecretKind,
    ttl_seconds: u32,
}

/// Wire form of `SealedEnvelope` we EMIT (subset of variants we currently
/// know how to produce). M2A.3 emits the `didcomm-authcrypt` variant only;
/// other variants land if/when those envelope kinds are needed for vault
/// release (e.g. an HPKE-armored airgap export).
#[derive(Debug, Serialize)]
#[serde(tag = "envelope", rename_all = "kebab-case")]
enum SealedEnvelopeWire {
    DidcommAuthcrypt { jwe: String },
}

/// DIDComm `Message.typ` for the release envelope's cleartext. Workspace-
/// namespaced (not a Trust Task URI) — this is purely transport metadata
/// inside the JWE; the outer Trust Task envelope carries the
/// `vault/release/0.1#response` type and the consumer parses the JWE
/// body as `VaultSecret` directly per the spec.
const RELEASE_INNER_MSG_TYPE: &str = "https://openvtc.org/vault/release/secret-envelope/1.0";

/// DIDComm `Message.typ` for the proxy-login envelope's cleartext.
/// Counterpart of [`RELEASE_INNER_MSG_TYPE`] for the SessionBlob the
/// wallet receives. Same workspace namespace; the JWE body is a
/// [`SessionBlob`] per `vault/_shared/0.1/session-blob`.
const PROXY_LOGIN_INNER_MSG_TYPE: &str =
    "https://openvtc.org/vault/proxy-login/session-envelope/1.0";

/// Request body for `vault/proxy-login/0.1`. Mirrors the canonical schema.
/// `consumerContext` / `stepUpProof` are accepted but not yet consumed
/// (M3 policy engine will read consumerContext; step-up gating across
/// the proxy-login flow lands as a follow-up to step-up's release-flow
/// integration). `ttlSecondsHint` is accepted but capped by the
/// maintainer. `nonce` (M2B.4) is embedded verbatim in the SIOP
/// id_token's `nonce` claim — the canonical use is the wallet
/// threading the RP's `/auth/challenge` value through so the resulting
/// id_token passes the RP's nonce check.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VaultProxyLoginBody {
    entry_id: String,
    /// Optional target the wallet is asking the VTA to log in *against*.
    /// When omitted the maintainer picks the entry's first DID-shaped or
    /// web-origin target (in that order). For SIOP entries the audience
    /// is the relying party's DID; for Password POST (M2B.5) it's the
    /// site origin.
    #[serde(default)]
    target: Option<SiteTarget>,
    /// Free-form `consumer-context` per the shared schema — origin /
    /// page hints the wallet ships so the policy engine can decide
    /// whether to proceed. Accepted, ignored by M2B.2b (default-allow).
    #[serde(default)]
    #[allow(dead_code)]
    consumer_context: Option<Value>,
    /// Step-up proof token (vta-approval JWS) — accepted for forward
    /// compatibility; the M2B.2b SIOP driver doesn't require step-up
    /// (the wallet already authenticated this caller). Sensitive sites
    /// gain step-up enforcement via M3 policy + step-up wiring.
    #[serde(default)]
    #[allow(dead_code)]
    step_up_proof: Option<Value>,
    /// Caller-supplied nonce — embedded verbatim as the SIOP id_token's
    /// `nonce` claim for the `did-self-issued` driver. Drivers without
    /// a nonce concept (Password POST, OAuth refresh — M2B.5+) ignore.
    /// Capped to the canonical schema's 512-char ceiling at the parse
    /// boundary; a longer string would fail JSON-Schema validation
    /// upstream but we double-check below to keep the SIOP token shape
    /// sane.
    #[serde(default)]
    nonce: Option<String>,
    #[serde(default)]
    ttl_seconds_hint: Option<u32>,
}

/// Schema-level ceiling for `nonce` per `vault/proxy-login/0.1`. The
/// canonical payload schema enforces this; we re-check here so a
/// malformed-but-parseable request still gets a clean reject rather
/// than a multi-KB JWT.
const NONCE_MAX_LEN: usize = 512;

/// Response body for `vault/proxy-login/0.1`. The `sealedSessionBlob`
/// is the same pluggable cipher envelope shape used by `vault/release` —
/// M2B.2b emits only the `didcomm-authcrypt` variant.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct VaultProxyLoginResponseBody {
    sealed_session_blob: SealedEnvelopeWire,
    /// Maintainer-assigned session id — opaque to the wallet, used by
    /// future `vault/session/{revoke, refresh}/0.1` calls. Same value
    /// as the `sessionId` inside the cleartext SessionBlob; exposed at
    /// the response root so the wallet can log / index it without
    /// having to unseal the envelope first (audit trail before
    /// decryption).
    session_id: String,
    /// Mirrors the cleartext SessionBlob's `expiresAt`. Exposed in the
    /// clear so the wallet's UI can show "session expires in N minutes"
    /// without unsealing. Discarding the wrapper at this time is the
    /// wallet's obligation.
    expires_at: String,
}

/// Reject the request unless the caller's role implies `VaultRead`. When
/// AclEntry-level explicit capabilities arrive (M4), this check upgrades
/// to consult the entry's `capabilities` Vec instead of deriving from role.
fn require_vault_read(auth: &AuthClaims, doc: &TrustTask<Value>) -> Result<(), Response> {
    if role_has_capability(&auth.role, Capability::VaultRead) {
        Ok(())
    } else {
        Err(reject_with(
            doc,
            RejectReason::PermissionDenied {
                reason: format!(
                    "vault read denied: role {} does not carry VaultRead capability",
                    auth.role
                ),
            },
        ))
    }
}

/// Reject the request unless the caller's role implies `VaultWrite` —
/// Admin and Initiator pass; Application, Reader, Monitor do not. Used by
/// upsert + delete. Same role→capability fallback story as
/// [`require_vault_read`]; upgrades to explicit `capabilities` in M4.
fn require_vault_write(auth: &AuthClaims, doc: &TrustTask<Value>) -> Result<(), Response> {
    if role_has_capability(&auth.role, Capability::VaultWrite) {
        Ok(())
    } else {
        Err(reject_with(
            doc,
            RejectReason::PermissionDenied {
                reason: format!(
                    "vault write denied: role {} does not carry VaultWrite capability",
                    auth.role
                ),
            },
        ))
    }
}

/// Reject the request unless the caller's role implies `FillRelease` —
/// Admin, Initiator, and Application pass; Reader and Monitor do not.
/// Used by release. Same role→capability fallback as the other
/// require_* helpers.
fn require_fill_release(auth: &AuthClaims, doc: &TrustTask<Value>) -> Result<(), Response> {
    if role_has_capability(&auth.role, Capability::FillRelease) {
        Ok(())
    } else {
        Err(reject_with(
            doc,
            RejectReason::PermissionDenied {
                reason: format!(
                    "vault release denied: role {} does not carry FillRelease capability",
                    auth.role
                ),
            },
        ))
    }
}

/// Reject the request unless the caller's role implies `ProxyLogin` —
/// Admin, Initiator, and Application pass; Reader and Monitor do not.
/// Used by vault/proxy-login. ProxyLogin is the "VTA performs the login
/// for the consumer" capability; it's strictly more privileged than
/// FillRelease (the consumer never sees the long-term secret) so the
/// role→capability mapping carries it on the same roles as FillRelease.
fn require_proxy_login(auth: &AuthClaims, doc: &TrustTask<Value>) -> Result<(), Response> {
    if role_has_capability(&auth.role, Capability::ProxyLogin) {
        Ok(())
    } else {
        Err(reject_with(
            doc,
            RejectReason::PermissionDenied {
                reason: format!(
                    "vault proxy-login denied: role {} does not carry ProxyLogin capability",
                    auth.role
                ),
            },
        ))
    }
}

/// Used by vault/sign-trust-task. Per-envelope signing on the entry's
/// principal DID — strictly more privileged than `Sign` (which is the
/// generic signing oracle), distinct from `ProxyLogin` (which mints a
/// session credential, not an arbitrary envelope). Splitting them lets
/// operators grant proxy-login without sign-trust-task to limit blast
/// radius on Service consumers.
fn require_sign_trust_task(auth: &AuthClaims, doc: &TrustTask<Value>) -> Result<(), Response> {
    if role_has_capability(&auth.role, Capability::SignTrustTask) {
        Ok(())
    } else {
        Err(reject_with(
            doc,
            RejectReason::PermissionDenied {
                reason: format!(
                    "vault sign-trust-task denied: role {} does not carry SignTrustTask capability",
                    auth.role
                ),
            },
        ))
    }
}

/// Unseal a `SealedEnvelope` into the cleartext [`VaultSecret`].
///
/// M2A supports the `didcomm-authcrypt` variant only. The JWE is unpacked
/// through the VTA's ATM (same machinery the `/auth/` endpoint uses), the
/// resulting message's `from` is cross-checked against the authenticated
/// caller (an attacker can't relay someone else's pre-signed seal through
/// their own auth context), and the cleartext body is deserialised as
/// `VaultSecret`.
///
/// Returns an `axum::Response` carrying the appropriate Trust Task reject
/// on failure — `envelope_unsupported` for non-DIDComm variants,
/// `permission_denied` for sender mismatch, `sealed_secret_invalid` for
/// every other failure path (parse, unpack, schema mismatch).
async fn unseal_secret(
    state: &AppState,
    auth: &AuthClaims,
    doc: &TrustTask<Value>,
    envelope: &SealedEnvelope,
) -> Result<VaultSecret, Response> {
    let jwe = match envelope {
        SealedEnvelope::DidcommAuthcrypt { jwe } => jwe,
        other => {
            return Err(reject_with(
                doc,
                RejectReason::TaskFailed {
                    reason: format!(
                        "vault/upsert:envelope_unsupported — received {kind}; this maintainer accepts only didcomm-authcrypt in M2A",
                        kind = other.kind_name()
                    ),
                    details: Some(serde_json::json!({
                        "receivedEnvelope": other.kind_name(),
                        "supportedEnvelopes": ["didcomm-authcrypt"],
                    })),
                },
            ));
        }
    };

    let atm = state.atm.as_ref().ok_or_else(|| {
        reject_with(
            doc,
            RejectReason::InternalError {
                reason: "ATM not configured — server cannot unpack DIDComm envelopes".into(),
            },
        )
    })?;

    let (msg, _metadata) = atm.unpack(jwe).await.map_err(|e| {
        reject_with(
            doc,
            RejectReason::TaskFailed {
                reason: format!("vault/upsert:sealed_secret_invalid — DIDComm unpack: {e}"),
                details: Some(serde_json::json!({ "reason": "unpack_failed" })),
            },
        )
    })?;

    // Cross-check: the authcrypt sender's DID must equal the authenticated
    // caller. Stops an attacker from replaying someone else's pre-signed
    // seal through their own session.
    let sender = msg
        .from
        .as_deref()
        .map(|s| s.split('#').next().unwrap_or(s).to_string())
        .ok_or_else(|| {
            reject_with(
                doc,
                RejectReason::TaskFailed {
                    reason: "vault/upsert:sealed_secret_invalid — JWE has no sender (from)".into(),
                    details: Some(serde_json::json!({ "reason": "missing_sender" })),
                },
            )
        })?;
    if sender != auth.did {
        return Err(reject_with(
            doc,
            RejectReason::PermissionDenied {
                reason: format!(
                    "vault/upsert:sealed_secret_invalid — JWE sender {sender} does not match authenticated caller {}",
                    auth.did
                ),
            },
        ));
    }

    let secret: VaultSecret = serde_json::from_value(msg.body).map_err(|e| {
        reject_with(
            doc,
            RejectReason::TaskFailed {
                reason: format!(
                    "vault/upsert:sealed_secret_invalid — cleartext not a VaultSecret: {e}"
                ),
                details: Some(serde_json::json!({ "reason": "cleartext_schema_invalid" })),
            },
        )
    })?;
    Ok(secret)
}

/// Reject if the caller's `allowed_contexts` is non-empty AND `context_id`
/// (if supplied) is not in the allowed list. Empty allowed_contexts means
/// super-admin scope.
fn enforce_context_scope(
    auth: &AuthClaims,
    context_id: Option<&str>,
    doc: &TrustTask<Value>,
) -> Result<(), Response> {
    let Some(ctx) = context_id else {
        return Ok(()); // No context filter — caller's full visibility applies.
    };
    if auth.allowed_contexts.is_empty() {
        return Ok(()); // Super-admin (or unscoped) sees everything.
    }
    if auth.allowed_contexts.iter().any(|c| c == ctx) {
        return Ok(());
    }
    Err(reject_with(
        doc,
        RejectReason::PermissionDenied {
            reason: format!("vault scope denied: caller is not authorised for context {ctx}"),
        },
    ))
}

/// Handler for `spec/vault/list/0.1`.
pub(super) async fn handle_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> Response {
    if let Err(r) = require_vault_read(auth, &doc) {
        return r;
    }

    let req: VaultListBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    // Reject mutually-exclusive filter combinations the spec calls out.
    if req.used_since.is_some() && req.never_used == Some(true) {
        return reject_with(
            &doc,
            RejectReason::MalformedRequest {
                reason: "vault/list: usedSince and neverUsed are mutually exclusive".into(),
            },
        );
    }

    if let Err(r) = enforce_context_scope(auth, req.context_id.as_deref(), &doc) {
        return r;
    }

    let filter = VaultListFilter {
        context_id: req.context_id.as_deref(),
        target_origin_prefix: req.target_origin_prefix.as_deref(),
        target_did: req.target_did.as_deref(),
        target_ios_bundle_id: req.target_ios_bundle_id.as_deref(),
        target_android_package: req.target_android_package.as_deref(),
        secret_kind: req.secret_kind,
        tag: req.tag.as_deref(),
        used_since: req.used_since.as_deref(),
        never_used: req.never_used,
        expires_before: req.expires_before.as_deref(),
        breached: req.breached,
    };

    let mut entries = match list_entries_store(&state.vault_ks, &filter).await {
        Ok(v) => v,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    // If the caller's role is scoped to a subset of contexts and they
    // queried without a `contextId` filter, narrow the result set to
    // visible contexts only. This is defence-in-depth in addition to
    // `enforce_context_scope` — that path covers the explicit-filter case;
    // this one covers the implicit-all-contexts case.
    if !auth.allowed_contexts.is_empty() && req.context_id.is_none() {
        entries.retain(|e| auth.allowed_contexts.iter().any(|c| c == &e.context_id));
    }

    // M1 pagination: single page. Apply page_size as a hard truncation.
    let page_size = req.page_size.unwrap_or(100) as usize;
    let truncated = entries.len() > page_size;
    entries.truncate(page_size);

    success_response(
        &doc,
        VaultListResponseBody {
            entries,
            truncated,
            cursor: None,
            redacted_fields: None,
        },
    )
}

/// Handler for `spec/vault/get/0.1`.
pub(super) async fn handle_get(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> Response {
    if let Err(r) = require_vault_read(auth, &doc) {
        return r;
    }
    let req: VaultGetBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    let entry = match get_vault_entry(&state.vault_ks, &req.id).await {
        Ok(Some(e)) => e,
        // Conflate not-found with permission-denied to deny enumeration.
        Ok(None) => {
            return app_error_to_reject(
                &doc,
                AppError::NotFound(format!("vault entry {} not found", req.id)),
            );
        }
        Err(e) => return app_error_to_reject(&doc, e),
    };

    if let Err(r) = enforce_context_scope(auth, Some(&entry.context_id), &doc) {
        return r;
    }

    success_response(
        &doc,
        VaultGetResponseBody {
            entry,
            redacted_fields: None,
        },
    )
}

/// Handler for `spec/vault/upsert/0.1`. Create or update a vault entry;
/// secret material rides inside the pluggable `sealedSecret` envelope and
/// is unsealed server-side via [`unseal_secret`]. See the spec for the
/// full payload shape; this implementation honours every required field
/// and the spec's full error-code surface
/// (`context_not_found` is currently NOT enforced — the maintainer accepts
/// any contextId the consumer supplies; cross-checking against the
/// contexts keyspace lands in a follow-up).
pub(super) async fn handle_upsert(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> Response {
    if let Err(r) = require_vault_write(auth, &doc) {
        return r;
    }

    let req: VaultUpsertBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    if let Err(r) = enforce_context_scope(auth, Some(&req.context_id), &doc) {
        return r;
    }

    // Load existing (if `id` supplied). Optimistic-concurrency check
    // happens after; we need the row for context-change-forbidden and
    // for the create-vs-update decision anyway.
    let existing: Option<StoredVaultEntry> = if let Some(id) = req.id.as_deref() {
        match get_stored_vault_entry(&state.vault_ks, id).await {
            Ok(e) => e,
            Err(e) => return app_error_to_reject(&doc, e),
        }
    } else {
        None
    };

    // An `expectedVersion` was supplied but there's no row at this id —
    // the client thinks it's updating something that doesn't exist.
    if existing.is_none() && req.expected_version.is_some() && req.id.is_some() {
        return reject_with(
            &doc,
            RejectReason::TaskFailed {
                reason: format!(
                    "vault/upsert:not_found — no entry at id {}",
                    req.id.as_deref().unwrap_or("(none)")
                ),
                details: None,
            },
        );
    }

    // Forbid changing the contextId of an existing entry.
    if let Some(e) = existing.as_ref()
        && e.entry.context_id != req.context_id
    {
        return reject_with(
            &doc,
            RejectReason::TaskFailed {
                reason: format!(
                    "vault/upsert:context_change_forbidden — entry {} is in context {}; cannot move to {}. Delete and recreate instead.",
                    e.entry.id, e.entry.context_id, req.context_id
                ),
                details: Some(serde_json::json!({
                    "currentContext": e.entry.context_id,
                    "requestedContext": req.context_id,
                })),
            },
        );
    }

    // Optimistic concurrency for updates.
    if let (Some(e), Some(v)) = (existing.as_ref(), req.expected_version)
        && e.entry.version != v
    {
        return reject_with(
            &doc,
            RejectReason::TaskFailed {
                reason: format!(
                    "vault/upsert:version_conflict — expectedVersion {v} != current version {}",
                    e.entry.version
                ),
                details: Some(serde_json::json!({ "currentVersion": e.entry.version })),
            },
        );
    }

    // Resolve the secret. Three cases:
    //   - sealed_secret supplied → unseal it.
    //   - no sealed_secret, existing entry → reuse existing secret.
    //   - no sealed_secret, create → secret_required.
    let secret: VaultSecret = match (&req.sealed_secret, existing.as_ref()) {
        (Some(env), _) => match unseal_secret(state, auth, &doc, env).await {
            Ok(s) => s,
            Err(resp) => return resp,
        },
        (None, Some(e)) => e.secret.clone(),
        (None, None) => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!(
                        "vault/upsert:secret_required — secretKind {:?} needs `sealedSecret` on create",
                        req.secret_kind
                    ),
                    details: None,
                },
            );
        }
    };

    if !secret.matches_kind(req.secret_kind) {
        return reject_with(
            &doc,
            RejectReason::TaskFailed {
                reason: format!(
                    "vault/upsert:sealed_secret_invalid — declared secretKind {:?} does not match secret variant {:?}",
                    req.secret_kind,
                    secret.kind()
                ),
                details: Some(serde_json::json!({
                    "declaredKind": serde_json::to_value(req.secret_kind).ok(),
                    "secretVariant": serde_json::to_value(secret.kind()).ok(),
                })),
            },
        );
    }

    // Build the resulting VaultEntry. Some fields come from `existing`
    // (immutable / sticky), some from the request, some are computed.
    let now = chrono::Utc::now().to_rfc3339();
    let is_create = existing.is_none();
    let secret_rotated_password =
        req.sealed_secret.is_some() && matches!(req.secret_kind, SecretKind::Password);

    let entry = VaultEntry {
        id: existing
            .as_ref()
            .map(|e| e.entry.id.clone())
            .or(req.id.clone())
            .unwrap_or_else(|| format!("vault_{}", Uuid::new_v4().simple())),
        context_id: req.context_id,
        targets: req.targets,
        label: req.label,
        secret_kind: req.secret_kind,
        tags: if req.clear_fields.contains(&ClearableField::Tags) {
            Vec::new()
        } else {
            req.tags
        },
        notes: if req.clear_fields.contains(&ClearableField::Notes) {
            None
        } else {
            req.notes
        },
        favicon: if req.clear_fields.contains(&ClearableField::Favicon) {
            None
        } else {
            req.favicon
        },
        selectors: if req.clear_fields.contains(&ClearableField::Selectors) {
            Vec::new()
        } else {
            req.selectors
        },
        custom_field_names: if req.clear_fields.contains(&ClearableField::CustomFieldNames) {
            Vec::new()
        } else {
            req.custom_field_names
        },
        // Attachments are not exposed on upsert — they round-trip from
        // existing rows untouched. Future task vault/attachments/*
        // manages them.
        attachments: existing
            .as_ref()
            .map(|e| e.entry.attachments.clone())
            .unwrap_or_default(),
        expires_at: if req.clear_fields.contains(&ClearableField::ExpiresAt) {
            None
        } else {
            req.expires_at
        },
        // Sticky from existing — maintainer-set fields.
        breached_at: existing.as_ref().and_then(|e| e.entry.breached_at.clone()),
        password_changed_at: if (is_create && matches!(req.secret_kind, SecretKind::Password))
            || secret_rotated_password
        {
            Some(now.clone())
        } else {
            existing
                .as_ref()
                .and_then(|e| e.entry.password_changed_at.clone())
        },
        created_at: existing
            .as_ref()
            .map(|e| e.entry.created_at.clone())
            .unwrap_or_else(|| now.clone()),
        created_by: existing
            .as_ref()
            .and_then(|e| e.entry.created_by.clone())
            .or_else(|| Some(auth.did.clone())),
        updated_at: now,
        updated_by: Some(auth.did.clone()),
        last_used_at: existing.as_ref().and_then(|e| e.entry.last_used_at.clone()),
        version: existing.as_ref().map(|e| e.entry.version + 1).unwrap_or(1),
        // Maintainer-derived from the canonical secret. Producer-supplied
        // values on the wire are intentionally ignored — the canonical
        // schema declares this field read-only and we recompute every
        // upsert + rotation. Stays in sync with the actual signing key
        // for did-self-issued / didcomm-peer entries.
        principal_did: VaultEntry::principal_did_from_secret(&secret),
    };

    let record = StoredVaultEntry {
        entry: entry.clone(),
        secret,
    };
    if let Err(e) = put_stored_vault_entry(&state.vault_ks, &record).await {
        return app_error_to_reject(&doc, e);
    }

    success_response(
        &doc,
        VaultUpsertResponseBody {
            entry,
            created: is_create,
        },
    )
}

/// Handler for `spec/vault/delete/0.1`.
///
/// M2A.2 performs a hard delete — the row is removed from the keyspace
/// and the secret bytes are zeroised by the keyspace handle's `remove`
/// implementation. There's no multi-device sync yet (M5 territory), so
/// no tombstone-with-grace machinery is needed. The response's
/// `graceUntil` field equals `deletedAt` to signal "no grace window";
/// callers that re-sync after M5 will see a real grace window.
///
/// Enumeration-resistance: a missing entry returns `not_found`
/// regardless of whether the consumer would actually have had read
/// access to it — the consumer can't probe id space by deleting.
///
/// Audit-log wiring for vault events lands when the audit module gains
/// a `vault.*` event variant. For M2A.2 the `reason` field is accepted
/// and ignored.
pub(super) async fn handle_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> Response {
    if let Err(r) = require_vault_write(auth, &doc) {
        return r;
    }

    let req: VaultDeleteBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    let existing = match get_stored_vault_entry(&state.vault_ks, &req.id).await {
        Ok(Some(e)) => e,
        Ok(None) => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!("vault/delete:not_found — no entry at id {}", req.id),
                    details: None,
                },
            );
        }
        Err(e) => return app_error_to_reject(&doc, e),
    };

    // Defence-in-depth: even with VaultWrite, narrow callers must be in
    // the entry's context. Same shape as the read path.
    if let Err(r) = enforce_context_scope(auth, Some(&existing.entry.context_id), &doc) {
        return r;
    }

    if let Some(v) = req.expected_version
        && v != existing.entry.version
    {
        return reject_with(
            &doc,
            RejectReason::TaskFailed {
                reason: format!(
                    "vault/delete:version_conflict — expectedVersion {v} != current version {}",
                    existing.entry.version
                ),
                details: Some(serde_json::json!({ "currentVersion": existing.entry.version })),
            },
        );
    }

    if let Err(e) = delete_vault_entry(&state.vault_ks, &req.id).await {
        return app_error_to_reject(&doc, e);
    }

    let now = chrono::Utc::now().to_rfc3339();
    success_response(
        &doc,
        VaultDeleteResponseBody {
            id: req.id,
            deleted_at: now.clone(),
            grace_until: now,
        },
    )
}

/// Handler for `spec/vault/release/0.1`. Releases the cleartext secret
/// material of an entry to the requesting consumer, wrapped in a
/// DIDComm-authcrypt envelope sealed to the caller's keyAgreement key.
///
/// M2A.3 flow:
/// 1. `require_fill_release` — Admin / Initiator / Application pass.
/// 2. Parse body, load entry by id (`not_found` if absent, conflated
///    with absence-of-read-access for enumeration resistance).
/// 3. `enforce_context_scope` against the entry's context.
/// 4. Default policy: allow (M3 swaps in `regorus`). Step-up demand
///    is not exercised in M2A.3 — the spec's `step_up_required`
///    error code lands when policy-driven decisions arrive.
/// 5. Cap TTL at 60 s (the maintainer-policy ceiling; client
///    `ttlSecondsHint` is honoured up to that cap).
/// 6. Build a DIDComm `Message` carrying the `VaultSecret` JSON as
///    body. Pack via `atm.pack_encrypted(msg, recipient=auth.did,
///    signer=vta_did, key_holder=vta_did)` — ATM resolves the
///    consumer's X25519 keyAgreement from their DID document
///    (cached on `state.did_resolver`) and signs with the VTA's
///    pre-loaded secrets resolver.
/// 7. Update the stored entry's `last_used_at` (NOT a version bump
///    — that's reserved for user-visible mutations; `last_used_at`
///    is server-managed metadata).
/// 8. Return the JWE inside a `SealedEnvelope { envelope:
///    "didcomm-authcrypt", jwe }` per the canonical schema.
///
/// Audit-log wiring for vault events lands when the audit module
/// gains a `vault.*` event variant — same hold as in M2A.2.
pub(super) async fn handle_release(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> Response {
    if let Err(r) = require_fill_release(auth, &doc) {
        return r;
    }

    let req: VaultReleaseBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    let mut stored = match get_stored_vault_entry(&state.vault_ks, &req.entry_id).await {
        Ok(Some(e)) => e,
        Ok(None) => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!("vault/release:not_found — no entry at id {}", req.entry_id),
                    details: None,
                },
            );
        }
        Err(e) => return app_error_to_reject(&doc, e),
    };

    if let Err(r) = enforce_context_scope(auth, Some(&stored.entry.context_id), &doc) {
        return r;
    }

    // ATM is required for outbound authcrypt. Pre-flight check before
    // we build the message so the error is clearly "infrastructure not
    // configured" rather than a packing failure mid-flow.
    let atm = match state.atm.as_ref() {
        Some(atm) => atm,
        None => {
            return reject_with(
                &doc,
                RejectReason::InternalError {
                    reason: "ATM not configured — server cannot pack DIDComm envelopes".into(),
                },
            );
        }
    };

    let vta_did = {
        let config = state.config.read().await;
        match config.vta_did.clone() {
            Some(d) => d,
            None => {
                return reject_with(
                    &doc,
                    RejectReason::InternalError {
                        reason: "vta_did not configured — server cannot identify itself as signer"
                            .into(),
                    },
                );
            }
        }
    };

    // Cap TTL. Client hint is honoured up to the M2A.3 ceiling (60s);
    // a higher hint silently caps rather than rejecting.
    const TTL_CEILING: u32 = 60;
    let ttl_seconds = req
        .ttl_seconds_hint
        .map(|t| t.min(TTL_CEILING))
        .unwrap_or(TTL_CEILING);

    // Serialise the VaultSecret as the cleartext body of the inner
    // DIDComm message. Per the canonical sealed-envelope schema, the
    // cleartext inside the JWE is the VaultSecret JSON directly.
    let secret_body = match serde_json::to_value(&stored.secret) {
        Ok(v) => v,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::InternalError {
                    reason: format!("vault/release: failed to serialise secret: {e}"),
                },
            );
        }
    };

    let msg = Message::build(
        Uuid::new_v4().to_string(),
        RELEASE_INNER_MSG_TYPE.to_string(),
        secret_body,
    )
    .from(vta_did.clone())
    .to(auth.did.clone())
    .finalize();

    let (jwe, _metadata) = match atm
        .pack_encrypted(&msg, &auth.did, Some(&vta_did), Some(&vta_did))
        .await
    {
        Ok(packed) => packed,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::InternalError {
                    reason: format!("vault/release: pack_encrypted failed: {e}"),
                },
            );
        }
    };

    // Update lastUsedAt on the stored entry. Server-managed metadata —
    // NOT a version bump (that's reserved for user-visible mutations
    // gated by optimistic concurrency). A concurrent upsert with a
    // stale expectedVersion still validates against the version this
    // release didn't touch.
    let now = chrono::Utc::now().to_rfc3339();
    stored.entry.last_used_at = Some(now);
    if let Err(e) = put_stored_vault_entry(&state.vault_ks, &stored).await {
        // Persist failure isn't fatal — the secret has been sealed and
        // is on its way. Log via the audit reject path so an operator
        // can see lastUsedAt drift if it ever happens.
        tracing::warn!(
            entry_id = %stored.entry.id,
            error = %e,
            "vault/release: lastUsedAt update failed; secret release proceeded"
        );
    }

    let secret_kind = stored.entry.secret_kind;
    success_response(
        &doc,
        VaultReleaseResponseBody {
            sealed_secret: SealedEnvelopeWire::DidcommAuthcrypt { jwe },
            secret_kind,
            ttl_seconds,
        },
    )
}

/// Per-driver TTL ceilings. SIOP is capped by the underlying id_token's
/// `exp` (300 s, the canonical M2B.2b limit). Password POST is capped
/// by the maintainer's policy; we keep it short by default so a
/// compromised wallet can't replay the session indefinitely. The
/// caller's `ttlSecondsHint` is honoured up to the ceiling and
/// silently truncated above it.
#[cfg(feature = "webvh")]
const PASSWORD_POST_TTL_CEILING_SECS: u64 = 900;

/// Handler for `spec/vault/proxy-login/0.1`. Two drivers wired today:
///
/// - **`did-self-issued`** (M2B.2b): VTA mints a SIOPv2 id_token on
///   the entry's behalf, wraps it in a [`SessionBlob`] with a single
///   `Authorization: Bearer …` header. Long-term signing key never
///   leaves the VTA.
/// - **`password`** with a `loginConfig` (M2B.5): VTA performs an
///   HTTP POST against the configured login URL with the entry's
///   credentials, captures the resulting Set-Cookie headers, and
///   returns them in a [`SessionBlob`] for the consumer to inject
///   into its browser. Long-term password leaves the VTA only as
///   the body of one outbound HTTPS request.
///
/// `password` without a `loginConfig` rejects with `not_proxyable`
/// (consumer falls back to `vault/release` for browser-fill). Other
/// secret kinds (`passkey`, `oauth-tokens`, `didcomm-peer`,
/// `bearer-token`, `ssh-key`, `custom`) reject with
/// `not_implemented` — future drivers will light them up.
pub(super) async fn handle_proxy_login(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> Response {
    if let Err(r) = require_proxy_login(auth, &doc) {
        return r;
    }

    let req: VaultProxyLoginBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };

    // Defense-in-depth nonce bounds check. The canonical schema
    // enforces `minLength: 1, maxLength: 512`; this guard handles
    // requests that bypassed schema validation (e.g. dispatcher
    // changes that disable schema-first parsing).
    if let Some(n) = req.nonce.as_deref()
        && (n.is_empty() || n.len() > NONCE_MAX_LEN)
    {
        return reject_with(
            &doc,
            RejectReason::MalformedRequest {
                reason: format!(
                    "vault/proxy-login: nonce length {} outside [1, {NONCE_MAX_LEN}]",
                    n.len()
                ),
            },
        );
    }

    // Load entry — conflate not-found with permission-denied to deny
    // enumeration (matches handle_release).
    let mut stored = match get_stored_vault_entry(&state.vault_ks, &req.entry_id).await {
        Ok(Some(e)) => e,
        Ok(None) => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!(
                        "vault/proxy-login:not_found — no entry at id {}",
                        req.entry_id
                    ),
                    details: None,
                },
            );
        }
        Err(e) => return app_error_to_reject(&doc, e),
    };

    if let Err(r) = enforce_context_scope(auth, Some(&stored.entry.context_id), &doc) {
        return r;
    }

    // ATM + vta_did are needed for the shared authcrypt tail
    // regardless of driver — hoist them above the dispatch so both
    // arms see the same readiness checks.
    let atm = match state.atm.as_ref() {
        Some(atm) => atm,
        None => {
            return reject_with(
                &doc,
                RejectReason::InternalError {
                    reason: "ATM not configured — server cannot pack DIDComm envelopes".into(),
                },
            );
        }
    };

    let vta_did = {
        let config = state.config.read().await;
        match config.vta_did.clone() {
            Some(d) => d,
            None => {
                return reject_with(
                    &doc,
                    RejectReason::InternalError {
                        reason: "vta_did not configured — server cannot identify itself as signer"
                            .into(),
                    },
                );
            }
        }
    };

    // Driver dispatch. Each arm constructs a `SessionBlob` (plus its
    // own session_id + expires_at) and the shared tail authcrypts +
    // persists + responds. Adding a new driver (e.g. OAuth refresh)
    // means one more arm here — the wrapper code stays put.
    let (session_blob, session_id, expires_at) = match &stored.secret {
        // ─── M2B.2b: did-self-issued (SIOP id_token) ───
        VaultSecret::DidSelfIssued {
            did: siop_did,
            signing_key_id,
            ..
        } => {
            let (audience, bind_origin) = match resolve_siop_audience(
                &req.target,
                &stored.entry.targets,
            ) {
                Some(pair) => pair,
                None => {
                    return reject_with(
                        &doc,
                        RejectReason::TaskFailed {
                            reason:
                                "vault/proxy-login:no_audience — entry has no DID or web-origin target to use as SIOP audience"
                                    .into(),
                            details: Some(serde_json::json!({
                                "entryTargets": &stored.entry.targets,
                            })),
                        },
                    );
                }
            };
            let ttl_secs = req
                .ttl_seconds_hint
                .map(|t| (t as u64).min(crate::operations::vault::PROXY_LOGIN_ID_TOKEN_TTL_SECS))
                .unwrap_or(crate::operations::vault::PROXY_LOGIN_ID_TOKEN_TTL_SECS);
            let signing_key = match crate::operations::vault::load_signing_key_by_id(
                &state.keys_ks,
                &state.imported_ks,
                &*state.seed_store,
                &state.audit_ks,
                signing_key_id,
            )
            .await
            {
                Ok(k) => k,
                Err(e) => return app_error_to_reject(&doc, e),
            };
            let iat = chrono::Utc::now().timestamp().max(0) as u64;
            let id_token = match crate::operations::vault::build_siop_id_token(
                siop_did,
                signing_key_id,
                &audience,
                req.nonce.as_deref(),
                iat,
                ttl_secs,
                &signing_key,
            ) {
                Ok(t) => t,
                Err(e) => return app_error_to_reject(&doc, e),
            };
            build_session_blob_with_bearer(id_token, bind_origin, ttl_secs)
        }
        // ─── M2B.5: password (HTTP-POST driver) ───
        VaultSecret::Password {
            username,
            password,
            totp,
            login_config: Some(login_config),
            ..
        } => {
            #[cfg(feature = "webvh")]
            {
                let cookies = match crate::operations::vault::password_post::run_password_post(
                    login_config,
                    username.as_deref(),
                    password,
                    totp.as_ref(),
                )
                .await
                {
                    Ok(c) => c,
                    Err(e) => {
                        return reject_with(
                            &doc,
                            password_post_error_to_reject(&e, &stored.entry.id),
                        );
                    }
                };
                let ttl_secs = req
                    .ttl_seconds_hint
                    .map(|t| (t as u64).min(PASSWORD_POST_TTL_CEILING_SECS))
                    .unwrap_or(PASSWORD_POST_TTL_CEILING_SECS);
                // bind_origin: prefer the entry's first WebOrigin (where the
                // user actually browses); falls back to the loginUrl's
                // origin when the entry only carries DID / app targets
                // (atypical but possible — e.g. an API-first site with a
                // DID-bound target).
                let bind_origin = first_web_origin(&stored.entry.targets).or_else(|| {
                    url::Url::parse(&login_config.login_url)
                        .ok()
                        .and_then(|u| u.origin().ascii_serialization().into())
                });
                build_session_blob_with_cookies(cookies, bind_origin, ttl_secs)
            }
            #[cfg(not(feature = "webvh"))]
            {
                let _ = (username, password, totp, login_config);
                return reject_with(
                    &doc,
                    RejectReason::TaskFailed {
                        reason:
                            "vault/proxy-login:not_implemented — password driver requires the `webvh` feature"
                                .into(),
                        details: None,
                    },
                );
            }
        }
        VaultSecret::Password {
            login_config: None, ..
        } => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason:
                        "vault/proxy-login:not_proxyable — password entry has no loginConfig; use vault/release for browser-fill"
                            .into(),
                    details: Some(serde_json::json!({
                        "secretKind": "password",
                        "remediation": "fall back to vault/release/0.1",
                    })),
                },
            );
        }
        other => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!(
                        "vault/proxy-login:not_implemented — entry secretKind {kind} has no proxy-login driver yet",
                        kind = secret_kind_label(other.kind())
                    ),
                    details: Some(serde_json::json!({
                        "secretKind": other.kind(),
                        "supportedKinds": ["did-self-issued", "password"],
                    })),
                },
            );
        }
    };

    let session_body = match serde_json::to_value(&session_blob) {
        Ok(v) => v,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::InternalError {
                    reason: format!("vault/proxy-login: failed to serialise SessionBlob: {e}"),
                },
            );
        }
    };

    let msg = Message::build(
        Uuid::new_v4().to_string(),
        PROXY_LOGIN_INNER_MSG_TYPE.to_string(),
        session_body,
    )
    .from(vta_did.clone())
    .to(auth.did.clone())
    .finalize();

    let (jwe, _metadata) = match atm
        .pack_encrypted(&msg, &auth.did, Some(&vta_did), Some(&vta_did))
        .await
    {
        Ok(packed) => packed,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::InternalError {
                    reason: format!("vault/proxy-login: pack_encrypted failed: {e}"),
                },
            );
        }
    };

    // Same lastUsedAt update as handle_release — server-managed
    // metadata, NOT a version bump.
    let now = chrono::Utc::now().to_rfc3339();
    stored.entry.last_used_at = Some(now);
    if let Err(e) = put_stored_vault_entry(&state.vault_ks, &stored).await {
        tracing::warn!(
            entry_id = %stored.entry.id,
            error = %e,
            "vault/proxy-login: lastUsedAt update failed; session release proceeded"
        );
    }

    success_response(
        &doc,
        VaultProxyLoginResponseBody {
            sealed_session_blob: SealedEnvelopeWire::DidcommAuthcrypt { jwe },
            session_id,
            expires_at,
        },
    )
}

// ─── vault/sign-trust-task/0.1 ─────────────────────────────────────

/// Request body for `vault/sign-trust-task/0.1`. Mirrors the canonical
/// schema. `consumerContext` / `stepUpProof` are accepted but not yet
/// consumed (M3 policy engine will read consumerContext; step-up gating
/// across sign-trust-task lands as a follow-up to the proxy-login wiring).
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VaultSignTrustTaskBody {
    entry_id: String,
    unsigned_envelope: Value,
    #[serde(default)]
    #[allow(dead_code)]
    consumer_context: Option<Value>,
    #[serde(default)]
    #[allow(dead_code)]
    step_up_proof: Option<Value>,
}

/// Response body for `vault/sign-trust-task/0.1`. Same `unsigned_envelope`
/// the consumer submitted with a `proof` field attached.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct VaultSignTrustTaskResponseBody {
    signed_envelope: Value,
}

/// Handler for `spec/vault/sign-trust-task/0.1`. Attaches an
/// `eddsa-jcs-2022` Data Integrity proof to a Trust Task envelope,
/// signing as the principal DID of a `did-self-issued` or
/// `didcomm-peer` vault entry.
///
/// The long-term signing key never leaves the maintainer. This is the
/// per-envelope-signing complement to `vault/proxy-login/0.1`: proxy-
/// login mints a session credential at session-start; sign-trust-task
/// signs individual follow-up tasks during that session so the proof
/// VM matches the authenticated session DID at the relying party.
///
/// Conformance check order matches the spec's error precedence:
/// `not_found` → `permission_denied` (cap) → context scope →
/// `not_signable` (entry kind) → `envelope_invalid` (structure) →
/// `envelope_already_proofed` → `envelope_issuer_mismatch` →
/// `envelope_expired` → sign.
pub(super) async fn handle_sign_trust_task(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> Response {
    if let Err(r) = require_sign_trust_task(auth, &doc) {
        return r;
    }
    let req: VaultSignTrustTaskBody = match parse_payload(&doc) {
        Ok(v) => v,
        Err(r) => return r,
    };

    // Load entry — conflate not-found with permission-denied to deny
    // enumeration (matches handle_release / handle_proxy_login).
    let stored = match get_stored_vault_entry(&state.vault_ks, &req.entry_id).await {
        Ok(Some(e)) => e,
        Ok(None) => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!(
                        "vault/sign-trust-task:not_found — no entry at id {}",
                        req.entry_id
                    ),
                    details: None,
                },
            );
        }
        Err(e) => return app_error_to_reject(&doc, e),
    };

    if let Err(r) = enforce_context_scope(auth, Some(&stored.entry.context_id), &doc) {
        return r;
    }

    // Only signable kinds (DID-anchored secrets) carry a principal
    // identity the maintainer can sign as. Password / OAuth / passkey
    // / bearer / ssh / custom kinds have no DID — reject loudly so the
    // consumer can fall back to a different flow (proxy-login for
    // session creds, release for browser autofill).
    let (principal_did, signing_key_id) = match &stored.secret {
        VaultSecret::DidSelfIssued {
            did,
            signing_key_id,
            ..
        }
        | VaultSecret::DidcommPeer {
            peer_did: did,
            signing_key_id,
            ..
        } => (did.clone(), signing_key_id.clone()),
        other => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!(
                        "vault/sign-trust-task:not_signable — entry kind '{}' has no DID-based signing identity",
                        secret_kind_label(other.kind()),
                    ),
                    details: Some(serde_json::json!({
                        "secretKind": secret_kind_label(other.kind()),
                    })),
                },
            );
        }
    };

    // Structural validation of the supplied envelope. Per spec: id,
    // type, issuer, recipient, issuedAt, payload all required; proof
    // must be absent.
    let envelope_obj = match req.unsigned_envelope.as_object() {
        Some(o) => o,
        None => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: "vault/sign-trust-task:envelope_invalid — unsignedEnvelope must be a JSON object".into(),
                    details: None,
                },
            );
        }
    };
    for field in ["id", "type", "issuer", "recipient", "issuedAt", "payload"] {
        if !envelope_obj.contains_key(field) {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: format!(
                        "vault/sign-trust-task:envelope_invalid — missing required field '{field}'"
                    ),
                    details: Some(serde_json::json!({ "missing": field })),
                },
            );
        }
    }
    if envelope_obj.contains_key("proof") {
        return reject_with(
            &doc,
            RejectReason::TaskFailed {
                reason: "vault/sign-trust-task:envelope_already_proofed — strip the existing proof and resubmit".into(),
                details: None,
            },
        );
    }

    // Strict issuer match: the maintainer refuses to silently rewrite
    // the consumer's issuer. Mismatch is loud so consumer bugs surface
    // explicitly rather than as cryptic verification failures at the
    // recipient.
    let envelope_issuer = match envelope_obj.get("issuer").and_then(|v| v.as_str()) {
        Some(s) => s,
        None => {
            return reject_with(
                &doc,
                RejectReason::TaskFailed {
                    reason: "vault/sign-trust-task:envelope_invalid — issuer must be a string"
                        .into(),
                    details: None,
                },
            );
        }
    };
    if envelope_issuer != principal_did {
        return reject_with(
            &doc,
            RejectReason::TaskFailed {
                reason: "vault/sign-trust-task:envelope_issuer_mismatch — envelope.issuer must equal the entry's principalDid".into(),
                details: Some(serde_json::json!({
                    "envelopeIssuer": envelope_issuer,
                    "expectedIssuer": principal_did,
                })),
            },
        );
    }

    // expiresAt (if present) must not be in the past.
    if let Some(exp_v) = envelope_obj.get("expiresAt") {
        let exp_str = exp_v.as_str().unwrap_or_default();
        match chrono::DateTime::parse_from_rfc3339(exp_str) {
            Ok(exp) if exp < chrono::Utc::now() => {
                return reject_with(
                    &doc,
                    RejectReason::TaskFailed {
                        reason: "vault/sign-trust-task:envelope_expired — envelope.expiresAt is in the past".into(),
                        details: Some(serde_json::json!({ "expiresAt": exp_str })),
                    },
                );
            }
            Ok(_) => {} // future-dated, fine
            Err(_) => {
                return reject_with(
                    &doc,
                    RejectReason::TaskFailed {
                        reason: "vault/sign-trust-task:envelope_invalid — expiresAt must be an RFC 3339 timestamp".into(),
                        details: Some(serde_json::json!({ "expiresAt": exp_str })),
                    },
                );
            }
        }
    }

    // Load the signing key as an affinidi Secret (the shape
    // DataIntegrityProof::sign consumes). The kid the proof's
    // verificationMethod field carries IS the entry's signing_key_id —
    // the maintainer trusts the stored entry's reference because the
    // upsert path validated it at the time the entry was written.
    let secret = match crate::operations::vault::load_signing_secret_by_id(
        &state.keys_ks,
        &state.imported_ks,
        &*state.seed_store,
        &state.audit_ks,
        &signing_key_id,
    )
    .await
    {
        Ok(s) => s,
        Err(e) => return app_error_to_reject(&doc, e),
    };

    // Sign. `DataIntegrityProof::sign` takes the document WITHOUT a
    // `proof` field — we already validated none is present. The
    // resulting `proof` object carries cryptosuite, verificationMethod
    // (`<principalDid>#<signingKeyId>`), proofPurpose=assertionMethod,
    // created, and proofValue.
    let proof = match affinidi_data_integrity::DataIntegrityProof::sign(
        &req.unsigned_envelope,
        &secret,
        affinidi_data_integrity::SignOptions::new(),
    )
    .await
    {
        Ok(p) => p,
        Err(e) => {
            return app_error_to_reject(
                &doc,
                AppError::Internal(format!("DataIntegrityProof sign failed: {e}")),
            );
        }
    };
    let proof_value = match serde_json::to_value(&proof) {
        Ok(v) => v,
        Err(e) => {
            return app_error_to_reject(&doc, AppError::Internal(format!("serialize proof: {e}")));
        }
    };

    // Attach proof to the envelope. Mutate the parsed JSON in place so
    // every other field — including any consumer-supplied `ext` — is
    // preserved byte-for-byte.
    let mut signed = req.unsigned_envelope.clone();
    signed
        .as_object_mut()
        .expect("envelope is an object — checked above")
        .insert("proof".to_string(), proof_value);

    // Audit log — `{who, when, entryId, envelope: {id, type, recipient}, outcome}`.
    // Per the spec, payload is OMITTED (it may carry sensitive RP-side
    // task content).
    let envelope_id = envelope_obj
        .get("id")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let envelope_type = envelope_obj
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let envelope_recipient = envelope_obj
        .get("recipient")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    tracing::info!(
        actor = %auth.did,
        entry_id = %req.entry_id,
        envelope_id,
        envelope_type,
        envelope_recipient,
        principal_did = %principal_did,
        "vault/sign-trust-task: signed"
    );

    success_response(
        &doc,
        VaultSignTrustTaskResponseBody {
            signed_envelope: signed,
        },
    )
}

/// Resolve the SIOP audience (and the SessionBlob's `bind_origin`) from
/// the optional request target + the entry's declared targets.
///
/// Priority:
/// 1. Explicit `req.target`: must be `Did` or `WebOrigin` (the only two
///    SIOP-meaningful target kinds). App targets reject — they'd need a
///    different flow.
/// 2. First `Did` target on the entry.
/// 3. First `WebOrigin` target on the entry.
/// 4. None — caller rejects with `no_audience`.
///
/// `bind_origin` is set when the *audience* is a web origin (the wallet
/// MUST refuse to inject the session into any other origin) OR when the
/// entry has a web-origin target alongside the DID audience (the wallet
/// uses the DID for the SIOP exchange but the page lives at the origin).
/// Returns `None` from `bind_origin` when no web origin is in play (e.g.
/// pure-DIDComm RP — no browser origin to bind to).
/// Construct a SessionBlob carrying a bearer-token Authorization
/// header — the SIOP driver's output shape. Cookie-free. Returns
/// `(blob, session_id, expires_at_rfc3339)`.
fn build_session_blob_with_bearer(
    bearer: String,
    bind_origin: Option<String>,
    ttl_secs: u64,
) -> (SessionBlob, String, String) {
    let session_id = Uuid::new_v4().to_string();
    let expires_at = (chrono::Utc::now() + chrono::Duration::seconds(ttl_secs as i64)).to_rfc3339();
    let blob = SessionBlob {
        session_id: session_id.clone(),
        expires_at: expires_at.clone(),
        cookies: Vec::new(),
        headers: vec![RequestHeader {
            name: "Authorization".to_string(),
            value: format!("Bearer {bearer}"),
        }],
        local_storage: Vec::new(),
        session_storage: Vec::new(),
        bind_origin,
        // SIOP id_tokens are one-shot — the wallet calls vault/proxy-login
        // again when the token expires. M3 may upgrade to BeforeExpiry once
        // the wallet has a background-refresh loop.
        refresh_hint: None,
    };
    (blob, session_id, expires_at)
}

/// Construct a SessionBlob carrying cookies — the Password POST
/// driver's output shape. No bearer header (the cookies ARE the
/// session). Returns `(blob, session_id, expires_at_rfc3339)`.
///
/// Only called from the Password POST proxy-login branch (gated on
/// `webvh` for `password_post::run_password_post`).
#[cfg(feature = "webvh")]
fn build_session_blob_with_cookies(
    cookies: Vec<vti_common::vault::CookieJarEntry>,
    bind_origin: Option<String>,
    ttl_secs: u64,
) -> (SessionBlob, String, String) {
    let session_id = Uuid::new_v4().to_string();
    let expires_at = (chrono::Utc::now() + chrono::Duration::seconds(ttl_secs as i64)).to_rfc3339();
    let blob = SessionBlob {
        session_id: session_id.clone(),
        expires_at: expires_at.clone(),
        cookies,
        headers: Vec::new(),
        local_storage: Vec::new(),
        session_storage: Vec::new(),
        bind_origin,
        // Password POST sessions can hint the wallet to refresh on 401
        // (the third party's cookie expired); the maintainer would then
        // re-run vault/proxy-login. M3 wires this hint into a real
        // wallet-side refresh loop.
        refresh_hint: Some(vti_common::vault::RefreshHint::On401),
    };
    (blob, session_id, expires_at)
}

/// Pick the first `web-origin` target on the entry. Used by the
/// password driver to derive the SessionBlob's `bind_origin` — the
/// scheme + host + port the wallet will inject cookies into. Returns
/// `None` if the entry has no web-origin target. Gated on `webvh`
/// alongside its only caller.
#[cfg(feature = "webvh")]
fn first_web_origin(targets: &[SiteTarget]) -> Option<String> {
    targets.iter().find_map(|t| match t {
        SiteTarget::WebOrigin { origin } => Some(origin.clone()),
        _ => None,
    })
}

/// Human-readable label for a [`SecretKind`] — used in error messages
/// so the consumer sees `secretKind password` instead of
/// `secretKind 0`.
fn secret_kind_label(kind: SecretKind) -> &'static str {
    match kind {
        SecretKind::Password => "password",
        SecretKind::Passkey => "passkey",
        SecretKind::OauthTokens => "oauth-tokens",
        SecretKind::DidSelfIssued => "did-self-issued",
        SecretKind::DidcommPeer => "didcomm-peer",
        SecretKind::BearerToken => "bearer-token",
        SecretKind::SshKey => "ssh-key",
        SecretKind::Custom => "custom",
    }
}

/// Translate a [`crate::operations::vault::password_post::PasswordPostError`]
/// into the canonical `vault/proxy-login/0.1` reject reason. Per the
/// spec: 4xx HTTP → `credential_rejected` (not retryable); 5xx HTTP +
/// transport failures → `target_unreachable` (retryable); bad config
/// → `malformed_request`; TOTP-not-supported → `not_implemented`.
#[cfg(feature = "webvh")]
fn password_post_error_to_reject(
    err: &crate::operations::vault::password_post::PasswordPostError,
    entry_id: &str,
) -> RejectReason {
    use crate::operations::vault::password_post::PasswordPostError;
    match err {
        PasswordPostError::NonSuccessStatus { status } if (400..500).contains(status) => {
            RejectReason::TaskFailed {
                reason: format!(
                    "vault/proxy-login:credential_rejected — third party returned HTTP {status} for entry {entry_id}"
                ),
                details: Some(serde_json::json!({
                    "status": status,
                    "remediation": "rotate the entry's password via vault/upsert/0.1",
                })),
            }
        }
        PasswordPostError::NonSuccessStatus { status } => RejectReason::TaskFailed {
            reason: format!(
                "vault/proxy-login:target_unreachable — third party returned HTTP {status}"
            ),
            details: Some(serde_json::json!({ "status": status, "retryable": true })),
        },
        PasswordPostError::Transport { url, source } => RejectReason::TaskFailed {
            reason: format!("vault/proxy-login:target_unreachable — {source} ({url})"),
            details: Some(serde_json::json!({ "url": url, "retryable": true })),
        },
        PasswordPostError::InvalidLoginUrl(msg) => RejectReason::MalformedRequest {
            reason: format!("vault/proxy-login:invalid_login_url — {msg}"),
        },
        PasswordPostError::TotpNotImplemented(msg) => RejectReason::TaskFailed {
            reason: format!("vault/proxy-login:not_implemented — {msg}"),
            details: None,
        },
        PasswordPostError::ResponseParse(msg) => RejectReason::InternalError {
            reason: format!("vault/proxy-login: response parse failure — {msg}"),
        },
    }
}

fn resolve_siop_audience(
    explicit: &Option<SiteTarget>,
    entry_targets: &[SiteTarget],
) -> Option<(String, Option<String>)> {
    // First web-origin on the entry — used as bind_origin whenever the
    // entry has one, regardless of whether the audience itself is a DID.
    let entry_origin: Option<String> = entry_targets.iter().find_map(|t| match t {
        SiteTarget::WebOrigin { origin } => Some(origin.clone()),
        _ => None,
    });

    if let Some(t) = explicit {
        return match t {
            SiteTarget::Did { did } => Some((did.clone(), entry_origin)),
            SiteTarget::WebOrigin { origin } => Some((origin.clone(), Some(origin.clone()))),
            // App targets aren't SIOP audiences.
            _ => None,
        };
    }

    // No explicit target — pick the entry's first DID target, falling
    // back to its first web-origin.
    let entry_did: Option<String> = entry_targets.iter().find_map(|t| match t {
        SiteTarget::Did { did } => Some(did.clone()),
        _ => None,
    });
    if let Some(did) = entry_did {
        return Some((did, entry_origin));
    }
    entry_origin.clone().map(|o| (o, entry_origin))
}

// Suppress an unused-import warning on the SiteTarget re-export — kept
// available for handler call-sites that materialise SiteTarget literals
// in upcoming milestones.
#[allow(dead_code)]
type _SiteTargetReexport = SiteTarget;

// M1 leaves handler-level tests to the integration suite (tests/) and to
// end-to-end verification via the plugin UI in M1.6. The vti-common
// `vault` module's tests cover the filter/sort logic in isolation; the
// dispatcher's parity-harness test asserts these URIs are wired. Real
// HTTP round-trips against the dispatcher arrive in M2 once vault/upsert
// is available to seed entries through the same authenticated channel
// (rather than reaching into the keyspace from a test, which would
// duplicate the wire-form encoder).
#[allow(dead_code)]
const _: &() = &();

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

    fn web(o: &str) -> SiteTarget {
        SiteTarget::WebOrigin {
            origin: o.to_string(),
        }
    }
    fn did(d: &str) -> SiteTarget {
        SiteTarget::Did { did: d.to_string() }
    }
    fn ios() -> SiteTarget {
        SiteTarget::IosApp {
            bundle_id: "com.example.app".into(),
            team_id: None,
        }
    }

    #[test]
    fn explicit_did_target_uses_did_as_audience_with_entry_origin_as_bind() {
        let entry_targets = vec![did("did:web:rp.example"), web("https://rp.example")];
        let (aud, bind) = resolve_siop_audience(&Some(did("did:web:rp.example")), &entry_targets)
            .expect("audience");
        assert_eq!(aud, "did:web:rp.example");
        assert_eq!(bind.as_deref(), Some("https://rp.example"));
    }

    #[test]
    fn explicit_web_origin_target_audience_equals_bind() {
        let entry_targets = vec![web("https://rp.example")];
        let (aud, bind) = resolve_siop_audience(&Some(web("https://rp.example")), &entry_targets)
            .expect("audience");
        assert_eq!(aud, "https://rp.example");
        assert_eq!(bind.as_deref(), Some("https://rp.example"));
    }

    #[test]
    fn explicit_app_target_rejects_for_siop() {
        let entry_targets = vec![did("did:web:rp.example")];
        assert!(
            resolve_siop_audience(&Some(ios()), &entry_targets).is_none(),
            "app targets aren't SIOP audiences"
        );
    }

    #[test]
    fn no_explicit_target_prefers_first_did_on_entry() {
        let entry_targets = vec![
            web("https://rp.example"),
            did("did:web:rp.example"),
            did("did:web:other"),
        ];
        let (aud, bind) = resolve_siop_audience(&None, &entry_targets).expect("audience");
        assert_eq!(aud, "did:web:rp.example", "first DID wins over later DIDs");
        assert_eq!(bind.as_deref(), Some("https://rp.example"));
    }

    #[test]
    fn no_explicit_target_falls_back_to_first_web_origin_when_no_did() {
        let entry_targets = vec![web("https://rp.example")];
        let (aud, bind) = resolve_siop_audience(&None, &entry_targets).expect("audience");
        assert_eq!(aud, "https://rp.example");
        assert_eq!(bind.as_deref(), Some("https://rp.example"));
    }

    #[test]
    fn no_audience_when_entry_has_only_app_targets() {
        let entry_targets = vec![ios()];
        assert!(
            resolve_siop_audience(&None, &entry_targets).is_none(),
            "app-only entry yields no SIOP audience"
        );
    }
}