openvtc-core 0.4.0

OpenVTC Core Library
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
//! The peer path: Trust Task documents between applicant and vetter, and
//! between a vetter and their community (design §5).
//!
//! Every vetting task carries a Data Integrity proof by its issuer — the specs
//! make it REQUIRED — even though DIDComm authcrypt already authenticates the
//! sender. The proof is what survives the transport: a statement dispute or an
//! audit reads the document, not the envelope it arrived in. [`open`] therefore
//! checks both, and that they name the same party.
//!
//! The Vetting Statement itself travels as `credential-exchange/issue/0.1`,
//! the same task a community uses to deliver a membership credential
//! ([`credential_delivery`]). Between peers it is a signed Trust Task document
//! like every other vetting leg: the vetter persona signs it for
//! `authentication`, and the statement inside keeps its own `assertionMethod`
//! proof. [`open`] checks it on arrival.

use std::str::FromStr;

use affinidi_tdk::didcomm::Message;
use affinidi_tdk::secrets_resolver::secrets::Secret;
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use trust_tasks_rs::{ErrorPayload, TrustTask, TrustTaskCode};
use uuid::Uuid;
use vta_sdk::protocols::credential_exchange::ISSUE as CREDENTIAL_ISSUE_TYPE;
use vta_sdk::trust_task_proof::{TrustTaskVmResolver, verify_trust_task_proof_with};

use crate::errors::OpenVTCError;
use crate::messaging::{MESSAGE_EXPIRY_SECS, build_didcomm_message, unix_now};

/// Why an inbound vetting document was not accepted.
#[derive(Debug, thiserror::Error)]
pub enum WireError {
    /// Not a Trust Task document, or a payload of the wrong shape.
    #[error("malformed vetting document: {0}")]
    Malformed(String),
    /// The document's `type` differs from the message's.
    #[error("document type does not match the message type")]
    TypeMismatch,
    /// The in-band `issuer` is not the transport-authenticated sender.
    #[error("document issuer is not the authenticated sender")]
    IssuerNotSender,
    /// Missing or failing proof.
    #[error("document proof did not verify")]
    Proof(String),
    /// Signed, but by someone other than the issuer.
    #[error("document is not signed by its issuer")]
    WrongSigner,
}

/// A Trust Task document on the peer path. Named here so callers need not
/// depend on `trust-tasks-rs` to hold one.
pub type Document = TrustTask<Value>;

/// A fresh `urn:uuid:` document id.
#[must_use]
pub fn new_id() -> String {
    format!("urn:uuid:{}", Uuid::new_v4())
}

fn config_error(what: &str, e: impl std::fmt::Display) -> OpenVTCError {
    OpenVTCError::Config(format!("{what}: {e}"))
}

/// A new request document from `issuer` to `recipient`.
pub fn document<P: Serialize>(
    type_uri: &str,
    issuer: &str,
    recipient: &str,
    id: String,
    payload: &P,
) -> Result<TrustTask<Value>, OpenVTCError> {
    crate::trust_task_doc::build(type_uri, issuer, recipient, id, payload)
}

/// The `#response` to `request`, threaded on it.
pub fn response<P: Serialize>(
    request: &TrustTask<Value>,
    payload: &P,
) -> Result<TrustTask<Value>, OpenVTCError> {
    let payload = serde_json::to_value(payload).map_err(|e| config_error("vetting payload", e))?;
    Ok(request.respond_with(new_id(), payload))
}

/// The `trust-task-error` refusing `request` with `code`.
pub fn refusal(
    request: &TrustTask<Value>,
    code: &str,
    message: Option<&str>,
) -> Result<TrustTask<Value>, OpenVTCError> {
    let code = TrustTaskCode::from_str(code).map_err(|e| config_error("error code", e))?;
    let mut payload = ErrorPayload::new(code);
    if let Some(message) = message {
        payload = payload.with_message(message);
    }
    let error = request.reject_with(new_id(), payload);
    serde_json::to_value(&error)
        .and_then(serde_json::from_value)
        .map_err(|e| config_error("error document", e))
}

/// Sign `doc` as its issuer, with its authentication key under
/// `proofPurpose: authentication` (see [`crate::capabilities::sign_document`]).
pub async fn sign(doc: &mut TrustTask<Value>, signer: &Secret) -> Result<(), OpenVTCError> {
    crate::capabilities::sign_document(doc, signer).await
}

