did-hosting-common 0.10.1

DID Hosting Common, Common methods and structs related to WebVH Content
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
use std::sync::Arc;

use affinidi_tdk::dids::{DID, KeyType};
use affinidi_tdk::secrets_resolver::secrets::Secret;
use didwebvh_rs::DIDWebVHState;
use didwebvh_rs::parameters::Parameters;
use serde_json::json;

use crate::error::{Result, WebVHError};

/// Generate a new Ed25519 did:key identity.
///
/// Returns `(did, secret)` where `did` is the DID string and `secret`
/// is the signing key needed for authentication and DID operations.
pub fn generate_ed25519_identity() -> Result<(String, Secret)> {
    DID::generate_did_key(KeyType::Ed25519)
        .map_err(|e| WebVHError::DIDComm(format!("failed to generate did:key: {e}")))
}

/// Encode a server URL into the host component used in `did:webvh` identifiers.
///
/// Ports are percent-encoded (`:` becomes `%3A`), matching the did:webvh spec.
///
/// # Examples
/// - `http://localhost:8085` -> `localhost%3A8085`
/// - `https://example.com`   -> `example.com`
pub fn encode_host(server_url: &str) -> Result<String> {
    let parsed = url::Url::parse(server_url)
        .map_err(|e| WebVHError::DIDComm(format!("invalid server URL: {e}")))?;

    let host_str = parsed
        .host_str()
        .ok_or_else(|| WebVHError::DIDComm("server URL has no host".into()))?;

    Ok(match parsed.port() {
        Some(port) => format!("{host_str}%3A{port}"),
        None => host_str.to_string(),
    })
}

/// Construct a `did:web` identifier from a server URL and mnemonic.
///
/// Follows the did:web method spec:
/// - `did:web:example.com` for the root DID (mnemonic = `.well-known`)
/// - `did:web:host:path` for path-based DIDs
/// - Ports are percent-encoded (`:` → `%3A`)
/// - Path separators (`/`) become `:`
///
/// # Examples
/// ```
/// # use did_hosting_common::did::build_did_web_id;
/// assert_eq!(build_did_web_id("https://example.com", "my-did").unwrap(), "did:web:example.com:my-did");
/// assert_eq!(build_did_web_id("https://example.com", ".well-known").unwrap(), "did:web:example.com");
/// ```
pub fn build_did_web_id(server_url: &str, mnemonic: &str) -> Result<String> {
    let host = encode_host(server_url)?;
    if mnemonic == ".well-known" {
        Ok(format!("did:web:{host}"))
    } else {
        let path = mnemonic.replace('/', ":");
        Ok(format!("did:web:{host}:{path}"))
    }
}

/// Options for building a DID document beyond the required signing key.
#[derive(Default)]
pub struct DidDocumentOptions<'a> {
    /// X25519 key agreement public key (multibase-encoded). When set, a
    /// `keyAgreement` verification method (`#key-1`) is added to the document.
    /// Required for DIDComm encrypted messaging.
    pub key_agreement_multibase: Option<&'a str>,
    /// Mediator DID or URL for the `DIDCommMessaging` service endpoint.
    /// When set, a `DIDCommMessaging` service is added so other parties
    /// know how to route messages to this DID.
    pub mediator_endpoint: Option<&'a str>,
    /// Mediator DID (or URL) for the `TSPTransport` service endpoint.
    /// When set, a `TSPTransport` service (`#tsp`) is added so other
    /// parties know they can reach this DID over the Trust Spanning
    /// Protocol. Emitted *before* `DIDCommMessaging` to match the VTA
    /// webvh templates' canonical preference order (TSP over DIDComm) —
    /// see `resolve_transport` / `didcomm_profile::resolve_mediator_did`.
    pub tsp_endpoint: Option<&'a str>,
}

/// Advertise a `WebVHHosting` service at `uri` on a document built by
/// [`build_did_document`], after any transport services it already has.
///
/// The shape is exactly what VTI's `did-host-http` template emits, and what a
/// VTA's `servers add` reads: an object endpoint carrying `uri`, not a bare
/// string.
///
/// Keyring VTI-18. A self-managed hosting daemon minted without a mediator
/// had **no services at all** — the transport services both need one — so it
/// served DIDs perfectly well and no VTA could register it: `servers add`
/// requires a `TSPTransport`, `DIDCommMessaging` or `WebVHHosting` entry. A
/// hosting daemon serves HTTP whatever else it speaks, so this entry is simply
/// true of it and needs nothing the operator has not already configured.
///
/// Appended rather than folded into [`DidDocumentOptions`]: that struct is
/// public and built by literal, so a new field would break every caller.
/// Appending also keeps the canonical order — TSP, then DIDComm, then HTTP.
pub fn add_webvh_hosting_service(doc: &mut serde_json::Value, uri: &str) {
    let did_id = doc["id"].as_str().unwrap_or_default().to_string();
    let entry = json!({
        "id": format!("{did_id}#webvh-hosting"),
        "type": "WebVHHosting",
        "serviceEndpoint": { "uri": uri },
    });
    match doc.get_mut("service").and_then(|s| s.as_array_mut()) {
        Some(services) => services.push(entry),
        None => doc["service"] = json!([entry]),
    }
}

