vta-service 0.23.2

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! WebVH-DID-lifecycle slice trust-task handlers.
//!
//! **Feature-gated** — requires `webvh` (the entire op layer for
//! WebVH DID-doc creation, update, deletion, and host registration
//! lives under `cfg(feature = "webvh")`). The whole module is
//! `#![cfg(feature = "webvh")]` at the top; mod.rs's `mod webvh;`
//! declaration carries the same gate. URIs are declared in vta-sdk
//! unconditionally — the parity harness uses
//! `KNOWN_FEATURE_GATED_URIS` to recognise them when this module
//! isn't compiled.
//!
//! Auth requirements per URI (enforced by the operation function or
//! by the typed `AdminAuth` / `SuperAdminAuth` extractors used in the
//! REST handlers — replicated here at the slice boundary since
//! trust-task handlers take `AuthClaims` directly):
//!
//! | URI                                 | Auth        |
//! |-------------------------------------|-------------|
//! | `webvh/servers/list/1.0`            | any authed  |
//! | `webvh/servers/add/1.0`             | super-admin |
//! | `webvh/servers/update/1.0`          | super-admin |
//! | `webvh/servers/remove/1.0`          | super-admin |
//! | `webvh/dids/list/1.0`               | any authed  |
//! | `webvh/dids/create/1.0`             | admin       |
//! | `webvh/dids/get/1.0`                | any authed  |
//! | `webvh/dids/get-log/1.0`            | any authed  |
//! | `webvh/dids/delete/1.0`             | admin       |
//! | `webvh/dids/update/1.0`             | admin       |
//! | `webvh/dids/rotate-keys/1.0`        | admin       |
//! | `webvh/dids/register-with-server/1.0` | super-admin |

#![cfg(feature = "webvh")]

use super::helpers::TrustTaskOutcome;
use didwebvh_rs::witness::Witnesses;
use serde_json::Value;
use trust_tasks_rs::{RejectReason, TrustTask};

use vta_sdk::protocols::did_management::{
    agent_name::{
        AgentNameBody, AgentNameCheckBody, AgentNameCheckResultBody, AgentNameEntry,
        AgentNameListBody, AgentNameListResultBody, AgentNameResultBody,
    },
    create::CreateDidWebvhBody,
    delete::DeleteDidWebvhBody,
    get::GetDidWebvhBody,
    list::ListDidsWebvhBody,
    servers::{
        ListWebvhServerDomainsBody, ListWebvhServersBody, ReconcileWebvhServerDidsBody,
        RegisterDidWithServerBody, RegisterDidWithServerResultBody, RegisterWebvhServerBody,
        RemoveWebvhServerBody,
    },
    update::{RotateDidWebvhKeysBody, UpdateDidWebvhBody},
};

use crate::auth::AuthClaims;
use crate::error::AppError;
use crate::operations;
use crate::operations::did_webvh::{
    AgentNameVerb, RegisterDidWithServerError, RegisterDidWithServerParams,
    RotateDidWebvhKeysOptions, UpdateDidWebvhOptions, register_did_with_server,
};
use crate::server::AppState;

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

// ─── Server CRUD ────────────────────────────────────────────────────────

/// Refuse a syntactically invalid `did` before it reaches a store lookup.
///
/// [`vti_common::identifier::validate_did`] has always existed and names the
/// offending character and its position. Nothing on this surface called it, so
/// a malformed DID fell through to `webvh_store::get_did`, missed, and came
/// back as `not found`.
///
/// That is the wrong answer, not merely a worse one. "Not found" is a claim
/// about the world — it says the DID does not exist here — and it sends the
/// operator looking for something that was deleted instead of at the argument
/// they passed. The case that produced this: a DID copy-pasted out of the
/// `dids list` table, which elides the middle of the SCID, so the argument
/// carried a literal `…` (U+2026). The store answered honestly and the answer
/// was misleading. It cost two people an hour and a wrong diagnosis each.
fn reject_malformed_did(doc: &TrustTask<Value>, did: &str) -> Option<TrustTaskOutcome> {
    vti_common::identifier::validate_did("did", did)
        .err()
        .map(|e| app_error_to_reject(doc, e))
}

/// `webvh/servers/list/1.0` — list registered webvh hosts.
pub(super) async fn handle_servers_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let _: ListWebvhServersBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::did_webvh::list_webvh_servers(&state.webvh_ks, auth, TRANSPORT_TRUST_TASK)
        .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// `webvh/servers/register/1.0` — register a webvh host, or update the