/// Whether a document of `type_uri` is addressed to a **community** (a VTC)
/// rather than to another member.
///
/// A community is a Trust Tasks consumer that follows the DIDComm binding
/// (`bindings/didcomm/0.2` §2–§4): a Trust Task reaches it only inside the
/// binding envelope, and a message typed as its own task URI is refused with a
/// problem-report (VTI #1687, Keyring VTI-42). Every question this client puts
/// to a community is one of these.
///
/// The peer legs — request, session, decline and their responses, between an
/// applicant's client and a vetter's — stay typed as the task. Both ends of
/// those are OpenVTC, and a client that predates reading the envelope routes
/// on the DIDComm `type`, so moving the sender alone would silently drop every
/// request a not-yet-updated vetter receives. Reading the envelope ships first
/// (`didcomm::open_didcomm_envelope`); moving these sends is a later release.
#[must_use]
pub fn is_community_bound(type_uri: &str) -> bool {
    use vta_sdk::protocols::vetting::{
        VETTING_REVOKE_STATEMENT_TYPE, VETTING_VETTER_GRANT_TYPE, VETTING_VETTER_LIST_TYPE,
        VETTING_VETTER_PROFILE_TYPE, VETTING_VETTER_RESEND_TYPE,
    };
    if super::protocol::JoinProtocol::from_manifest_request(type_uri).is_some() {
        return true;
    }
    matches!(
        type_uri,
        VETTING_REVOKE_STATEMENT_TYPE
            | VETTING_VETTER_GRANT_TYPE
            | VETTING_VETTER_LIST_TYPE
            | VETTING_VETTER_PROFILE_TYPE
            | VETTING_VETTER_RESEND_TYPE
            | pcs::ROOT_TYPE
            | pcs::TOKENS_TYPE
            | pcs::EVENT_MODE_TYPE
            | pcs::CHALLENGE_TYPE
    )
}

/// The DIDComm `type` that carries `doc`: the binding envelope for a document
/// addressed to a community ([`is_community_bound`]), the task URI for a peer.
fn carriage_type(doc: &TrustTask<Value>) -> String {
    let type_uri = doc.type_uri.to_string();
    if is_community_bound(&type_uri) {
        crate::capabilities::TRUST_TASK_ENVELOPE_TYPE.to_string()
    } else {
        type_uri
    }
}

/// Wrap `doc` for DIDComm. The message id is the document id, and the thread is
/// the document's, so a reply correlates the same way on DIDComm and TSP.
///
/// The DIDComm `type` is `carriage_type`'s: the binding envelope toward a
/// community, the task URI toward a peer. The body is the document either way —
/// the envelope *is* the DIDComm message, not a second wrapper inside it.
pub fn to_message(doc: &TrustTask<Value>) -> Result<Message, OpenVTCError> {
    let from = doc
        .issuer
        .clone()
        .ok_or_else(|| OpenVTCError::Config("vetting document has no issuer".into()))?;
    let to = doc
        .recipient
        .clone()
        .ok_or_else(|| OpenVTCError::Config("vetting document has no recipient".into()))?;
    let body = serde_json::to_value(doc).map_err(|e| config_error("vetting document", e))?;
    let now = unix_now();
    let mut builder = Message::build(doc.id.clone(), carriage_type(doc), body)
        .from(from)
        .to(to)
        .created_time(now)
        .expires_time(now + MESSAGE_EXPIRY_SECS);
    if let Some(thread) = &doc.thread_id {
        builder = builder.thid(thread.clone());
    }
    Ok(builder.finalize())
}

/// The DIDComm message delivering a signed Vetting Statement to the applicant,
/// threaded on the session it came out of.
///
/// The delivery is a `credential-exchange/issue/0.1` Trust Task document from
/// the vetter persona to the applicant — fresh `id`, `issuedAt` — signed by
/// `signer`, the vetter persona's authentication key, through the same path as
/// every other document this client sends ([`sign`]). The statement is its
/// payload's `credential_response.credential`, carrying its own
/// `assertionMethod` proof.
pub async fn credential_delivery(
    vetter_did: &str,
    applicant_did: &str,
    statement: &Value,
    session_id: &str,
    signer: &Secret,
) -> Result<Message, OpenVTCError> {
    let mut doc = document(
        CREDENTIAL_ISSUE_TYPE,
        vetter_did,
        applicant_did,
        new_id(),
        &json!({ "credential_response": { "credential": statement } }),
    )?;
    doc.thread_id = Some(session_id.to_string());
    sign(&mut doc, signer).await?;
    to_message(&doc)
}

/// `vetting/attestation/0.1` — a vetter gives an applicant an attestation that names nobody.
///
/// The hidden path's answer to [`credential_delivery`]. The document is signed like any other, so
/// the applicant knows the delivery came from the vetter it sat with; what is *inside* carries no
/// issuer, and it is the inside that reaches the community.
///
/// The type URI is the published task's. Until the pinned `trust-tasks-rs` carries its generated
/// module, the payload is assembled here and checked against the published schema by
/// `openvtc-core`'s own fixture test — see `docs/design/vetting-hidden-vetters-pcs.md` §19.
///
/// # Errors
///
/// [`OpenVTCError::Config`] if the message cannot be built.
pub fn hidden_attestation(
    vetter_did: &str,
    applicant_did: &str,
    attestation: &Value,
    session_id: &str,
) -> Result<Message, OpenVTCError> {
    build_didcomm_message(
        HIDDEN_ATTESTATION_TYPE,
        attestation.clone(),
        vetter_did,
        applicant_did,
        Some(session_id),
    )
    .map_err(|e| config_error("attestation delivery", e))
}