/// Advertise a `TrustTaskHTTPS` service at `base_uri` on a document built by
/// [`build_did_document`] (typically alongside [`add_webvh_hosting_service`]).
///
/// `base_uri` is the Trust-Task **base**, not the request URL — HTTPS binding
/// 0.2 §6 makes the advertised endpoint the base and the caller composes
/// `<base>/trust-tasks`. The control plane nests its whole API under `/api`
/// off the origin root (`did-hosting-control`'s `routes/mod.rs`), so
/// `base_uri` is `{public_url}/api`; this matches every `vta-sdk`
/// `did-host-http*` template exactly (`vta-sdk`'s
/// `TRUST_TASK_HTTPS_SERVICE_TYPE`).
///
/// `WebVHHosting` is not this endpoint — it says where DID *documents* are
/// served, a different claim — so without this entry a VTA either can't find
/// the Trust-Task endpoint, or falls back to posting Trust Tasks at the
/// hosting origin, which never agreed to accept them. A VTA-provisioned DID
/// gets this entry for free from the `vta-sdk` template; a **self-managed**
/// daemon builds its own document locally instead, so it needs the same
/// explicit fix `add_webvh_hosting_service` got for `WebVHHosting` (Keyring
/// VTI-18 sibling).
///
/// Callers should gate this on [`is_https_or_loopback`] first — a VTA must
/// never be told to POST Trust Tasks over plaintext HTTP to a real host.
pub fn add_trust_task_https_service(doc: &mut serde_json::Value, base_uri: &str) {
    let did_id = doc["id"].as_str().unwrap_or_default().to_string();
    let entry = json!({
        "id": format!("{did_id}#trust-tasks"),
        "type": "TrustTaskHTTPS",
        "serviceEndpoint": base_uri,
    });
    match doc.get_mut("service").and_then(|s| s.as_array_mut()) {
        Some(services) => services.push(entry),
        None => doc["service"] = json!([entry]),
    }
}

/// Advertise a `SignInPortal` service at `endpoint` on a document built by
/// [`build_did_document`]: the page where this service's people sign in with
/// a wallet (contract C4, VTI-LNK-102).
///
/// A wallet reading a sign-in trigger link compares the origin of
/// `serviceEndpoint` with the page the link was activated from, and refuses
/// a mismatch (`wrong-origin`, VTI-LNK-105). So `endpoint` must be the
/// console's login page on the origin that serves it; for a hosting daemon
/// that is `{origin}/login`. The `auth/oob/*` tasks themselves travel over
/// the `TrustTaskHTTPS` service ([`add_trust_task_https_service`]).
///
/// Callers should gate this on [`is_sign_in_portal_url`] — stricter than the
/// `TrustTaskHTTPS` entry's [`is_https_or_loopback`]: `https` only.
pub fn add_sign_in_portal_service(doc: &mut serde_json::Value, endpoint: &str) {
    let did_id = doc["id"].as_str().unwrap_or_default().to_string();
    let entry = json!({
        "id": format!("{did_id}#sign-in-portal"),
        "type": SERVICE_TYPE_SIGN_IN_PORTAL,
        "serviceEndpoint": endpoint,
    });
    match doc.get_mut("service").and_then(|s| s.as_array_mut()) {
        Some(services) => services.push(entry),
        None => doc["service"] = json!([entry]),
    }
}

/// Whether `uri` may be advertised as a `SignInPortal` (contract C4), and so
/// serve wallet sign-in with a trigger link: `https://` with a host, and no
/// userinfo.
///
/// Stricter than [`is_https_or_loopback`] on purpose: the portal's origin is
/// what `auth/oob/*` binds a sign-in to, and the published `Origin` type
/// (`trust_tasks_rs::specs::auth::oob`) admits `https://` only, so a plain-
/// http portal — even on loopback — could never complete a conforming
/// sign-in (a wallet refuses to approve one). The control plane applies the
/// same rule to its `public_url` before it serves the family at all
/// (`did-hosting-control`'s `oob::http::portal_origin`).
pub fn is_sign_in_portal_url(uri: &str) -> bool {
    url::Url::parse(uri).is_ok_and(|url| {
        url.scheme() == "https"
            && url.host().is_some()
            && url.username().is_empty()
            && url.password().is_none()
    })
}

/// Whether `uri` is safe to advertise as a `TrustTaskHTTPS` endpoint.
///
/// `https://` always qualifies. Plain `http://` qualifies only for loopback
/// (`localhost`, `127.0.0.1`, `[::1]`) — acceptable for a local dev daemon,
/// never for a real deployment a VTA might actually route Trust Tasks to.
///
/// The URL is parsed and its host compared exactly, never by text prefix:
/// `http://localhost.evil.example` and `http://127.0.0.1.evil.example` are
/// not loopback, and neither is a URL carrying userinfo. `127.0.0.0/8`
/// counts, as every address in it is loopback.
pub fn is_https_or_loopback(uri: &str) -> bool {
    let Ok(url) = url::Url::parse(uri) else {
        return false;
    };
    if !url.username().is_empty() || url.password().is_some() {
        return false;
    }
    match url.scheme() {
        "https" => url.host().is_some(),
        "http" => match url.host() {
            Some(url::Host::Domain(d)) => d.eq_ignore_ascii_case("localhost"),
            Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
            Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
            None => false,
        },
        _ => false,
    }
}

