trql-client 0.19.0

Transport-agnostic Trust Registry query client (TRQP over Trust Tasks): HTTPS, DIDComm, TSP
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
//! Transport discovery from a registry's DID document.
//!
//! A registry advertises the wires it speaks as `service` entries in its DID
//! document. This module turns those entries into a [`ServiceCapabilities`]
//! set and picks the transport to use — the highest-preference protocol
//! **both** sides speak, in the workspace order **TSP > DIDComm > HTTPS**.
//!
//! Two rules the matching deliberately follows:
//!
//! * **Match on service `type`**, never on the `#id` fragment and never on the
//!   endpoint's value shape. A TSP VID is a DID too, so "it looks like a DID,
//!   therefore DIDComm" is wrong. Fragments are arbitrary labels — the OWF
//!   reference TSP implementation names its id `#tsp-transport` while Affinidi
//!   names it `#tsp`, for the same `TSPTransport` type.
//! * **Never silently downgrade** past what the registry advertises. No shared
//!   protocol is a typed [`TrqlError::NoMatchingTransport`], not a quiet
//!   fallback to HTTPS.
//!
//! Resolution itself is the caller's job: this module is pure logic over an
//! already-resolved document, so it needs no resolver dependency and works
//! under any feature combination.
//!
//! ```rust,ignore
//! let doc: serde_json::Value = resolve(registry_did).await?;
//! let caps = ServiceCapabilities::from_document(&doc);
//! let choice = caps.select(TransportKind::compiled())?;
//! match choice.kind {
//!     TransportKind::Https => /* build HttpsTransport with choice.endpoint */,
//!     // TSP/DIDComm endpoints are the registry's *mediator* DID — resolve
//!     // onward for the transport URL, or hand it to an ATM profile.
//!     _ => { /* ... */ }
//! }
//! ```

use serde_json::Value;

use crate::error::TrqlError;
use crate::transport::TransportKind;

/// DID-document service `type` for a TSP transport endpoint.
///
/// `TSPTransport` is the OpenWallet-Foundation-Labs reference-implementation
/// convention; the ToIP TSP spec names no DID-document service type. Kept in
/// sync with `vta_sdk::protocol::matching::TSP_SERVICE_TYPE` and the registry's
/// own `didcomm::did_document::TSP_SERVICE_TYPE`.
pub const TSP_SERVICE_TYPE: &str = "TSPTransport";

/// DID-document service `type` for a DIDComm v2 mediator endpoint (W3C).
pub const DIDCOMM_SERVICE_TYPE: &str = "DIDCommMessaging";

/// DID-document service `type` for a Trust Registry's REST/TRQP surface.
///
/// Names the interface served — TRQP over REST — matching how the sibling
/// types name protocols rather than products.
pub const REST_SERVICE_TYPE: &str = "TRQPRest";

/// A VTA's REST API service `type`.
///
/// Accepted when discovering a peer because a caller may point this client at
/// a VTA-hosted endpoint, and because `vta-sdk` and `vta-service` continue to
/// use it — correctly, for VTAs. A Trust Registry must **not** advertise it:
/// see `trust_registry::didcomm::did_document::REST_SERVICE_TYPE`.
pub const VTA_REST_SERVICE_TYPE: &str = "VTARest";

/// Every service `type` that denotes a REST endpoint, in match order.
///
/// Matching a set rather than one string is what lets a consumer discover both
/// kinds of peer without either having to claim the other's identity.
///
/// [`TRUST_REGISTRY_SERVICE_TYPE`] is deliberately **absent**. It is not a
/// transport: in a VTC's document it carries a DID, and admitting it here
/// would land that DID in `ServiceCapabilities::https`, where [`select`] would
/// hand an HTTPS transport a `did:webvh:` string to POST to.
///
/// [`select`]: ServiceCapabilities::select
pub const REST_SERVICE_TYPES: [&str; 2] = [REST_SERVICE_TYPE, VTA_REST_SERVICE_TYPE];