/// label of one already registered. Super-admin.
///
/// Absorbs the retired `servers/add/1.0` and `servers/update/1.0`.
pub(super) async fn handle_servers_register(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: RegisterWebvhServerBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    match operations::did_webvh::register_webvh_server(
        &state.webvh_ks,
        auth,
        &req.id,
        req.did.as_deref(),
        req.label,
        Some(did_resolver),
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// `webvh/servers/remove/1.0` — deregister a webvh host. Super-admin.
pub(super) async fn handle_servers_remove(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: RemoveWebvhServerBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::did_webvh::remove_webvh_server(
        &state.webvh_ks,
        auth,
        &req.id,
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

// ─── DID lifecycle ──────────────────────────────────────────────────────

/// `webvh/dids/list/1.0` — list known DIDs, optionally filtered.
pub(super) async fn handle_dids_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: ListDidsWebvhBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match operations::did_webvh::list_dids_webvh(
        &state.webvh_ks,
        auth,
        req.context_id.as_deref(),
        req.server_id.as_deref(),
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// `webvh/dids/create/1.0` — mint a new DID. Admin role on target context.
pub(super) async fn handle_dids_create(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let body: CreateDidWebvhBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let config = state.config.read().await;
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let params = body.into();
    let deps =
        operations::did_webvh::CreateDidWebvhDeps::from_app_state(state, &config, did_resolver);
    match operations::did_webvh::create_did_webvh(&deps, auth, params, TRANSPORT_TRUST_TASK).await {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// `webvh/dids/get/1.0` — fetch a DID record, optionally with its raw
/// `did.jsonl` (`includeLog`).
///
/// Absorbs the retired `webvh/dids/get-log/1.0`. The unauthenticated
/// public log mirror (`GET /did/{did}/log`) remains deliberately NOT
/// trust-task-wrapped — it stays plain REST as the DID-resolver
/// failover path.
pub(super) async fn handle_dids_get(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: GetDidWebvhBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Some(reject) = reject_malformed_did(&doc, &req.did) {
        return reject;
    }
    match operations::did_webvh::get_did_webvh(
        &state.webvh_ks,
        auth,
        &req.did,
        TRANSPORT_TRUST_TASK,
        req.include_log,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// `webvh/dids/delete/1.0` — delete a DID locally (+ remote cleanup
/// when hosted). Admin role on the DID's context.
pub(super) async fn handle_dids_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: DeleteDidWebvhBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Some(reject) = reject_malformed_did(&doc, &req.did) {
        return reject;
    }
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::delete_did_webvh(
        &deps,
        auth,
        &req.did,
        vta_did.as_deref(),
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// `webvh/dids/update/1.0` — apply a generic DID-doc patch. Admin
/// role on the DID's context.
///
/// The SDK wire body
/// (`vta_sdk::protocols::did_management::update::UpdateDidWebvhBody`)
/// carries `witnesses` as opaque JSON (no `didwebvh-rs` dependency
/// for SDK consumers). Convert to the op-layer's typed
/// `UpdateDidWebvhOptions` at the slice boundary by deserialising
/// the JSON into `Witnesses` (the enum is `#[serde(untagged)]`, so
/// the wire shapes are identical).
///
/// The trust-task envelope has no URL path, so the caller carries
/// the target `did` at the payload top level via the
/// [`UpdateDidWithDid`] wrapper.
pub(super) async fn handle_dids_update(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: UpdateDidWithDid = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let UpdateDidWithDid { did, body } = req;
    if let Some(reject) = reject_malformed_did(&doc, &did) {
        return reject;
    }
    let options = match update_body_to_options(body) {
        Ok(o) => o,
        Err(resp) => return reject_with(&doc, resp),
    };
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::update_did_webvh(
        &deps,
        auth,
        &did,
        options,
        vta_did.as_deref(),
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => {
            // A Destructive update that passed the consent gate and then failed
            // in execute previously vanished into a bare 422 — no line named the
            // cause, so a consent-approved-but-still-looping DID was undiagnosable
            // from the log. The error's Display distinguishes the sub-causes
            // (`reconcile publish_did: …`, `webvh server … missing`,
            // `get_published_version: …`, a signing/library failure), so log it.
            tracing::warn!(
                did = %did,
                error = %e,
                "webvh dids/update execute failed after the consent gate passed — \
                 returning task error to requester"
            );
            app_error_to_reject(&doc, AppError::from(e))
        }
    }
}

/// `spec/vta/webvh/agent-name/list/1.0` — read the DID's agent-name registry
/// from the hosting control plane, parked names included. Read-only.
pub(super) async fn handle_agent_name_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: AgentNameListBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Some(reject) = reject_malformed_did(&doc, &req.did) {
        return reject;
    }
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::list_agent_names(&deps, auth, &req.did, vta_did.as_deref()).await {
        Ok((did, names)) => success_response(
            &doc,
            AgentNameListResultBody {
                did,
                names: names
                    .into_iter()
                    .map(|e| AgentNameEntry {
                        name: e.name,
                        enabled: e.enabled,
                        created_at: e.created_at,
                    })
                    .collect(),
            },
        ),
        Err(e) => app_error_to_reject(&doc, AppError::from(e)),
    }
}

/// `spec/vta/webvh/agent-name/check/1.0` — is this name free on the DID's
/// host? Read-only; lets a client report a collision before signing anything.
pub(super) async fn handle_agent_name_check(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: AgentNameCheckBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Some(reject) = reject_malformed_did(&doc, &req.did) {
        return reject;
    }
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::check_agent_name(
        &deps,
        auth,
        &req.did,
        &req.name,
        vta_did.as_deref(),
    )
    .await
    {
        Ok(a) => success_response(
            &doc,
            AgentNameCheckResultBody {
                name: a.name,
                domain: a.domain,
                available: a.available,
                reserved: a.reserved,
            },
        ),
        Err(e) => app_error_to_reject(&doc, AppError::from(e)),
    }
}

/// `spec/vta/webvh/agent-name/set/1.0` — bind an agent name: publish a new
/// signed version claiming it in `alsoKnownAs` and register the binding with
/// the host, which refuses a reserved name or one another DID already holds.
/// Destructive.
pub(super) async fn handle_agent_name_set(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    handle_agent_name(state, auth, doc, AgentNameVerb::Set).await
}

/// `spec/vta/webvh/agent-name/remove/1.0` — release an agent name: publish a
/// new signed version dropping it from `alsoKnownAs` and tell the host to drop
/// the reservation, so anyone may reclaim it. Destructive — and unlike
/// `disable`, not recoverable by this DID alone.
pub(super) async fn handle_agent_name_remove(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    handle_agent_name(state, auth, doc, AgentNameVerb::Remove).await
}

/// `spec/vta/webvh/agent-name/disable/1.0` — park an agent name: publish a new
/// signed version dropping it from `alsoKnownAs` and tell the host to keep it
/// reserved. Destructive.
pub(super) async fn handle_agent_name_disable(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    handle_agent_name(state, auth, doc, AgentNameVerb::Disable).await
}

/// `spec/vta/webvh/agent-name/enable/1.0` — resume serving a parked name:
/// publish a new signed version that claims it again.
pub(super) async fn handle_agent_name_enable(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    handle_agent_name(state, auth, doc, AgentNameVerb::Enable).await
}

async fn handle_agent_name(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
    verb: AgentNameVerb,
) -> TrustTaskOutcome {
    let req: AgentNameBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Some(reject) = reject_malformed_did(&doc, &req.did) {
        return reject;
    }
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::agent_name_op(
        &deps,
        auth,
        &req.did,
        &req.name,
        verb,
        vta_did.as_deref(),
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(_) => success_response(
            &doc,
            AgentNameResultBody {
                did: req.did,
                name: req.name,
                // Whether the name resolves now — `remove` reports `false`
                // like `disable`; the caller knows which verb it sent.
                enabled: verb.claims_name(),
            },
        ),
        Err(e) => app_error_to_reject(&doc, AppError::from(e)),
    }
}

/// `webvh/dids/rotate-keys/1.0` — rotate every VM's key bytes on a
/// DID and apply the resulting document change as one update. Admin
/// role on the DID's context.
pub(super) async fn handle_dids_rotate_keys(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: RotateKeysWithDid = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Some(reject) = reject_malformed_did(&doc, &req.did) {
        return reject;
    }
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let options = RotateDidWebvhKeysOptions {
        pre_rotation_count: req.body.pre_rotation_count,
        label: req.body.label,
    };
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::rotate_did_webvh_keys(
        &deps,
        auth,
        &req.did,
        options,
        vta_did.as_deref(),
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, AppError::from(e)),
    }
}

/// `webvh/dids/register-with-server/1.0` — promote a serverless DID
/// to a server-managed one. Super-admin.
pub(super) async fn handle_dids_register_with_server(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: RegisterDidWithServerBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Some(reject) = reject_malformed_did(&doc, &req.did) {
        return reject;
    }
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match register_did_with_server(
        &deps,
        auth,
        RegisterDidWithServerParams {
            did: req.did,
            server_id: req.server_id,
            force: req.force,
            domain: req.domain.clone(),
        },
        vta_did.as_deref(),
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        Ok(result) => success_response(
            &doc,
            RegisterDidWithServerResultBody {
                did: result.did,
                server_id: result.server_id,
                log_entry_count: result.log_entry_count,
            },
        ),
        Err(e) => app_error_to_reject(&doc, map_register_err(e)),
    }
}

/// Map `RegisterDidWithServerError` onto `AppError`. Mirrors the
/// `map_register_err` helper in `routes::did_webvh` so REST and
/// trust-task transports return the same statuses for the same
/// failure modes. Kept private to the slice — sharing the helper
/// with `routes::did_webvh` would mean making it `pub(crate)`,
/// which we don't yet need.
fn map_register_err(e: RegisterDidWithServerError) -> AppError {
    use RegisterDidWithServerError as E;
    match e {
        E::Auth(msg) => AppError::Forbidden(msg),
        E::DidNotFound(msg) | E::ServerNotFound(msg) | E::LogMissing(msg) => {
            AppError::NotFound(msg)
        }
        E::AlreadyServerManaged { .. } | E::Conflict(_) => AppError::Conflict(e.to_string()),
        E::Transport(msg) => AppError::Internal(format!("publish: {msg}")),
        // Pass the host's typed rejection through untouched — see
        // `RegisterDidWithServerError::Publish`.
        E::Publish(e) => e,
        E::DidUrlParse { .. } => AppError::Validation(e.to_string()),
        E::Storage(msg) => AppError::Internal(msg),
    }
}

// ─── Helpers internal to this slice ─────────────────────────────────────

/// Convert the camelCase wire body into the op-layer options shape.
///
/// `pub(crate)` so the REST route shares this one conversion rather than
/// deserialising the caller's JSON straight into [`UpdateDidWebvhOptions`].
/// That shortcut silently dropped `expectedVersionId`: the wire body is
/// `rename_all = "camelCase"`, the op-layer struct is snake_case with no
/// aliases and no `deny_unknown_fields`, so the field matched nothing and
/// defaulted to `None` — the optimistic-concurrency precondition never
/// applied on that path. Two conversions are two chances to drift; there is
/// deliberately only one.
pub(crate) fn update_body_to_options(
    body: UpdateDidWebvhBody,
) -> Result<UpdateDidWebvhOptions, RejectReason> {
    let witnesses = match body.witnesses {
        Some(v) => match serde_json::from_value::<Witnesses>(v) {
            Ok(w) => Some(w),
            Err(e) => {
                return Err(RejectReason::MalformedRequest {
                    reason: format!("witnesses: {e}"),
                });
            }
        },
        None => None,
    };
    Ok(UpdateDidWebvhOptions {
        document: body.document,
        pre_rotation_count: body.pre_rotation_count,
        witnesses,
        watchers: body.watchers,
        ttl: body.ttl,
        label: body.label,
        expected_version_id: body.expected_version_id,
    })
}

/// Wrapper carrying `RotateDidWebvhKeysBody` plus the target `did`.
/// The trust-task envelope has no URL path; the caller must include
/// the DID at the payload top level.
#[derive(Debug, serde::Deserialize)]
struct RotateKeysWithDid {
    did: String,
    #[serde(flatten)]
    body: RotateDidWebvhKeysBody,
}

/// Wrapper carrying `UpdateDidWebvhBody` plus the target `did`. Same
/// rationale as [`RotateKeysWithDid`].
#[derive(Debug, serde::Deserialize)]
pub(super) struct UpdateDidWithDid {
    pub(super) did: String,
    #[serde(flatten)]
    pub(super) body: UpdateDidWebvhBody,
}

/// `vta/webvh/servers/domains/0.1` — relay a hosting server's caller-scoped
/// domain view.
///
/// The VTA holds the registration and the credentials; the *server* holds the
/// ACL that decides which domains this caller may use. The relay is therefore
/// deliberately transparent — no second filter here, because narrowing a list
/// the server already scoped would report fewer domains than the caller may
/// actually use, and the caller has no way to tell that happened.
/// `spec/vta/webvh/servers/reconcile/0.1` — diff a hosting server's DIDs against
/// this VTA's records. Read-only; super-admin (the operation explains why).
pub(super) async fn handle_servers_reconcile(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: ReconcileWebvhServerDidsBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::reconcile_webvh_server_dids(
        &deps,
        auth,
        vta_did.as_deref(),
        &req.server_id,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// `spec/vta/webvh/servers/retire-orphan/0.1` — remove a slot the host serves
/// and this VTA has no record of. Destructive, no undo, super-admin.
///
/// The refusals are the interesting half. Three conditions decline, and each
/// carries the specification's extended code in `details.reason` so a caller
/// keys on a stable field rather than on prose — the same shape the consent
/// gate uses. Two of the three are *uncertainty* rather than contradiction,
/// and refusing on uncertainty is deliberate: the alternative to a false
/// refusal is a retry, and the alternative to a false removal is nothing.
pub(super) async fn handle_servers_retire_orphan(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use vta_sdk::protocols::did_management::servers::RetireOrphanSlotBody;
    let req: RetireOrphanSlotBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::retire_orphan_slot(&deps, auth, vta_did.as_deref(), &req).await {
        Ok(Ok(body)) => success_response(&doc, body),
        Ok(Err(refusal)) => {
            tracing::info!(
                caller = %auth.did,
                server_id = %req.server_id,
                slot_id = %req.slot_id,
                code = refusal.code(),
                "retire-orphan refused"
            );
            super::helpers::reject_with(
                &doc,
                trust_tasks_rs::RejectReason::TaskFailed {
                    reason: refusal.message(),
                    details: Some(serde_json::json!({
                        "reason": refusal.code(),
                        "serverId": req.server_id,
                        "slotId": req.slot_id,
                    })),
                },
            )
        }
        Err(e) => app_error_to_reject(&doc, e),
    }
}

pub(super) async fn handle_servers_domains(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: ListWebvhServerDomainsBody = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let did_resolver = match state.did_resolver.as_ref() {
        Some(r) => r,
        None => {
            return app_error_to_reject(
                &doc,
                AppError::Internal("DID resolver not available".into()),
            );
        }
    };
    let vta_did = state.config.read().await.vta_did.clone();
    let deps = operations::did_webvh::WebvhDeps::from_app_state(state, did_resolver);
    match operations::did_webvh::list_webvh_server_domains(
        &deps,
        auth,
        vta_did.as_deref(),
        &req.server_id,
    )
    .await
    {
        Ok(body) => success_response(&doc, body),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

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

    fn doc(did: &str) -> TrustTask<Value> {
        serde_json::from_value(serde_json::json!({
            "id": "urn:uuid:00000000-0000-4000-8000-000000000000",
            "type": "https://trusttasks.org/spec/vta/webvh/dids/delete/1.0",
            "issuer": "did:key:z6MkIssuer",
            "recipient": "did:key:z6MkVta",
            "payload": { "did": did },
        }))
        .expect("a well-formed Trust Task")
    }

    /// The case that sent two people to the wrong conclusion: a DID copied out
    /// of the `dids list` table, which elides the middle of the SCID, so the
    /// argument carries a literal `…` (U+2026).
    ///
    /// Before this guard it reached the store, missed, and came back as `not
    /// found` — which reads as "that DID was deleted" rather than "look at what
    /// you typed".
    #[test]
    fn a_truncated_did_is_refused_as_malformed_not_as_missing() {
        let bad = "did:webvh:QmbsoTcwkM\u{2026}:webvh.storm.ws:hurdle-surface";
        let outcome = reject_malformed_did(&doc(bad), bad).expect("a truncated DID is refused");

        let rendered = String::from_utf8_lossy(&outcome.body).to_string();
        assert!(
            rendered.contains("malformedRequest"),
            "must be malformedRequest, not a lookup miss: {rendered}"
        );
        // Naming the character is the whole value: `…` is invisible enough in a
        // terminal that "invalid character" alone would not land.
        assert!(
            rendered.contains("invalid character"),
            "the reason must name what is wrong with the argument: {rendered}"
        );
    }

    /// Other ways an argument fails to be a DID, each refused here rather than
    /// deeper.
    #[test]
    fn other_non_dids_are_refused_too() {
        for bad in [
            "",
            "not-a-did",
            "did:webvh:has space",
            "did:webvh:tab\tchar",
        ] {
            assert!(
                reject_malformed_did(&doc(bad), bad).is_some(),
                "`{bad}` must be refused"
            );
        }
    }

    /// A real DID passes through untouched — the guard must not become a
    /// second, stricter DID grammar that rejects things the store holds.
    #[test]
    fn a_well_formed_did_is_not_refused() {
        for good in [
            "did:webvh:QmbsoTcwkMjqaezmeFW4c6yth2sKDGtDiaGrzS1e3BvdZX:webvh.storm.ws:hurdle-surface",
            "did:key:z6MkhBYkvHQSLDmhVQWoy6ZiQc2VU3EFYjLz2KQ2YQDQ77Ag",
            "did:web:example.com%3A8443:path",
        ] {
            assert!(
                reject_malformed_did(&doc(good), good).is_none(),
                "`{good}` must pass"
            );
        }
    }
}