/// The published type URI of `vetting/attestation/0.1`.
///
/// Inside OpenVTC's inbound filter (`trusttasks.org/spec/vetting/*`), so it reaches
/// [`crate::vetting::inbound::handle`] without a filter change.
pub const HIDDEN_ATTESTATION_TYPE: &str = "https://trusttasks.org/spec/vetting/attestation/0.1";

/// A verified inbound document.
#[derive(Debug, Clone)]
pub struct Opened<P> {
    /// The document as received.
    pub document: TrustTask<Value>,
    /// Its payload, parsed.
    pub payload: P,
}

/// Read an inbound vetting document: parse it, bind its issuer to the
/// authenticated `sender`, verify its proof, and parse the payload.
pub async fn open<P: DeserializeOwned>(
    message: &Message,
    sender: &str,
    resolver: &TrustTaskVmResolver,
) -> Result<Opened<P>, WireError> {
    let document: TrustTask<Value> = serde_json::from_value(message.body.clone())
        .map_err(|e| WireError::Malformed(e.to_string()))?;
    if document.type_uri.to_string() != message.typ {
        return Err(WireError::TypeMismatch);
    }
    if document.issuer.as_deref() != Some(sender) {
        return Err(WireError::IssuerNotSender);
    }
    let signer = verify_trust_task_proof_with(&document, resolver)
        .await
        .map_err(|e| WireError::Proof(e.cause().unwrap_or("no detail").to_string()))?;
    if signer != sender {
        return Err(WireError::WrongSigner);
    }
    let payload = serde_json::from_value(document.payload.clone())
        .map_err(|e| WireError::Malformed(e.to_string()))?;
    Ok(Opened { document, payload })
}

/// The `join-requests/manifest` request an applicant sends a community to learn
/// what it requires, in `protocol`. The payload is empty.
pub fn manifest_request(
    applicant_did: &str,
    community_did: &str,
    protocol: super::protocol::JoinProtocol,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(
        protocol.manifest_type(),
        applicant_did,
        community_did,
        new_id(),
        &json!({}),
    )
}

/// A `vtc/vetting/vetters/list/0.1` request for one page of `community_did`'s
/// vetter directory. The community refuses a caller it cannot identify, so this
/// is signed and sent as one of our personas like every other vetting task.
pub fn vetter_list_request(
    issuer: &str,
    community_did: &str,
    body: &vta_sdk::protocols::vetting::vetters::list::v0_1::Payload,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(
        vta_sdk::protocols::vetting::VETTING_VETTER_LIST_TYPE,
        issuer,
        community_did,
        new_id(),
        body,
    )
}

/// A `vtc/vetting/vetters/profile/0.1` request publishing (replacing) our
/// vetter profile at `community_did`.
pub fn vetter_profile_request(
    vetter_did: &str,
    community_did: &str,
    body: &vta_sdk::protocols::vetting::vetters::profile::v0_1::Payload,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(
        vta_sdk::protocols::vetting::VETTING_VETTER_PROFILE_TYPE,
        vetter_did,
        community_did,
        new_id(),
        body,
    )
}

/// The three Trust Tasks hidden vetting's community half serves.
///
/// Published specifications (`dtgwg-trust-tasks-tf`, branch `hidden-vetting-tasks`); the payload
/// types are written here rather than taken from `trust_tasks_rs::specs` because the generated
/// bindings are 0.22 and this workspace pins `^0.21`. `vetting::hidden::tests` validates each of
/// them against the published schema, which is the check the generated type would have carried.
pub mod pcs {
    use serde::{Deserialize, Serialize};
    use serde_json::Value;

    /// `vtc/vetting/vetters/pcs-root/0.1`.
    pub const ROOT_TYPE: &str = "https://trusttasks.org/spec/vtc/vetting/vetters/pcs-root/0.1";
    /// `vtc/vetting/vetters/pcs-tokens/0.1`.
    pub const TOKENS_TYPE: &str = "https://trusttasks.org/spec/vtc/vetting/vetters/pcs-tokens/0.1";
    /// `vtc/vetting/vetters/event-mode/0.1`.
    pub const EVENT_MODE_TYPE: &str =
        "https://trusttasks.org/spec/vtc/vetting/vetters/event-mode/0.1";
    /// `vtc/vetting/pcs-challenge/0.1`.
    pub const CHALLENGE_TYPE: &str = "https://trusttasks.org/spec/vtc/vetting/pcs-challenge/0.1";

    /// `#response` of each, which is what an inbound arm matches on.
    #[must_use]
    pub fn response_of(type_uri: &str) -> String {
        format!("{type_uri}#response")
    }