/// DID-document service `type` for a Trust Registry, per the
/// [ToIP Trust Registry Service Profile][profile].
///
/// The type means two different things depending on whose document carries it,
/// and the difference is which kind of URI the endpoint holds:
///
/// * in a **registry's own** document — an endpoint, alongside `TRQPRest`,
///   pointing at the registry's TRQP surface;
/// * in a **VTC's** document — a referral, whose `uri` is the *DID* of the
///   registry authoritative for that community.
///
/// [`registry_referral`] draws that line. TRQP v2 recommends the referral form
/// without naming a service type, which is why this one comes from the Service
/// Profile spec rather than the protocol spec.
///
/// [profile]: https://github.com/trustoverip/tswg-trust-registry-service-profile/blob/main/spec.md
pub const TRUST_REGISTRY_SERVICE_TYPE: &str = "TrustRegistry";

/// Transports in descending preference order: TSP, then DIDComm, then HTTPS.
///
/// TSP is preferred where both sides speak it because it keeps intermediaries
/// blind to routing metadata; HTTPS is the floor.
pub const PREFERENCE_ORDER: [TransportKind; 3] = [
    TransportKind::Tsp,
    TransportKind::Didcomm,
    TransportKind::Https,
];

impl TransportKind {
    /// The DID-document service `type` that advertises this transport.
    #[must_use]
    pub fn service_type(self) -> &'static str {
        match self {
            Self::Tsp => TSP_SERVICE_TYPE,
            Self::Didcomm => DIDCOMM_SERVICE_TYPE,
            Self::Https => REST_SERVICE_TYPE,
        }
    }

    /// Whether this build can actually construct this transport.
    #[must_use]
    pub fn is_compiled(self) -> bool {
        match self {
            Self::Tsp => cfg!(feature = "tsp"),
            Self::Didcomm => cfg!(feature = "didcomm"),
            Self::Https => cfg!(feature = "https"),
        }
    }

    /// The transports compiled into this build, in preference order.
    ///
    /// Selecting against this rather than a hard-coded list means a binary
    /// built without `--features tsp` will not choose TSP and then fail to
    /// construct the transport.
    #[must_use]
    pub fn compiled() -> Vec<TransportKind> {
        PREFERENCE_ORDER
            .into_iter()
            .filter(|k| k.is_compiled())
            .collect()
    }
}

/// The transports a registry advertises, parsed from its DID document by
/// service `type`.
///
/// Each field holds the endpoint to route to for that protocol:
///
/// * `tsp` / `didcomm` — the registry's **mediator DID**, not a transport URL.
///   Both use mediator indirection; the URL lives in the mediator's own DID
///   document, so a second resolution hop is required.
/// * `https` — the registry's REST **base URL**, used directly.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ServiceCapabilities {
    /// Mediator DID advertised for TSP, if any.
    pub tsp: Option<String>,
    /// Mediator DID advertised for DIDComm, if any.
    pub didcomm: Option<String>,
    /// REST base URL advertised, if any.
    pub https: Option<String>,
}

/// The transport chosen for a registry, and where to send.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransportChoice {
    /// The selected binding.
    pub kind: TransportKind,
    /// Where to route: the registry's **mediator DID** for TSP/DIDComm (resolve
    /// onward), its **base URL** for HTTPS.
    pub endpoint: String,
}

impl ServiceCapabilities {
    /// Parse the `service` array of a resolved DID document.
    ///
    /// Unknown service types are ignored, entries missing a usable endpoint are
    /// skipped, and the first entry of each type wins — a document advertising
    /// two DIDComm services is not an error, it just has one preferred.
    #[must_use]
    pub fn from_document(doc: &Value) -> Self {
        let mut caps = Self::default();
        let Some(services) = doc.get("service").and_then(Value::as_array) else {
            return caps;
        };
        for svc in services {
            let Some(uri) = svc.get("serviceEndpoint").and_then(endpoint_uri) else {
                continue;
            };
            if uri.is_empty() {
                continue;
            }
            if service_has_type(svc, TSP_SERVICE_TYPE) {
                caps.tsp.get_or_insert(uri);
            } else if service_has_type(svc, DIDCOMM_SERVICE_TYPE) {
                caps.didcomm.get_or_insert(uri);
            } else if REST_SERVICE_TYPES.iter().any(|t| service_has_type(svc, t)) {
                caps.https.get_or_insert(uri);
            }
        }
        caps
    }

    /// The endpoint advertised for `kind`, if any.
    #[must_use]
    pub fn endpoint(&self, kind: TransportKind) -> Option<&str> {
        match kind {
            TransportKind::Tsp => self.tsp.as_deref(),
            TransportKind::Didcomm => self.didcomm.as_deref(),
            TransportKind::Https => self.https.as_deref(),
        }
    }