/// Build a standard DID document with `{SCID}` placeholders.
///
/// The returned JSON value uses the did:webvh identifier format with an
/// Ed25519 verification method at `#key-0`. Additional keys and services
/// can be added via [`DidDocumentOptions`].
///
/// An empty mnemonic — or `.well-known`, the slot the root DID is *stored*
/// under — builds the **root** DID for the host: `did:webvh:{SCID}:<host>`
/// with no path segments, which per did:webvh resolves at
/// `https://<host>/.well-known/did.jsonl`.
///
/// `.well-known` is a storage location, not part of the identifier. Emitting it
/// inside the DID produces an id no conforming resolver can round-trip: it maps
/// the pathless form to `/.well-known/did.jsonl` implicitly, so on the way back
/// it strips the suffix and then rejects the document because the `id` inside no
/// longer matches the DID it was asked to resolve —
///
/// ```text
/// DID being resolved (did:webvh:Qm…:did.example.com)
/// does not match the top-level 'id' in any DIDDoc version
/// ```
///
/// The document serves fine; the *identifier* is what fails to round-trip. This
/// mirrors [`build_did_web_id`] and `setup_recipe::apply::hosting_url_for`,
/// which both already fold `.well-known` to the root.
pub fn build_did_document(
    host: &str,
    mnemonic: &str,
    public_key_multibase: &str,
    opts: &DidDocumentOptions<'_>,
) -> serde_json::Value {
    let did_path = if mnemonic == ".well-known" {
        String::new()
    } else {
        mnemonic.replace('/', ":")
    };
    let did_id = if did_path.is_empty() {
        format!("did:webvh:{{SCID}}:{host}")
    } else {
        format!("did:webvh:{{SCID}}:{host}:{did_path}")
    };

    let mut vm = vec![json!({
        "id": format!("{did_id}#key-0"),
        "type": "Multikey",
        "controller": &did_id,
        "publicKeyMultibase": public_key_multibase,
    })];

    // @context matches the upstream webvh VTA templates' output (W3C DID v1 +
    // CID v1). Keep these two in sync: the setup wizards have the VTA render
    // most webvh DIDs via the template, but bootstrap_did() still builds the
    // `.well-known` root DID locally with this helper — both shapes must be
    // identical so callers and resolvers don't see drift.
    let mut doc = json!({
        "@context": [
            "https://www.w3.org/ns/did/v1",
            "https://www.w3.org/ns/cid/v1",
        ],
        "id": did_id,
        "authentication": [format!("{did_id}#key-0")],
        "assertionMethod": [format!("{did_id}#key-0")],
    });

    // Add X25519 key agreement key
    if let Some(ka_key) = opts.key_agreement_multibase {
        vm.push(json!({
            "id": format!("{did_id}#key-1"),
            "type": "Multikey",
            "controller": &did_id,
            "publicKeyMultibase": ka_key,
        }));
        doc["keyAgreement"] = json!([format!("{did_id}#key-1")]);
    }

    doc["verificationMethod"] = json!(vm);

    // Add services. Service ids (`#tsp`, `#vta-didcomm`) and the
    // ordering (TSP first, then DIDComm) match the VTA webvh templates
    // — see `vta-sdk`'s `did-host-*didcomm.json`. The `#vta-didcomm`
    // fragment is deliberate (not the older `#didcomm` convention).
    let mut services = vec![];
    if let Some(tsp) = opts.tsp_endpoint {
        // `TSPTransport`'s `serviceEndpoint` is a bare string (the
        // mediator VID), unlike DIDComm's array-of-objects shape.
        services.push(json!({
            "id": format!("{did_id}#tsp"),
            "type": "TSPTransport",
            "serviceEndpoint": tsp,
        }));
    }
    if let Some(mediator) = opts.mediator_endpoint {
        services.push(json!({
            "id": format!("{did_id}#vta-didcomm"),
            "type": "DIDCommMessaging",
            "serviceEndpoint": [{
                "accept": ["didcomm/v2"],
                "uri": mediator,
            }],
        }));
    }
    if !services.is_empty() {
        doc["service"] = json!(services);
    }

    doc
}

// ---------------------------------------------------------------------------
// Service-type introspection
// ---------------------------------------------------------------------------

/// HTTP DID-log hosting endpoint (`did-host-http*` templates).
pub const SERVICE_TYPE_WEBVH_HOSTING: &str = "WebVHHosting";
/// Legacy read-only alias for [`SERVICE_TYPE_WEBVH_HOSTING`]. Never written;
/// accepted on read.
pub const SERVICE_TYPE_WEBVH_HOSTING_LEGACY: &str = "WebVHHostingService";
/// Trust Spanning Protocol transport (`#tsp`).
pub const SERVICE_TYPE_TSP: &str = "TSPTransport";
/// DIDComm v2 transport (`#vta-didcomm`).
pub const SERVICE_TYPE_DIDCOMM: &str = "DIDCommMessaging";
/// Trust-Task HTTPS binding endpoint (`#trust-tasks`), HTTPS binding 0.2 §6.
/// Kept in sync with `vta-sdk`'s `TRUST_TASK_HTTPS_SERVICE_TYPE`.
pub const SERVICE_TYPE_TRUST_TASK_HTTPS: &str = "TrustTaskHTTPS";
/// The page where people sign in with a wallet (`#sign-in-portal`), contract
/// C4 / VTI-LNK-102.
pub const SERVICE_TYPE_SIGN_IN_PORTAL: &str = "SignInPortal";