    /// What a vetter sends to enrol.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct RootRequest {
        pub label: String,
        pub id: String,
        pub request: Value,
    }

    /// What the community answers with.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct RootResponse {
        pub label: String,
        pub pre_credential: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub ext: Option<Value>,
    }

    /// One tick of the drip, asked for.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct TokensRequest {
        pub label: String,
        pub tick: u32,
        pub requests: Vec<TokenRequest>,
    }

    /// One blinded serial with its opening proof.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct TokenRequest {
        pub commitment: String,
        pub opening_proof: String,
    }

    /// One tick of the drip, served.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct TokensResponse {
        pub label: String,
        pub tick: u32,
        pub pre_credentials: Vec<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub ext: Option<Value>,
    }

    /// A vetter asking to vet at a named event, at one of the rates the community publishes.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct EventModeRequest {
        pub event_id: String,
        pub tier: String,
        pub window: EventWindow,
    }

    /// The days a vetter expects to be vetting at an event. Dates, never timestamps: an hour
    /// would say when this vetter expects to be at a desk.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct EventWindow {
        pub start_date: chrono::NaiveDate,
        pub end_date: chrono::NaiveDate,
    }

    /// Where the request stands.
    ///
    /// `pending` is the ordinary answer to a first request and is not a refusal — a refusal
    /// arrives as a `trust-task-error`. The three optional members are present only once the
    /// label is live; reading them as permission while `state` is `pending` is the mistake this
    /// shape is arranged to make awkward.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct EventModeResponse {
        pub event_id: String,
        pub state: String,
        pub tier: String,
        pub window: EventWindow,
        /// How many vetters have asked, including us. A count and never a list: who else is at
        /// the event is the anonymity set.
        pub group_size: usize,
        /// How many this community needs before the event may be approved at all.
        pub group_floor: usize,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub label: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub drip_per_tick: Option<usize>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub closes_after: Option<chrono::NaiveDate>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub ext: Option<Value>,
    }

    /// The word the community uses for a live event.
    pub const EVENT_APPROVED: &str = "approved";

    /// An applicant asking for the challenge its proof must bind. Every member is optional: the
    /// applicant is identified by `issuer`.
    #[derive(Debug, Clone, Default, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct ChallengeRequest {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub criterion_id: Option<String>,
    }

    /// The challenge, and when it stops being accepted.
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    pub struct ChallengeResponse {
        pub challenge: String,
        pub expires_at: chrono::DateTime<chrono::Utc>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub ext: Option<Value>,
    }
}

/// A `vtc/vetting/vetters/pcs-root/0.1` request: enrol this persona for a class label.
///
/// # Errors
///
/// [`OpenVTCError::Config`] if the document cannot be built.
pub fn pcs_root_request(
    vetter_did: &str,
    community_did: &str,
    body: &pcs::RootRequest,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(pcs::ROOT_TYPE, vetter_did, community_did, new_id(), body)
}

/// A `vtc/vetting/vetters/pcs-tokens/0.1` request: draw one tick of the drip.
///
/// # Errors
///
/// [`OpenVTCError::Config`] if the document cannot be built.
pub fn pcs_tokens_request(
    vetter_did: &str,
    community_did: &str,
    body: &pcs::TokensRequest,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(pcs::TOKENS_TYPE, vetter_did, community_did, new_id(), body)
}

/// A `vtc/vetting/vetters/event-mode/0.1` request: ask to vet at a named event.
///
/// # Errors
///
/// [`OpenVTCError::Config`] if the document cannot be built.
pub fn pcs_event_mode_request(
    vetter_did: &str,
    community_did: &str,
    body: &pcs::EventModeRequest,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(
        pcs::EVENT_MODE_TYPE,
        vetter_did,
        community_did,
        new_id(),
        body,
    )
}

/// A `vtc/vetting/pcs-challenge/0.1` request: ask for the nonce this submission must bind.
///
/// # Errors
///
/// [`OpenVTCError::Config`] if the document cannot be built.
pub fn pcs_challenge_request(
    applicant_did: &str,
    community_did: &str,
    criterion_id: Option<&str>,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(
        pcs::CHALLENGE_TYPE,
        applicant_did,
        community_did,
        new_id(),
        &pcs::ChallengeRequest {
            criterion_id: criterion_id.map(ToString::to_string),
        },
    )
}

/// A `vtc/vetting/vetters/resend/0.1` request asking `community_did` to
/// deliver our live vetter grant credential again.
pub fn vetter_resend_request(
    vetter_did: &str,
    community_did: &str,
) -> Result<TrustTask<Value>, OpenVTCError> {
    document(
        vta_sdk::protocols::vetting::VETTING_VETTER_RESEND_TYPE,
        vetter_did,
        community_did,
        new_id(),
        &vta_sdk::protocols::vetting::vetters::resend::v0_1::Payload::default(),
    )
}

/// Sign `document` with `persona`'s key and send it over DIDComm to its
/// recipient. Returns the document id — what a reply threads on.
///
/// `Ok` means handed to the transport, not delivered (R1.1): every step that
/// waits on the other party is driven by their reply, never by this.
pub async fn sign_and_send(
    config: &crate::config::Config,
    tdk: &affinidi_tdk::TDK,
    service: &crate::didcomm::Messaging,
    persona: crate::config::account::PersonaId,
    document: TrustTask<Value>,
) -> Result<String, OpenVTCError> {
    send_reply(
        config,
        tdk,
        service,
        super::inbound::Reply {
            persona,
            document,
            eligibility: None,
        },
    )
    .await
}