    /// Every transport advertised, in preference order.
    #[must_use]
    pub fn advertised(&self) -> Vec<TransportKind> {
        PREFERENCE_ORDER
            .into_iter()
            .filter(|k| self.endpoint(*k).is_some())
            .collect()
    }

    /// Choose the transport to use: the highest-preference one present in both
    /// `ours` and this capability set.
    ///
    /// Returns [`TrqlError::NoMatchingTransport`] carrying both sides' sets
    /// when the intersection is empty, so an operator can see what each side
    /// offers rather than guessing why a query failed.
    pub fn select(&self, ours: &[TransportKind]) -> Result<TransportChoice, TrqlError> {
        for kind in PREFERENCE_ORDER {
            if ours.contains(&kind)
                && let Some(endpoint) = self.endpoint(kind)
            {
                return Ok(TransportChoice {
                    kind,
                    endpoint: endpoint.to_string(),
                });
            }
        }
        Err(TrqlError::NoMatchingTransport {
            ours: ours.to_vec(),
            theirs: self.advertised(),
        })
    }
}

/// The DID this document refers a TRQP query on to, if it refers at all.
///
/// A `TrustRegistry` entry is a **referral** when its `uri` is a DID other
/// than this document's own `id` — the shape a VTC publishes to name the
/// registry authoritative for it. Any other `TrustRegistry` entry is an
/// **endpoint** (the registry describing its own surface) and yields `None`,
/// so the caller parses capabilities from the document it already has.
///
/// The `did:` test is unambiguous because the other DID-valued endpoints in a
/// document are mediator addresses, and those always carry
/// `DIDCommMessaging` or `TSPTransport`, never `TrustRegistry`.
///
/// # Following a referral
///
/// Resolve the returned DID, then parse [`ServiceCapabilities`] from *that*
/// document:
///
/// ```ignore
/// let mut doc = resolve(start_did).await?;
/// let referral = registry_referral(&doc);
/// if let Some(target) = &referral {
///     doc = resolve(target).await?;   // one hop, no loop
/// }
/// let choice = ServiceCapabilities::from_document(&doc).select(&TransportKind::compiled())?;
///
/// // Carry the starting DID through, so the answer has to confirm the hop.
/// let mut client = TrqlClient::new(transport_for(&choice)?, registry_did);
/// if referral.is_some() {
///     client = client.referred_by(start_did);
/// }
/// ```
///
/// **Cap at one hop.** TRQP's wording assumes the registry's own document
/// holds the endpoints, so a second referral is a misconfiguration rather than
/// a chain to follow, and chasing it invites cycles. This function is
/// deliberately pure and single-shot: it cannot resolve, so it cannot loop.
///
/// # This does not establish authority
///
/// A referral is a **self-assertion**. Anyone can publish a document naming
/// any registry, and nothing here checks that the named registry agrees.
/// Authority flows registry → subject, never the reverse, so following a
/// referral must be paired with closing the loop: confirming the registry's
/// answer carries an `authority_id` equal to the DID the referral started
/// from. Until then the referral has established *where to ask* and nothing
/// about the answer.
///
/// Hand the starting DID to [`TrqlClient::referred_by`] and the client
/// enforces that for you, rejecting an answer that leaves the referral
/// unconfirmed. Discovery cannot do it here: this function sees a document,
/// never a query result.
///
/// [`TrqlClient::referred_by`]: crate::TrqlClient::referred_by
#[must_use]
pub fn registry_referral(doc: &Value) -> Option<String> {
    let own_id = doc.get("id").and_then(Value::as_str);
    doc.get("service")
        .and_then(Value::as_array)?
        .iter()
        .filter(|svc| service_has_type(svc, TRUST_REGISTRY_SERVICE_TYPE))
        .filter_map(|svc| svc.get("serviceEndpoint").and_then(endpoint_uri))
        .find(|uri| uri.starts_with("did:") && Some(uri.as_str()) != own_id)
}

/// Does this service entry carry `type_`?
///
/// `type` may be a string or an array of strings per the DID Core spec.
fn service_has_type(svc: &Value, type_: &str) -> bool {
    match svc.get("type") {
        Some(Value::String(s)) => s == type_,
        Some(Value::Array(arr)) => arr.iter().any(|t| t.as_str() == Some(type_)),
        _ => false,
    }
}