/// True for the services the did:webvh spec *implies* rather than the
/// operator declaring.
///
/// A conforming did:webvh resolver synthesises `#whois`
/// (`LinkedVerifiablePresentation`) and `#files` (`relativeRef`) into every
/// resolved document when they aren't already present — see
/// `didwebvh-rs`'s `resolve::implicit::update_implicit_services`. They are
/// therefore on 100% of resolved webvh DIDs and carry no operator intent.
///
/// This matters because the two read paths disagree about them. Reading a
/// stored `did.jsonl` (the DID-list badge cache) never sees them; resolving
/// the DID (the registry probe, the control-plane self-check) always does.
/// Left unfiltered, the same DID renders a spurious `Other` badge on the
/// Servers list and none on the DID list.
///
/// Matched on the `id` fragment, which is how the resolver itself detects
/// them — an operator who declares a `LinkedVerifiablePresentation` under
/// some other fragment genuinely is advertising something, and keeps its
/// badge.
pub fn is_implicit_webvh_service(service_id: &str) -> bool {
    service_id.ends_with("#whois") || service_id.ends_with("#files")
}

/// Extract the `type` of every entry in a DID document's `service` array.
///
/// The single canonical reader for "what does this document advertise",
/// shared by the DID-list badge cache, the registry's per-instance
/// capability probe, and the control plane's advertised-vs-enabled check.
/// It is the read-side counterpart to [`build_did_document`], which writes
/// the same services.
///
/// Handles both shapes the ecosystem's templates emit: a bare string
/// (`"type": "TSPTransport"`, the webvh `did-host-*` templates) and a
/// single-element array (`"type": ["DIDCommMessaging"]`, `ai-agent-peer`).
/// A service carrying several types contributes all of them.
///
/// Order is the document's own — the webvh templates render hosting, then
/// TSP, then DIDComm, so callers that surface the first match inherit the
/// same TSP-over-DIDComm preference [`crate::server::didcomm_profile::resolve_transport`]
/// applies. Duplicates are collapsed, keeping first occurrence.
///
/// Spec-implied services (`#whois`, `#files`) are skipped — see
/// [`is_implicit_webvh_service`]. Without this, resolved documents would
/// always report two extra types that no operator declared, and the stored-log
/// and resolved read paths would disagree about the same DID.
///
/// Returns an empty vector when `service` is absent, not an array, or
/// contains no usable `type`. Callers that need to distinguish "no services"
/// from "document unavailable" should wrap the result in an `Option`
/// themselves — see `DidRecord::services`.
pub fn service_types_from_doc(doc: &serde_json::Value) -> Vec<String> {
    let Some(services) = doc.get("service").and_then(|s| s.as_array()) else {
        return Vec::new();
    };

    let mut out: Vec<String> = Vec::new();
    let mut push = |t: &str| {
        if !t.is_empty() && !out.iter().any(|seen| seen == t) {
            out.push(t.to_string());
        }
    };

    for svc in services {
        let id = svc.get("id").and_then(|v| v.as_str()).unwrap_or("");
        if is_implicit_webvh_service(id) {
            continue;
        }
        match svc.get("type") {
            Some(serde_json::Value::String(t)) => push(t),
            Some(serde_json::Value::Array(types)) => {
                for t in types.iter().filter_map(|t| t.as_str()) {
                    push(t);
                }
            }
            _ => {}
        }
    }
    out
}

/// True when `types` contains a service advertising the TSP transport.
pub fn advertises_tsp(types: &[String]) -> bool {
    types.iter().any(|t| t == SERVICE_TYPE_TSP)
}

/// True when `types` contains a service advertising the DIDComm transport.
pub fn advertises_didcomm(types: &[String]) -> bool {
    types.iter().any(|t| t == SERVICE_TYPE_DIDCOMM)
}