/// Present the role credentials `eligibility` names as the acceptance's
/// `eligibilityVp`, signed by `holder` for `authentication`. Done before the
/// document itself is signed, so its proof covers the presentation.
///
/// # Errors
///
/// A payload that is not an object, or a presentation that cannot be signed.
pub async fn attach_eligibility(
    document: &mut TrustTask<Value>,
    holder: &Secret,
    eligibility: super::inbound::EligibilityPresentation,
) -> Result<(), OpenVTCError> {
    let vp = vta_sdk::vetting::eligibility::build_eligibility_vp(
        holder,
        eligibility.credentials,
        &eligibility.nonce,
        &eligibility.domain,
    )
    .await
    .map_err(|e| config_error("eligibility presentation", e))?;
    document
        .payload
        .as_object_mut()
        .ok_or_else(|| OpenVTCError::Config("vetting reply payload is not an object".into()))?
        .insert("eligibilityVp".into(), vp);
    Ok(())
}

/// Sign a reply from [`super::inbound::handle`] as its persona — presenting
/// the role credential it asks for with the persona's authentication key —
/// and send it over DIDComm. Returns the document id.
///
/// `Ok` means handed to the transport, not delivered (R1.1).
pub async fn send_reply(
    config: &crate::config::Config,
    tdk: &affinidi_tdk::TDK,
    service: &crate::didcomm::Messaging,
    reply: super::inbound::Reply,
) -> Result<String, OpenVTCError> {
    let keys = config.get_persona_keys_for(reply.persona, tdk).await?;
    let mut document = reply.document;
    if let Some(eligibility) = reply.eligibility {
        attach_eligibility(&mut document, &keys.authentication.secret, eligibility).await?;
    }
    sign(&mut document, &keys.authentication.secret).await?;
    let message = to_message(&document)?;
    let (from, to) = (
        document.issuer.as_deref().unwrap_or_default(),
        document.recipient.as_deref().unwrap_or_default(),
    );
    crate::didcomm::send_message(service, config, &message, from, to)
        .await
        .map_err(|e| config_error("send vetting document", e))?;
    Ok(document.id)
}

/// Deliver a signed statement to the applicant, in a delivery document signed
/// by `signer`, the vetter persona's authentication key.
pub async fn send_statement(
    config: &crate::config::Config,
    service: &crate::didcomm::Messaging,
    vetter_did: &str,
    applicant_did: &str,
    statement: &Value,
    session_id: &str,
    signer: &Secret,
) -> Result<(), OpenVTCError> {
    let message =
        credential_delivery(vetter_did, applicant_did, statement, session_id, signer).await?;
    crate::didcomm::send_message(service, config, &message, vetter_did, applicant_did)
        .await
        .map_err(|e| config_error("send vetting statement", e))
}

/// The statement a `credential-exchange/issue` message carries, if it is an
/// identity-vetting statement rather than a community-issued credential.
///
/// This decides whether vetting claims the message, not whether it is taken:
/// it looks in the signed delivery's `payload` ([`credential_delivery`]) and
/// also at the top of the body, so a bare, unsigned statement is claimed — and
/// then refused by [`open`] — rather than handed on to the join handler. Read
/// the statement to act on from the opened document ([`statement_in`]).
#[must_use]
pub fn delivered_statement(body: &Value) -> Option<&Value> {
    body.get("payload")
        .and_then(statement_in)
        .or_else(|| statement_in(body))
}

/// The identity-vetting statement at `credential_response.credential` in an
/// issue payload, if that is what it holds: a statement credential whose
/// `credentialSubject.predicate` is the registry's `vetted/1` predicate.
///
/// Classified by predicate, never by a type string — a VSC's meaning is its
/// predicate. This only claims the delivery for the vetting handler; the
/// statement is parsed and verified in full by `verify_statement`.
///
/// A `vetted/1` statement **the community issued for itself** is not claimed
/// ([`is_community_issued`]): it records the community's own identity check,
/// not a vetter's, so it answers no vetting request and counts toward no
/// vetter threshold. It is left to the community-credential handling.
#[must_use]
pub fn statement_in(payload: &Value) -> Option<&Value> {
    let credential = payload.pointer("/credential_response/credential")?;
    (credential
        .pointer("/credentialSubject/predicate")
        .and_then(Value::as_str)
        == Some(vta_sdk::protocols::vetting::VETTED_PREDICATE)
        && !is_community_issued(credential))
    .then_some(credential)
}