/// Resolve a `serviceEndpoint` to its URI, tolerating the three shapes a DID
/// document may carry it in: a plain string (the TSP/REST convention), an
/// object with a `uri` field (DIDComm v2), or an array of either.
fn endpoint_uri(endpoint: &Value) -> Option<String> {
    match endpoint {
        Value::String(s) => Some(s.clone()),
        Value::Object(map) => map.get("uri")?.as_str().map(str::to_string),
        Value::Array(arr) => arr.iter().find_map(endpoint_uri),
        _ => None,
    }
}

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

    fn doc(services: Value) -> Value {
        json!({ "id": "did:webvh:registry.example", "service": services })
    }

    const ALL: [TransportKind; 3] = [
        TransportKind::Tsp,
        TransportKind::Didcomm,
        TransportKind::Https,
    ];

    // --- VTC → registry referral ---

    /// A VTC names the registry authoritative for it: same service `type`,
    /// but the endpoint holds a DID rather than a URL.
    #[test]
    fn a_vtc_pointing_at_a_registry_did_is_a_referral() {
        let vtc = json!({
            "id": "did:webvh:QmVtcScid:community.example",
            "service": [
                { "id": "#trust-registry", "type": "TrustRegistry",
                  "serviceEndpoint": { "uri": "did:webvh:QmRegistryScid:registry.example",
                                       "profile": "https://trustoverip.org/profiles/trqp/v2" } },
                { "id": "#didcomm", "type": "DIDCommMessaging",
                  "serviceEndpoint": { "uri": "did:web:mediator.example" } },
            ]
        });
        assert_eq!(
            registry_referral(&vtc).as_deref(),
            Some("did:webvh:QmRegistryScid:registry.example")
        );
    }

    /// The same type in the registry's own document describes its surface, so
    /// there is nowhere to be referred to — the caller uses this document.
    #[test]
    fn a_registry_describing_its_own_surface_is_not_a_referral() {
        let registry = json!({
            "id": "did:webvh:QmRegistryScid:registry.example",
            "service": [
                { "id": "#rest", "type": ["TRQPRest", "TrustRegistry"],
                  "serviceEndpoint": { "uri": "https://registry.example",
                                       "profile": "https://trustoverip.org/profiles/trqp/v2" } },
            ]
        });
        assert_eq!(registry_referral(&registry), None);
    }

    /// A document naming *itself* is a misconfiguration, not a hop: following
    /// it would resolve the same document forever.
    #[test]
    fn a_self_referential_entry_is_not_a_referral() {
        let doc = json!({
            "id": "did:webvh:QmRegistryScid:registry.example",
            "service": [
                { "id": "#trust-registry", "type": "TrustRegistry",
                  "serviceEndpoint": "did:webvh:QmRegistryScid:registry.example" },
            ]
        });
        assert_eq!(registry_referral(&doc), None);
    }

    /// The trap §5 of the design note calls out: a referral DID must never be
    /// treated as a REST base URL, or `select` hands an HTTPS transport a DID
    /// to POST to.
    #[test]
    fn a_referral_did_never_becomes_an_https_endpoint() {
        let vtc = json!({
            "id": "did:webvh:QmVtcScid:community.example",
            "service": [
                { "id": "#trust-registry", "type": "TrustRegistry",
                  "serviceEndpoint": { "uri": "did:webvh:QmRegistryScid:registry.example" } },
            ]
        });
        let caps = ServiceCapabilities::from_document(&vtc);
        assert_eq!(caps, ServiceCapabilities::default(), "{caps:?}");
        assert!(
            caps.select(&ALL).is_err(),
            "a referral advertises no transport of its own"
        );
    }

    /// Mediator entries are DID-valued too; only `TrustRegistry` ones refer.
    #[test]
    fn a_mediator_did_is_not_mistaken_for_a_referral() {
        let doc = json!({
            "id": "did:webvh:QmRegistryScid:registry.example",
            "service": [
                { "id": "#tsp", "type": "TSPTransport", "serviceEndpoint": "did:web:mediator" },
                { "id": "#didcomm", "type": "DIDCommMessaging",
                  "serviceEndpoint": { "uri": "did:web:mediator" } },
            ]
        });
        assert_eq!(registry_referral(&doc), None);
    }

    /// Both halves of the walk, in the order a caller performs them: the VTC
    /// refers, the registry's own document supplies the transports.
    #[test]
    fn one_hop_lands_on_the_registrys_capabilities() {
        let vtc = json!({
            "id": "did:webvh:QmVtcScid:community.example",
            "service": [{ "id": "#trust-registry", "type": "TrustRegistry",
                          "serviceEndpoint": { "uri": "did:webvh:QmRegistryScid:registry.example" } }]
        });
        let registry = json!({
            "id": "did:webvh:QmRegistryScid:registry.example",
            "service": [
                { "id": "#rest", "type": ["TRQPRest", "TrustRegistry"],
                  "serviceEndpoint": { "uri": "https://registry.example" } },
                { "id": "#tsp", "type": "TSPTransport", "serviceEndpoint": "did:web:mediator" },
            ]
        });

        let target = registry_referral(&vtc).expect("the VTC refers");
        assert_eq!(target, registry["id"].as_str().unwrap());
        // Second hop is not taken: the registry's document does not refer on.
        assert_eq!(registry_referral(&registry), None);

        let choice = ServiceCapabilities::from_document(&registry)
            .select(&ALL)
            .unwrap();
        assert_eq!(choice.kind, TransportKind::Tsp);
        assert_eq!(choice.endpoint, "did:web:mediator");
    }

    #[test]
    fn a_document_with_no_services_refers_nowhere() {
        assert_eq!(registry_referral(&json!({ "id": "did:webvh:x" })), None);
    }

    #[test]
    fn parses_each_service_type() {
        let caps = ServiceCapabilities::from_document(&doc(json!([
            { "id": "#tsp", "type": "TSPTransport", "serviceEndpoint": "did:web:mediator" },
            { "id": "#didcomm", "type": "DIDCommMessaging",
              "serviceEndpoint": { "uri": "did:web:mediator", "accept": ["didcomm/v2"] } },
            { "id": "#rest", "type": "TRQPRest", "serviceEndpoint": "https://registry.example" },
        ])));
        assert_eq!(caps.tsp.as_deref(), Some("did:web:mediator"));
        assert_eq!(caps.didcomm.as_deref(), Some("did:web:mediator"));
        assert_eq!(caps.https.as_deref(), Some("https://registry.example"));
    }

    /// The registry's two DID-document builders emit different endpoint
    /// shapes for the same service, so both must parse identically.
    #[test]
    fn tolerates_string_object_and_array_endpoints() {
        for endpoint in [
            json!("did:web:mediator"),
            json!({ "uri": "did:web:mediator", "accept": ["didcomm/v2"] }),
            json!([{ "uri": "did:web:mediator" }]),
        ] {
            let caps = ServiceCapabilities::from_document(&doc(json!([
                { "id": "#x", "type": "DIDCommMessaging", "serviceEndpoint": endpoint }
            ])));
            assert_eq!(caps.didcomm.as_deref(), Some("did:web:mediator"));
        }
    }

    /// Fragments are arbitrary labels; only `type` decides.
    #[test]
    fn matches_on_type_not_fragment() {
        let caps = ServiceCapabilities::from_document(&doc(json!([
            { "id": "did:x#tsp-transport", "type": "TSPTransport", "serviceEndpoint": "did:web:m" },
            { "id": "did:x#tsp", "type": "TRQPRest", "serviceEndpoint": "https://r.example" },
        ])));
        assert_eq!(caps.tsp.as_deref(), Some("did:web:m"));
        // The `#tsp`-fragmented entry is REST by type, and must be read as such.
        assert_eq!(caps.https.as_deref(), Some("https://r.example"));
    }

    #[test]
    fn type_may_be_an_array() {
        let caps = ServiceCapabilities::from_document(&doc(json!([
            { "id": "#m", "type": ["DIDCommMessaging", "Other"], "serviceEndpoint": "did:web:m" }
        ])));
        assert_eq!(caps.didcomm.as_deref(), Some("did:web:m"));
    }

    #[test]
    fn ignores_unknown_types_empty_and_missing_endpoints() {
        let caps = ServiceCapabilities::from_document(&doc(json!([
            { "id": "#a", "type": "SomethingElse", "serviceEndpoint": "https://x" },
            { "id": "#b", "type": "TRQPRest", "serviceEndpoint": "" },
            { "id": "#c", "type": "TSPTransport" },
            { "id": "#d", "type": "DIDCommMessaging", "serviceEndpoint": 42 },
        ])));
        assert_eq!(caps, ServiceCapabilities::default());
        assert!(caps.advertised().is_empty());
    }

    #[test]
    fn document_without_services_yields_nothing() {
        assert_eq!(
            ServiceCapabilities::from_document(&json!({ "id": "did:x" })),
            ServiceCapabilities::default()
        );
    }

    #[test]
    fn first_entry_of_a_type_wins() {
        let caps = ServiceCapabilities::from_document(&doc(json!([
            { "id": "#r1", "type": "TRQPRest", "serviceEndpoint": "https://first.example" },
            { "id": "#r2", "type": "TRQPRest", "serviceEndpoint": "https://second.example" },
        ])));
        assert_eq!(caps.https.as_deref(), Some("https://first.example"));
    }

    #[test]
    fn selects_the_most_preferred_shared_transport() {
        let caps = ServiceCapabilities {
            tsp: Some("did:web:m".into()),
            didcomm: Some("did:web:m".into()),
            https: Some("https://r.example".into()),
        };
        assert_eq!(caps.select(&ALL).unwrap().kind, TransportKind::Tsp);

        // We don't speak TSP -> next best.
        let choice = caps
            .select(&[TransportKind::Didcomm, TransportKind::Https])
            .unwrap();
        assert_eq!(choice.kind, TransportKind::Didcomm);
        assert_eq!(choice.endpoint, "did:web:m");

        // HTTPS-only client falls to REST and gets the URL, not the mediator.
        let choice = caps.select(&[TransportKind::Https]).unwrap();
        assert_eq!(choice.kind, TransportKind::Https);
        assert_eq!(choice.endpoint, "https://r.example");
    }

    /// A registry that advertises only DIDComm must not be reached over HTTPS
    /// merely because we can speak it — that is a silent downgrade past what
    /// the peer offered.
    #[test]
    fn no_shared_transport_is_a_typed_error_not_a_fallback() {
        let caps = ServiceCapabilities {
            didcomm: Some("did:web:m".into()),
            ..Default::default()
        };
        let err = caps.select(&[TransportKind::Https]).unwrap_err();
        match err {
            TrqlError::NoMatchingTransport { ours, theirs } => {
                assert_eq!(ours, vec![TransportKind::Https]);
                assert_eq!(theirs, vec![TransportKind::Didcomm]);
            }
            other => panic!("expected NoMatchingTransport, got {other:?}"),
        }
    }

    /// A registry advertising nothing is the same failure, and must name that
    /// it advertised nothing rather than blaming the client.
    #[test]
    fn empty_capabilities_report_an_empty_peer_set() {
        let err = ServiceCapabilities::default()
            .select(&ALL)
            .expect_err("no transports advertised");
        match err {
            TrqlError::NoMatchingTransport { theirs, .. } => assert!(theirs.is_empty()),
            other => panic!("expected NoMatchingTransport, got {other:?}"),
        }
    }

    #[test]
    fn no_matching_transport_is_not_retryable() {
        let err = ServiceCapabilities::default().select(&ALL).unwrap_err();
        assert!(!err.is_retryable());
    }

    #[test]
    fn service_types_match_the_workspace_constants() {
        assert_eq!(TransportKind::Tsp.service_type(), "TSPTransport");
        assert_eq!(TransportKind::Didcomm.service_type(), "DIDCommMessaging");
        assert_eq!(TransportKind::Https.service_type(), "TRQPRest");
    }

    /// A registry advertises `TRQPRest`; a VTA advertises `VTARest`. Both are
    /// REST endpoints, and neither has to claim the other's type for a
    /// consumer to find it.
    #[test]
    fn both_rest_type_names_are_discovered() {
        for ty in ["TRQPRest", "VTARest"] {
            let caps = ServiceCapabilities::from_document(&doc(json!([
                { "id": "#rest", "type": ty, "serviceEndpoint": "https://r.example" }
            ])));
            assert_eq!(
                caps.https.as_deref(),
                Some("https://r.example"),
                "{ty} must be recognised as REST"
            );
        }
    }

    #[test]
    fn compiled_transports_are_in_preference_order() {
        let compiled = TransportKind::compiled();
        let expected: Vec<_> = PREFERENCE_ORDER
            .into_iter()
            .filter(|k| compiled.contains(k))
            .collect();
        assert_eq!(compiled, expected);
        // The default feature set always includes HTTPS.
        #[cfg(feature = "https")]
        assert!(compiled.contains(&TransportKind::Https));
    }
}