/// Create a WebVH log entry from a DID document and signing secret.
///
/// Returns `(scid, jsonl)` where:
/// - `scid` is the self-certifying identifier derived from the log entry
/// - `jsonl` is the serialized log entry ready for upload to the server
pub async fn create_log_entry(
    did_document: &serde_json::Value,
    secret: &Secret,
) -> Result<(String, String)> {
    let public_key_multibase = secret
        .get_public_keymultibase()
        .map_err(|e| WebVHError::DIDComm(format!("failed to get public key multibase: {e}")))?;

    // didwebvh-rs 0.3 requires the signing key's verification_method to
    // contain '#' followed by the multibase public key.
    let mut signing_key = secret.clone();
    if !signing_key.id.contains('#') {
        signing_key.id = format!("did:key:{public_key_multibase}#{public_key_multibase}");
    }

    let mut state = DIDWebVHState::default();
    let params = Parameters {
        update_keys: Some(Arc::new(vec![public_key_multibase.into()])),
        ..Default::default()
    };

    state
        .create_log_entry(None, did_document, &params, &signing_key)
        .await
        .map_err(|e| WebVHError::DIDComm(format!("failed to create WebVH log entry: {e}")))?;

    let scid = state.scid().to_string();

    let lines: Vec<String> = state
        .log_entries()
        .iter()
        .map(|e| {
            serde_json::to_string(&e.log_entry)
                .map_err(|e| WebVHError::DIDComm(format!("failed to serialize log entry: {e}")))
        })
        .collect::<Result<Vec<_>>>()?;
    let jsonl = lines.join("\n");

    Ok((scid, jsonl))
}

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

    /// Keyring VTI-18: a self-managed daemon with no mediator used to mint a
    /// document with no `service` member at all. The hosting entry alone must
    /// be enough to create one.
    #[test]
    fn hosting_is_advertised_on_a_document_with_no_services() {
        let mut doc =
            build_did_document("example.com", ".well-known", "z6MkKey", &Default::default());
        assert!(
            doc.get("service").is_none(),
            "precondition: no transport, no services"
        );

        add_webvh_hosting_service(&mut doc, "https://example.com");

        let services = doc["service"]
            .as_array()
            .expect("a service array now exists");
        assert_eq!(services.len(), 1);
        // Exactly the shape VTI's `did-host-http` template emits and a VTA's
        // `servers add` reads: an object endpoint carrying `uri`.
        assert_eq!(services[0]["type"], "WebVHHosting");
        assert_eq!(
            services[0]["serviceEndpoint"],
            json!({ "uri": "https://example.com" })
        );
        assert_eq!(
            services[0]["id"],
            json!(format!("{}#webvh-hosting", doc["id"].as_str().unwrap()))
        );
    }

    /// With transports present it goes last, keeping the canonical order —
    /// TSP, then DIDComm, then HTTP — rather than displacing either.
    #[test]
    fn hosting_goes_after_the_transport_services() {
        let mut doc = build_did_document(
            "example.com",
            ".well-known",
            "z6MkKey",
            &DidDocumentOptions {
                key_agreement_multibase: Some("z6LSKa"),
                mediator_endpoint: Some("did:web:mediator.example"),
                tsp_endpoint: Some("did:web:mediator.example"),
            },
        );
        add_webvh_hosting_service(&mut doc, "https://example.com");

        let types: Vec<&str> = doc["service"]
            .as_array()
            .unwrap()
            .iter()
            .map(|s| s["type"].as_str().unwrap())
            .collect();
        assert_eq!(types, ["TSPTransport", "DIDCommMessaging", "WebVHHosting"]);
    }

    /// The `TrustTaskHTTPS` sibling of the VTI-18 fix above: a self-managed
    /// daemon builds its document locally rather than through a `vta-sdk`
    /// template, so it needs the same explicit entry the template would
    /// otherwise have supplied for free.
    #[test]
    fn trust_task_https_is_advertised_with_the_api_base_as_endpoint() {
        let mut doc =
            build_did_document("example.com", ".well-known", "z6MkKey", &Default::default());
        add_webvh_hosting_service(&mut doc, "https://example.com");
        add_trust_task_https_service(&mut doc, "https://example.com/api");

        let services = doc["service"].as_array().expect("service array");
        assert_eq!(services.len(), 2);
        assert_eq!(services[1]["type"], "TrustTaskHTTPS");
        // A bare string endpoint (the Trust-Task base) — unlike `WebVHHosting`'s
        // `{ "uri": ... }` object shape.
        assert_eq!(services[1]["serviceEndpoint"], "https://example.com/api");
        assert_eq!(
            services[1]["id"],
            json!(format!("{}#trust-tasks", doc["id"].as_str().unwrap()))
        );
    }

    /// Contract C4: `{ id: <did>#sign-in-portal, type: SignInPortal,
    /// serviceEndpoint: <login page URL> }`, a bare string endpoint.
    #[test]
    fn sign_in_portal_is_advertised_with_the_login_page_as_endpoint() {
        let mut doc =
            build_did_document("example.com", ".well-known", "z6MkKey", &Default::default());
        add_trust_task_https_service(&mut doc, "https://example.com/api");
        add_sign_in_portal_service(&mut doc, "https://example.com/login");

        let services = doc["service"].as_array().expect("service array");
        assert_eq!(services[1]["type"], SERVICE_TYPE_SIGN_IN_PORTAL);
        assert_eq!(services[1]["serviceEndpoint"], "https://example.com/login");
        assert_eq!(
            services[1]["id"],
            json!(format!("{}#sign-in-portal", doc["id"].as_str().unwrap()))
        );
    }

    #[test]
    fn only_https_qualifies_for_a_sign_in_portal() {
        assert!(is_sign_in_portal_url("https://example.com/login"));
        assert!(is_sign_in_portal_url("https://example.com:8443/login"));
        // Loopback http is fine for TrustTaskHTTPS, never for a portal.
        assert!(!is_sign_in_portal_url("http://localhost:8534/login"));
        assert!(!is_sign_in_portal_url("http://127.0.0.1:8534/login"));
        assert!(!is_sign_in_portal_url("https://user@example.com/login"));
        assert!(!is_sign_in_portal_url("not a url"));
    }

    #[test]
    fn https_and_loopback_http_qualify_for_trust_task_https() {
        assert!(is_https_or_loopback("https://example.com/api"));
        assert!(is_https_or_loopback("http://localhost:8534/api"));
        assert!(is_https_or_loopback("http://127.0.0.1:8534/api"));
        assert!(is_https_or_loopback("http://[::1]:8534/api"));
    }

    #[test]
    fn plaintext_http_to_a_real_host_does_not_qualify() {
        assert!(!is_https_or_loopback("http://example.com/api"));
        assert!(!is_https_or_loopback("http://webvh.example.com/api"));
        // Lookalikes that only start with a loopback name are not loopback.
        assert!(!is_https_or_loopback("http://localhost.evil.example/api"));
        assert!(!is_https_or_loopback("http://127.0.0.1.evil.example/api"));
        assert!(!is_https_or_loopback("http://localhostevil.example/api"));
        assert!(!is_https_or_loopback("http://user@localhost/api"));
        assert!(!is_https_or_loopback("http://evil.example@127.0.0.1/api"));
        assert!(!is_https_or_loopback("ftp://localhost/api"));
        assert!(!is_https_or_loopback("not a url"));
        assert!(is_https_or_loopback("http://127.0.0.2:8534/api"));
        assert!(is_https_or_loopback("HTTP://LOCALHOST:8534/api"));
    }

    #[test]
    fn encode_host_with_port() {
        let result = encode_host("http://localhost:8085").unwrap();
        assert_eq!(result, "localhost%3A8085");
    }

    #[test]
    fn encode_host_without_port() {
        let result = encode_host("https://example.com").unwrap();
        assert_eq!(result, "example.com");
    }

    #[test]
    fn encode_host_invalid_url() {
        assert!(encode_host("not-a-url").is_err());
    }

    #[test]
    fn build_did_web_id_simple() {
        assert_eq!(
            build_did_web_id("https://example.com", "my-did").unwrap(),
            "did:web:example.com:my-did"
        );
    }

    #[test]
    fn build_did_web_id_with_port() {
        assert_eq!(
            build_did_web_id("http://localhost:8530", "my-did").unwrap(),
            "did:web:localhost%3A8530:my-did"
        );
    }

    #[test]
    fn build_did_web_id_nested_path() {
        assert_eq!(
            build_did_web_id("https://example.com", "people/staff").unwrap(),
            "did:web:example.com:people:staff"
        );
    }

    #[test]
    fn build_did_web_id_well_known() {
        assert_eq!(
            build_did_web_id("https://example.com", ".well-known").unwrap(),
            "did:web:example.com"
        );
    }

    #[test]
    fn build_did_web_id_invalid_url() {
        assert!(build_did_web_id("not-a-url", "test").is_err());
    }

    #[test]
    fn build_did_document_correct_did_id() {
        let doc = build_did_document(
            "example.com%3A8085",
            "mypath",
            "z6Mk...",
            &Default::default(),
        );
        let id = doc["id"].as_str().unwrap();
        assert!(id.starts_with("did:webvh:{SCID}:example.com%3A8085:"));
        assert!(id.ends_with(":mypath"));
    }

    #[test]
    fn build_did_document_nested_path() {
        let doc = build_did_document(
            "example.com",
            "people/staff/glenn",
            "z6Mk...",
            &Default::default(),
        );
        let id = doc["id"].as_str().unwrap();
        assert!(id.contains(":people:staff:glenn"));
        assert!(!id.contains('/'));
    }

    #[test]
    fn build_did_document_structure() {
        let doc = build_did_document("example.com", "test", "z6MkPubKey", &Default::default());
        let context = doc["@context"].as_array().expect("@context is array");
        assert_eq!(
            context,
            &vec![
                serde_json::Value::String("https://www.w3.org/ns/did/v1".to_string()),
                serde_json::Value::String("https://www.w3.org/ns/cid/v1".to_string()),
            ]
        );
        assert!(doc["authentication"].is_array());
        assert!(doc["verificationMethod"].is_array());
        let vm = &doc["verificationMethod"][0];
        assert_eq!(vm["type"], "Multikey");
        assert_eq!(vm["publicKeyMultibase"], "z6MkPubKey");
        assert!(doc.get("service").is_none());
    }

    #[test]
    fn build_did_document_with_vta_didcomm_service() {
        let doc = build_did_document(
            "example.com",
            "test",
            "z6MkPubKey",
            &DidDocumentOptions {
                mediator_endpoint: Some("did:example:mediator"),
                ..Default::default()
            },
        );
        let service = &doc["service"];
        assert!(service.is_array());
        let svc = &service[0];
        assert!(svc["id"].as_str().unwrap().ends_with("#vta-didcomm"));
        assert_eq!(svc["type"], "DIDCommMessaging");
        assert_eq!(svc["serviceEndpoint"][0]["uri"], "did:example:mediator");
        assert_eq!(svc["serviceEndpoint"][0]["accept"][0], "didcomm/v2");
    }

    /// Locks the local builder's output to the shape produced by the VTA
    /// webvh VTA templates. Update both sides together if either ever
    /// moves. Covers: contexts, key-0 and key-1 verification method IDs,
    /// `#vta-didcomm` service ID, single-entry service array.
    #[test]
    fn build_did_document_matches_webvh_service_template() {
        let doc = build_did_document(
            "example.com",
            "control",
            "z6MkSigning",
            &DidDocumentOptions {
                key_agreement_multibase: Some("z6LSKA"),
                mediator_endpoint: Some("did:webvh:QmMED:mediator.example.com"),
                ..Default::default()
            },
        );
        let did_id = doc["id"].as_str().unwrap();

        // @context
        assert_eq!(
            doc["@context"][0], "https://www.w3.org/ns/did/v1",
            "first context entry"
        );
        assert_eq!(
            doc["@context"][1], "https://www.w3.org/ns/cid/v1",
            "second context entry (cid v1)"
        );
        assert_eq!(
            doc["@context"].as_array().unwrap().len(),
            2,
            "no extra contexts"
        );

        // Verification methods
        let vm = doc["verificationMethod"].as_array().unwrap();
        assert_eq!(vm.len(), 2);
        assert_eq!(vm[0]["id"], format!("{did_id}#key-0"));
        assert_eq!(vm[0]["type"], "Multikey");
        assert_eq!(vm[0]["controller"], did_id);
        assert_eq!(vm[1]["id"], format!("{did_id}#key-1"));
        assert_eq!(vm[1]["type"], "Multikey");

        // Purpose relations
        assert_eq!(doc["assertionMethod"][0], format!("{did_id}#key-0"));
        assert_eq!(doc["authentication"][0], format!("{did_id}#key-0"));
        assert_eq!(doc["keyAgreement"][0], format!("{did_id}#key-1"));

        // Service — single entry with `#vta-didcomm`
        let service = doc["service"].as_array().unwrap();
        assert_eq!(service.len(), 1, "exactly one service entry");
        assert_eq!(service[0]["id"], format!("{did_id}#vta-didcomm"));
        assert_eq!(service[0]["type"], "DIDCommMessaging");
        assert_eq!(
            service[0]["serviceEndpoint"][0]["uri"],
            "did:webvh:QmMED:mediator.example.com"
        );
        assert_eq!(service[0]["serviceEndpoint"][0]["accept"][0], "didcomm/v2");
    }

    /// Locks the local builder's TSP output to the `vta-sdk`
    /// `did-host-http-didcomm.json` / `did-host-didcomm.json` templates:
    /// the `#tsp` `TSPTransport` service is emitted **first** (canonical
    /// preference order), before `#vta-didcomm`, and its `serviceEndpoint`
    /// is a bare string (the mediator VID), not the DIDComm
    /// array-of-objects shape. Update both sides together if either moves.
    #[test]
    fn build_did_document_matches_webvh_tsp_template_ordering() {
        let doc = build_did_document(
            "example.com",
            "control",
            "z6MkSigning",
            &DidDocumentOptions {
                key_agreement_multibase: Some("z6LSKA"),
                mediator_endpoint: Some("did:webvh:QmMED:mediator.example.com"),
                tsp_endpoint: Some("did:webvh:QmMED:mediator.example.com"),
            },
        );
        let did_id = doc["id"].as_str().unwrap();
        let service = doc["service"].as_array().unwrap();
        assert_eq!(service.len(), 2, "TSP + DIDComm service entries");

        // TSP first — matches the template's canonical service order.
        assert_eq!(service[0]["id"], format!("{did_id}#tsp"));
        assert_eq!(service[0]["type"], "TSPTransport");
        assert_eq!(
            service[0]["serviceEndpoint"], "did:webvh:QmMED:mediator.example.com",
            "TSP serviceEndpoint is a bare string, not an array-of-objects"
        );

        // DIDComm second, unchanged.
        assert_eq!(service[1]["id"], format!("{did_id}#vta-didcomm"));
        assert_eq!(service[1]["type"], "DIDCommMessaging");
        assert_eq!(
            service[1]["serviceEndpoint"][0]["uri"],
            "did:webvh:QmMED:mediator.example.com"
        );
    }

    // ---- service_types_from_doc ----

    #[test]
    fn service_types_reads_bare_string_and_array_type_shapes() {
        // `did-host-*` templates emit a bare string; `ai-agent-peer` emits
        // a single-element array. Both must be understood.
        let doc = serde_json::json!({
            "service": [
                { "id": "#webvh-hosting", "type": "WebVHHosting" },
                { "id": "#auth", "type": ["Authentication"] },
            ]
        });
        assert_eq!(
            service_types_from_doc(&doc),
            vec!["WebVHHosting".to_string(), "Authentication".to_string()]
        );
    }

    #[test]
    fn service_types_preserves_document_order_and_dedupes() {
        let doc = serde_json::json!({
            "service": [
                { "type": "TSPTransport" },
                { "type": "DIDCommMessaging" },
                { "type": "TSPTransport" },
            ]
        });
        // TSP first (the canonical template order) and the repeat collapses.
        assert_eq!(
            service_types_from_doc(&doc),
            vec!["TSPTransport".to_string(), "DIDCommMessaging".to_string()]
        );
    }

    #[test]
    fn service_types_handles_multi_type_service() {
        let doc = serde_json::json!({
            "service": [{ "type": ["TSPTransport", "DIDCommMessaging"] }]
        });
        let types = service_types_from_doc(&doc);
        assert!(advertises_tsp(&types));
        assert!(advertises_didcomm(&types));
    }

    #[test]
    fn service_types_absent_or_malformed_yields_empty() {
        assert!(service_types_from_doc(&serde_json::json!({})).is_empty());
        // `service` present but not an array.
        assert!(service_types_from_doc(&serde_json::json!({ "service": "nope" })).is_empty());
        // Entries with no usable `type` contribute nothing.
        let doc =
            serde_json::json!({ "service": [{ "id": "#x" }, { "type": 42 }, { "type": "" }] });
        assert!(service_types_from_doc(&doc).is_empty());
    }

    /// The read side must agree with the write side: whatever
    /// `build_did_document` emits is what `service_types_from_doc` reports.
    #[test]
    fn service_types_round_trips_build_did_document() {
        let doc = build_did_document(
            "example.com",
            "alice",
            "z6MkTest",
            &DidDocumentOptions {
                key_agreement_multibase: None,
                mediator_endpoint: Some("did:webvh:QmMED:mediator.example.com"),
                tsp_endpoint: Some("did:webvh:QmMED:mediator.example.com"),
            },
        );
        let types = service_types_from_doc(&doc);
        // TSP before DIDComm, matching the canonical template order.
        assert_eq!(
            types,
            vec!["TSPTransport".to_string(), "DIDCommMessaging".to_string()]
        );
        assert!(advertises_tsp(&types));
        assert!(advertises_didcomm(&types));
    }

    /// A conforming did:webvh resolver injects `#whois`
    /// (`LinkedVerifiablePresentation`) and `#files` (`relativeRef`) into
    /// every document. They are not operator-declared and must not surface
    /// as advertised services — otherwise every resolved DID grows a
    /// permanent, meaningless `Other` badge.
    #[test]
    fn service_types_skips_resolver_injected_implicit_services() {
        let did = "did:webvh:QmSCID:webvh.example.com:server1";
        let doc = serde_json::json!({
            "service": [
                {
                    "id": format!("{did}#webvh-hosting"),
                    "type": "WebVHHosting",
                    "serviceEndpoint": { "uri": "https://webvh.example.com/server1" }
                },
                {
                    "id": format!("{did}#whois"),
                    "type": "LinkedVerifiablePresentation",
                    "serviceEndpoint": "https://webvh.example.com/server1/whois.vp"
                },
                {
                    "id": format!("{did}#files"),
                    "type": "relativeRef",
                    "serviceEndpoint": "https://webvh.example.com/server1/files"
                },
            ]
        });
        assert_eq!(
            service_types_from_doc(&doc),
            vec!["WebVHHosting".to_string()],
            "only the operator-declared service should surface"
        );
    }

    /// The filter keys on the `id` fragment, not the type — an operator who
    /// declares a `LinkedVerifiablePresentation` under their own fragment is
    /// genuinely advertising it and keeps the badge.
    #[test]
    fn service_types_keeps_operator_declared_linked_vp() {
        let did = "did:webvh:QmSCID:example.com:x";
        let doc = serde_json::json!({
            "service": [{
                "id": format!("{did}#my-presentation"),
                "type": "LinkedVerifiablePresentation",
                "serviceEndpoint": "https://example.com/vp"
            }]
        });
        assert_eq!(
            service_types_from_doc(&doc),
            vec!["LinkedVerifiablePresentation".to_string()]
        );
    }

    #[test]
    fn implicit_service_predicate_matches_only_whois_and_files() {
        assert!(is_implicit_webvh_service("did:webvh:Q:h:p#whois"));
        assert!(is_implicit_webvh_service("did:webvh:Q:h:p#files"));
        assert!(!is_implicit_webvh_service("did:webvh:Q:h:p#tsp"));
        assert!(!is_implicit_webvh_service("did:webvh:Q:h:p#vta-didcomm"));
        assert!(!is_implicit_webvh_service("did:webvh:Q:h:p#webvh-hosting"));
        // Substring, not suffix, must not match.
        assert!(!is_implicit_webvh_service("did:webvh:Q:h:p#whois-extra"));
        assert!(!is_implicit_webvh_service(""));
    }

    /// The resolver path feeds `is_implicit_webvh_service` a `Url::as_str()`,
    /// not a raw string. Pin that the `did:` scheme round-trips its fragment
    /// intact — otherwise the filter silently stops matching and every server
    /// grows an `Other` badge again.
    #[test]
    fn implicit_predicate_matches_url_parsed_service_ids() {
        let base =
            "did:webvh:QmRUN4vrMp6cS1xqWSH46bCipf9W95VrFDyyFBm8XXcZ1E:webvh.storm.ws:webvh-server1";
        for frag in ["whois", "files"] {
            let parsed = url::Url::parse(&format!("{base}#{frag}")).expect("parse service id");
            assert!(
                is_implicit_webvh_service(parsed.as_str()),
                "Url::as_str() must preserve the #{frag} fragment; got {}",
                parsed.as_str()
            );
        }
        let hosting = url::Url::parse(&format!("{base}#webvh-hosting")).expect("parse");
        assert!(!is_implicit_webvh_service(hosting.as_str()));
    }

    #[test]
    fn service_types_empty_when_document_advertises_none() {
        let doc = build_did_document(
            "example.com",
            "alice",
            "z6MkTest",
            &DidDocumentOptions {
                key_agreement_multibase: None,
                mediator_endpoint: None,
                tsp_endpoint: None,
            },
        );
        assert!(service_types_from_doc(&doc).is_empty());
        assert!(!advertises_tsp(&service_types_from_doc(&doc)));
    }
}