/// Whether a `vetted/1` statement, unverified, is one the community issued for
/// itself: its `issuer` is the community its `object.value.community` names,
/// and the value carries none of the vetter-only members (`identityCommitment`,
/// `cardDigestMultibase`, `declaredRelationship`). A shape read only — the
/// verified form is [`crate::dtg::is_community_vetting`].
#[must_use]
pub fn is_community_issued(credential: &Value) -> bool {
    let issuer = match credential.get("issuer") {
        Some(Value::String(id)) => Some(id.as_str()),
        Some(Value::Object(o)) => o.get("id").and_then(Value::as_str),
        _ => None,
    };
    let Some(value) = credential.pointer("/credentialSubject/object/value") else {
        return false;
    };
    let community = value.get("community").and_then(Value::as_str);
    issuer.is_some()
        && issuer == community
        && [
            "identityCommitment",
            "cardDigestMultibase",
            "declaredRelationship",
        ]
        .iter()
        .all(|member| value.get(member).is_none())
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use vta_sdk::protocols::vetting::{
        VETTING_DECLINE_TYPE, VETTING_REQUEST_ERR_CAPACITY, VETTING_REQUEST_TYPE, decline, session,
    };

    /// A `did:key` Ed25519 secret from a fixed seed, `id` = `<did>#<multibase>`.
    pub(crate) fn secret(seed_byte: u8) -> Secret {
        let mut secret = Secret::generate_ed25519(None, Some(&[seed_byte; 32]));
        let public = secret.get_public_keymultibase().unwrap();
        secret.id = format!("did:key:{public}#{public}");
        secret
    }

    pub(crate) fn did(secret: &Secret) -> String {
        secret.id.split('#').next().unwrap().to_string()
    }

    /// A persona's assertionMethod key as `Config::regenerate_persona_keys`
    /// loads it: the secret id is the did:webvh verification method.
    fn webvh_persona_secret() -> Secret {
        let mut secret = Secret::generate_ed25519(None, Some(&[7u8; 32]));
        secret.id = "did:webvh:QmScid:example.com:alice#key-0".to_string();
        secret
    }

    /// Vetting documents and cards are signed locally as the persona DID — the
    /// same path reciprocal VMCs and capabilities take — so the proof names
    /// the persona's own verification method, not a VTA key or a did:key.
    #[tokio::test]
    async fn a_persona_signs_as_its_webvh_verification_method() {
        let signer = webvh_persona_secret();
        let persona = "did:webvh:QmScid:example.com:alice";
        let mut doc = document(
            VETTING_DECLINE_TYPE,
            persona,
            "did:webvh:QmScid:example.com:bob",
            new_id(),
            &decline(),
        )
        .unwrap();
        sign(&mut doc, &signer).await.unwrap();
        let signed = serde_json::to_value(&doc).unwrap();
        assert_eq!(
            signed.pointer("/proof/verificationMethod"),
            Some(&json!("did:webvh:QmScid:example.com:alice#key-0"))
        );

        let draft = vta_sdk::vetting::card::CardDraft {
            id: new_id(),
            publisher: persona.to_string(),
            audience: "did:webvh:QmScid:example.com:bob".to_string(),
            community: "did:webvh:QmScid:example.com:vtc".to_string(),
            challenge: "c".repeat(43),
            domain: "did:webvh:QmScid:example.com:vtc".to_string(),
            issued_at: chrono::Utc::now(),
            validity: chrono::Duration::minutes(10),
            claims: vec![
                session::v0_1::VettingCardClaim::try_from(
                    session::v0_1::VettingCardClaim::builder()
                        .type_("name.legal")
                        .value(json!("Alice Example"))
                        .provenance("selfAsserted"),
                )
                .unwrap(),
            ],
            identity_types: vec!["name.legal".into()],
            salt: vta_sdk::vetting::card::new_commitment_salt().unwrap(),
        };
        let card = vta_sdk::vetting::card::sign_card(draft, &signer)
            .await
            .unwrap();
        assert_eq!(
            card.pointer("/proof/verificationMethod"),
            Some(&json!("did:webvh:QmScid:example.com:alice#key-0"))
        );
    }

    fn decline() -> decline::v0_1::Payload {
        decline::v0_1::Payload::try_from(decline::v0_1::Payload::builder().request_id("r1"))
            .unwrap()
    }

    #[tokio::test]
    async fn a_signed_document_opens_for_its_sender_only() {
        let (vetter, applicant, other) = (secret(1), secret(2), secret(3));
        let mut doc = document(
            VETTING_DECLINE_TYPE,
            &did(&vetter),
            &did(&applicant),
            new_id(),
            &decline(),
        )
        .unwrap();
        sign(&mut doc, &vetter).await.unwrap();
        let message = to_message(&doc).unwrap();
        assert_eq!(message.id, doc.id);

        let resolver = TrustTaskVmResolver::did_key_only();
        let opened: Opened<decline::v0_1::Payload> =
            open(&message, &did(&vetter), &resolver).await.unwrap();
        assert_eq!(opened.payload.request_id.as_str(), "r1");

        assert!(matches!(
            open::<decline::v0_1::Payload>(&message, &did(&other), &resolver).await,
            Err(WireError::IssuerNotSender)
        ));
    }

    #[tokio::test]
    async fn an_unsigned_document_does_not_open() {
        let (vetter, applicant) = (secret(1), secret(2));
        let doc = document(
            VETTING_DECLINE_TYPE,
            &did(&vetter),
            &did(&applicant),
            new_id(),
            &decline(),
        )
        .unwrap();
        let message = to_message(&doc).unwrap();
        assert!(matches!(
            open::<decline::v0_1::Payload>(
                &message,
                &did(&vetter),
                &TrustTaskVmResolver::did_key_only()
            )
            .await,
            Err(WireError::Proof(_))
        ));
    }

    /// `vtc/vetting/vetters/resend/0.1` declares `proof` REQUIRED
    /// (trust-tasks 0.23), and is signed the same way as a personhood
    /// challenge or assertion: with the authentication key, under
    /// `proofPurpose: authentication` — both are the persona acting on their
    /// own standing rather than making a claim to be held to later.
    #[tokio::test]
    async fn a_resend_request_is_signed_under_authentication_proof_purpose() {
        let vetter = secret(3);
        let mut request = vetter_resend_request(&did(&vetter), "did:key:zVtc").unwrap();
        sign(&mut request, &vetter).await.unwrap();
        assert_eq!(
            request.proof.as_ref().unwrap().proof_purpose,
            "authentication"
        );
    }

    /// Toward a community the DIDComm `type` is the binding envelope, which a
    /// VTC requires (VTI #1687); toward a peer it stays the task URI, which a
    /// peer on an older release still routes on. The body is the document and
    /// the message id is its id either way, so a reply correlates the same.
    #[test]
    fn a_community_gets_the_envelope_and_a_peer_the_task_type() {
        use vta_sdk::protocols::vetting::{VETTING_REVOKE_STATEMENT_TYPE, vetters};
        let community_bound = [
            manifest_request(
                "did:key:zApplicant",
                "did:key:zVtc",
                crate::vetting::protocol::JoinProtocol::V0_2,
            )
            .unwrap(),
            vetter_resend_request("did:key:zVetter", "did:key:zVtc").unwrap(),
            vetter_list_request(
                "did:key:zApplicant",
                "did:key:zVtc",
                &vetters::list::v0_1::Payload::try_from(vetters::list::v0_1::Payload::builder())
                    .unwrap(),
            )
            .unwrap(),
            document(
                VETTING_REVOKE_STATEMENT_TYPE,
                "did:key:zVetter",
                "did:key:zVtc",
                new_id(),
                &json!({}),
            )
            .unwrap(),
        ];
        for doc in &community_bound {
            let message = to_message(doc).unwrap();
            assert_eq!(
                message.typ,
                crate::capabilities::TRUST_TASK_ENVELOPE_TYPE,
                "{} must ride the envelope",
                doc.type_uri
            );
            assert_eq!(message.id, doc.id);
            assert_eq!(message.body, serde_json::to_value(doc).unwrap());
            assert!(is_community_bound(&doc.type_uri.to_string()));
        }

        // Hidden vetting's four community-side tasks go to the community too. They were written
        // before the envelope rule and name a string constant rather than a generated type, so
        // nothing else would notice them going task-typed — and a community refuses that.
        for type_uri in [
            pcs::ROOT_TYPE,
            pcs::TOKENS_TYPE,
            pcs::EVENT_MODE_TYPE,
            pcs::CHALLENGE_TYPE,
        ] {
            let doc = document(
                type_uri,
                "did:key:zVetter",
                "did:key:zVtc",
                new_id(),
                &json!({}),
            )
            .unwrap();
            assert_eq!(
                to_message(&doc).unwrap().typ,
                crate::capabilities::TRUST_TASK_ENVELOPE_TYPE,
                "{type_uri} must ride the envelope"
            );
        }
        // The attestation is a peer leg: vetter to applicant.
        assert!(!is_community_bound(HIDDEN_ATTESTATION_TYPE));

        for type_uri in [VETTING_REQUEST_TYPE, VETTING_DECLINE_TYPE] {
            let doc = document(
                type_uri,
                "did:key:zApplicant",
                "did:key:zVetter",
                new_id(),
                &json!({}),
            )
            .unwrap();
            let message = to_message(&doc).unwrap();
            assert_eq!(message.typ, type_uri, "a peer leg stays typed as its task");
        }
        // A response is never community-bound: this client answers peers only.
        let request = manifest_request(
            "did:key:zApplicant",
            "did:key:zVtc",
            crate::vetting::protocol::JoinProtocol::V0_2,
        )
        .unwrap();
        let reply = response(&request, &json!({})).unwrap();
        assert!(!is_community_bound(&reply.type_uri.to_string()));
    }

    #[test]
    fn responses_and_refusals_thread_on_the_request() {
        let request = document(
            VETTING_REQUEST_TYPE,
            "did:key:zApplicant",
            "did:key:zVetter",
            new_id(),
            &json!({}),
        )
        .unwrap();
        let reply = response(&request, &json!({ "requestId": "r1" })).unwrap();
        assert_eq!(reply.thread_id.as_deref(), Some(request.id.as_str()));
        assert_eq!(reply.issuer.as_deref(), Some("did:key:zVetter"));
        assert!(reply.type_uri.to_string().ends_with("#response"));

        let refused = refusal(&request, VETTING_REQUEST_ERR_CAPACITY, None).unwrap();
        assert_eq!(refused.thread_id.as_deref(), Some(request.id.as_str()));
        assert_eq!(refused.payload["code"], VETTING_REQUEST_ERR_CAPACITY);
        assert!(
            crate::messaging::is_trust_task_error_type(&refused.type_uri.to_string()),
            "the inbound router must recognise it"
        );
    }

    fn a_statement() -> Value {
        json!({
            "credentialSubject": {
                "predicate": vta_sdk::protocols::vetting::VETTED_PREDICATE
            }
        })
    }

    /// The statement's delivery is a Trust Task document signed by the vetter
    /// persona for `authentication`, addressed to the applicant and threaded on
    /// the session, and it opens for the vetter only. An unsigned one — the
    /// bare body this used to send — is still claimed, and refused.
    #[tokio::test]
    async fn a_statement_delivery_is_signed_for_authentication_and_refused_unsigned() {
        let (vetter, applicant, other) = (secret(1), secret(2), secret(3));
        let statement = a_statement();
        let message = credential_delivery(
            &did(&vetter),
            &did(&applicant),
            &statement,
            "urn:uuid:session",
            &vetter,
        )
        .await
        .unwrap();
        assert_eq!(message.typ, CREDENTIAL_ISSUE_TYPE);
        assert_eq!(message.thid.as_deref(), Some("urn:uuid:session"));
        let body = &message.body;
        assert_eq!(body["type"], CREDENTIAL_ISSUE_TYPE);
        assert_eq!(body["issuer"], did(&vetter));
        assert_eq!(body["recipient"], did(&applicant));
        assert!(body["id"].as_str().unwrap().starts_with("urn:uuid:"));
        assert!(body.get("issuedAt").is_some());
        assert_eq!(
            body.pointer("/proof/proofPurpose"),
            Some(&json!("authentication"))
        );
        assert_eq!(delivered_statement(body), Some(&statement));

        let resolver = TrustTaskVmResolver::did_key_only();
        let opened: Opened<Value> = open(&message, &did(&vetter), &resolver).await.unwrap();
        assert_eq!(statement_in(&opened.payload), Some(&statement));
        assert!(matches!(
            open::<Value>(&message, &did(&other), &resolver).await,
            Err(WireError::IssuerNotSender)
        ));

        // The same document, unsigned.
        let mut unsigned = message.clone();
        unsigned.body.as_object_mut().unwrap().remove("proof");
        assert!(matches!(
            open::<Value>(&unsigned, &did(&vetter), &resolver).await,
            Err(WireError::Proof(_))
        ));
        // The bare body: claimed, then refused.
        let bare = crate::messaging::build_didcomm_message(
            CREDENTIAL_ISSUE_TYPE,
            json!({ "credential_response": { "credential": statement } }),
            &did(&vetter),
            &did(&applicant),
            Some("urn:uuid:session"),
        )
        .unwrap();
        assert!(delivered_statement(&bare.body).is_some());
        assert!(
            open::<Value>(&bare, &did(&vetter), &resolver)
                .await
                .is_err()
        );
    }

    #[test]
    fn only_identity_vetting_statements_are_picked_out_of_an_issue() {
        let statement = a_statement();
        let body = json!({ "credential_response": { "credential": statement } });
        assert!(delivered_statement(&body).is_some());
        assert!(delivered_statement(&json!({ "payload": body })).is_some());
        let vmc = json!({ "credential_response": { "credential": {
            "type": ["VerifiableCredential", "MembershipCredential"]
        } } });
        assert!(delivered_statement(&vmc).is_none());
    }

    /// The community recording its own identity check is not a vetter's
    /// statement: the vetting handler leaves it alone.
    #[test]
    fn a_community_issued_vetted_statement_is_not_a_vetter_statement() {
        let statement = |issuer: &str, vetter_members: bool| {
            let mut value = json!({
                "community": "did:example:c",
                "method": "video",
                "claimsVerified": ["name.legal"],
                "livenessConfirmed": true,
            });
            if vetter_members {
                value["identityCommitment"] = json!("zC");
                value["cardDigestMultibase"] = json!("zD");
                value["declaredRelationship"] = json!("none");
            }
            json!({ "credential_response": { "credential": {
                "issuer": issuer,
                "credentialSubject": {
                    "predicate": vta_sdk::protocols::vetting::VETTED_PREDICATE,
                    "object": { "value": value }
                }
            } } })
        };
        let own = statement("did:example:c", false);
        assert!(is_community_issued(
            &own["credential_response"]["credential"]
        ));
        assert!(statement_in(&own).is_none());
        // A vetter's statement for the same community is claimed.
        assert!(statement_in(&statement("did:example:v", true)).is_some());
        // Bare of vetter members but not from the community: still claimed, and
        // refused by the vetter-path checks rather than waved through here.
        assert!(statement_in(&statement("did:example:v", false)).is_some());
        // The community's DID with vetter members: a vetter-shaped statement.
        assert!(statement_in(&statement("did:example:c", true)).is_some());
    }
}