vta-sdk 0.9.9

SDK 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
//! Client surface for DIDComm protocol management.
//!
//! Spec: `docs/05-design-notes/didcomm-protocol-management.md`.
//!
//! Phase 3 lands `enable_didcomm` (REST-only by nature — DIDComm is
//! not yet running at first-enable time). The disable / migrate /
//! drain-cancel / report calls — and their DIDComm transport
//! handlers — arrive in Phase 4 verticals.
//!
//! Runtime REST service-management wire types (the symmetric
//! REST-side of the spec §4 surface — `EnableRestRequest`,
//! `UpdateRestRequest`, `DisableRestRequest`, `RollbackRestRequest`,
//! `ServiceMutationResponse`) live in [`services`].

pub mod services;

use serde::{Deserialize, Serialize};

#[cfg(feature = "client")]
use crate::client::VtaClient;
#[cfg(feature = "client")]
use crate::error::VtaError;
#[cfg(feature = "client")]
use crate::protocols::protocol_management;

/// Request body for `POST /services/didcomm/enable`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[must_use]
pub struct EnableDidcommRequest {
    pub mediator_did: String,
    /// Skip handshake steps 2-5 (DID resolution always runs).
    /// Emits a `MediatorHandshakeBypassed` telemetry event when set.
    #[serde(default)]
    pub force: bool,
    /// Trust-ping round-trip timeout (default: 10 seconds).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handshake_timeout_secs: Option<u64>,
}

impl EnableDidcommRequest {
    pub fn new(mediator_did: impl Into<String>) -> Self {
        Self {
            mediator_did: mediator_did.into(),
            force: false,
            handshake_timeout_secs: None,
        }
    }

    pub fn force(mut self, force: bool) -> Self {
        self.force = force;
        self
    }

    pub fn handshake_timeout_secs(mut self, secs: u64) -> Self {
        self.handshake_timeout_secs = Some(secs);
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnableDidcommResponse {
    pub new_version_id: String,
    pub mediator_did: String,
    pub mediator_endpoint: String,
    /// The VTA's own DID — subject of the LogEntry this enable
    /// wrote. Carried so the CLI can print follow-up commands like
    /// `pnm webvh did-log <vta_did>` for serverless deployments.
    /// `#[serde(default)]` + elide-when-empty keeps the wire form
    /// back-compat with older servers.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub vta_did: String,
    /// True when the VTA's DID is self-hosted (`server_id =
    /// "serverless"`). The new LogEntry is local only — operators
    /// must fetch the updated `did.jsonl` and redeploy.
    /// `#[serde(default)]` for back-compat.
    #[serde(default)]
    pub serverless: bool,
}

/// Request body for `POST /services/didcomm/disable`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisableDidcommRequest {
    /// Drain TTL in seconds. 0 = immediate teardown (REST only;
    /// over DIDComm transport, minimum 1h is enforced server-side).
    pub drain_ttl_secs: u64,
}

impl DisableDidcommRequest {
    pub fn new(drain_ttl_secs: u64) -> Self {
        Self { drain_ttl_secs }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisableDidcommResponse {
    pub new_version_id: String,
    pub prior_mediator_did: String,
    /// `Some(rfc3339)` when the listener entered drain state;
    /// `None` when it was torn down immediately.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drains_until: Option<String>,
    /// The VTA's own DID. See [`EnableDidcommResponse::vta_did`].
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub vta_did: String,
    /// True when the VTA's DID is self-hosted. See
    /// [`EnableDidcommResponse::serverless`].
    #[serde(default)]
    pub serverless: bool,
}

#[cfg(feature = "client")]
impl VtaClient {
    /// Enable DIDComm on a REST-only VTA. Spec: success criterion #1.
    ///
    /// The VTA must be configured with a vta_did, must currently
    /// have `services.didcomm = false`, and the caller must have
    /// super-admin role. On success, the VTA publishes a new WebVH
    /// LogEntry advertising the mediator and registers it as
    /// active.
    ///
    /// **First-enable handshake:** the route runs a transient
    /// `DIDCommService` round-trip against the candidate mediator
    /// before publishing — see
    /// `vta_service::messaging::transient_handshake`. The operation
    /// itself uses [`AlwaysOkProver`] because the steady-state
    /// `DIDCommService` doesn't exist yet at first-enable. The
    /// live-prover path through `update_didcomm` covers the
    /// steady-state case.
    pub async fn enable_didcomm(
        &self,
        req: EnableDidcommRequest,
    ) -> Result<EnableDidcommResponse, VtaError> {
        // REST-only by nature. Calling this over DIDComm transport
        // will surface as a 404 from the upstream message router,
        // which the rpc() layer turns into a `VtaError::Protocol`.
        // That's the right behaviour — the operation is logically
        // not available over DIDComm transport.
        self.rpc(
            "services-management/1.0/enable-not-available-via-didcomm",
            serde_json::to_value(&req)?,
            "services-management/1.0/enable-not-available-via-didcomm-result",
            30,
            |c, url| c.post(format!("{url}/services/didcomm/enable")).json(&req),
        )
        .await
    }

    /// Disable DIDComm. Refuses if REST is also disabled
    /// (`NoProtocolRemaining`). Drain TTL semantics:
    /// - `0` = immediate teardown (REST transport only).
    /// - `>= 3600` = drain window over DIDComm transport (server
    ///   enforces 1h minimum).
    pub async fn disable_didcomm(
        &self,
        req: DisableDidcommRequest,
    ) -> Result<DisableDidcommResponse, VtaError> {
        self.rpc(
            protocol_management::DISABLE_DIDCOMM,
            serde_json::to_value(&req)?,
            protocol_management::DISABLE_DIDCOMM_RESULT,
            30,
            |c, url| c.post(format!("{url}/services/didcomm/disable")).json(&req),
        )
        .await
    }

    /// Update which DIDComm mediator the VTA's `#vta-didcomm`
    /// service entry advertises. Runs the pre-promotion handshake
    /// against the new mediator and places the prior mediator in
    /// drain state for the requested TTL.
    ///
    /// (T2.3 rename — was `migrate_mediator`. Operation is the
    /// same; the naming aligns with the unified `services
    /// {kind} {verb}` surface.)
    pub async fn update_didcomm(
        &self,
        req: UpdateDidcommRequest,
    ) -> Result<UpdateDidcommResponse, VtaError> {
        self.rpc(
            protocol_management::UPDATE_DIDCOMM,
            serde_json::to_value(&req)?,
            protocol_management::UPDATE_DIDCOMM_RESULT,
            120,
            |c, url| c.post(format!("{url}/services/didcomm/update")).json(&req),
        )
        .await
    }

    // ── REST service-management client methods (P1 wire types,
    //    P5 client surface) ──────────────────────────────────────────

    /// Enable REST advertisement on the VTA's DID document by
    /// publishing a `#vta-rest` service entry. Spec §3.4.
    pub async fn enable_rest(
        &self,
        req: services::EnableRestRequest,
    ) -> Result<services::ServiceMutationResponse, VtaError> {
        self.rpc(
            protocol_management::ENABLE_REST,
            serde_json::to_value(&req)?,
            protocol_management::ENABLE_REST_RESULT,
            30,
            |c, url| c.post(format!("{url}/services/rest/enable")).json(&req),
        )
        .await
    }

    /// Update the URL on the existing `#vta-rest` service entry.
    pub async fn update_rest(
        &self,
        req: services::UpdateRestRequest,
    ) -> Result<services::ServiceMutationResponse, VtaError> {
        self.rpc(
            protocol_management::UPDATE_REST,
            serde_json::to_value(&req)?,
            protocol_management::UPDATE_REST_RESULT,
            30,
            |c, url| c.post(format!("{url}/services/rest/update")).json(&req),
        )
        .await
    }

    /// Remove the `#vta-rest` entry from the VTA's DID document.
    /// Refused with `LastServiceRefused` when DIDComm is also off.
    pub async fn disable_rest(
        &self,
        req: services::DisableRestRequest,
    ) -> Result<services::ServiceMutationResponse, VtaError> {
        self.rpc(
            protocol_management::DISABLE_REST,
            serde_json::to_value(&req)?,
            protocol_management::DISABLE_REST_RESULT,
            30,
            |c, url| c.post(format!("{url}/services/rest/disable")).json(&req),
        )
        .await
    }

    // ── Fail-forward rollback client methods (P3 server, P5
    //    client surface) ──────────────────────────────────────────

    /// Fail-forward the most recent REST mutation by re-applying
    /// the snapshotted prior state. Spec §3.5a.
    pub async fn rollback_rest(
        &self,
        req: services::RollbackRestRequest,
    ) -> Result<services::RollbackResponse, VtaError> {
        self.rpc(
            protocol_management::ROLLBACK_REST,
            serde_json::to_value(&req)?,
            protocol_management::ROLLBACK_REST_RESULT,
            60,
            |c, url| c.post(format!("{url}/services/rest/rollback")).json(&req),
        )
        .await
    }

    // ── WebAuthn service-management client methods ─────────────────

    /// Enable WebAuthn-RP advertisement on the VTA's DID document by
    /// publishing a `#vta-webauthn` service entry.
    pub async fn enable_webauthn(
        &self,
        req: services::EnableWebauthnRequest,
    ) -> Result<services::ServiceMutationResponse, VtaError> {
        self.rpc(
            protocol_management::ENABLE_WEBAUTHN,
            serde_json::to_value(&req)?,
            protocol_management::ENABLE_WEBAUTHN_RESULT,
            30,
            |c, url| c.post(format!("{url}/services/webauthn/enable")).json(&req),
        )
        .await
    }

    /// Update the URL on the existing `#vta-webauthn` entry.
    pub async fn update_webauthn(
        &self,
        req: services::UpdateWebauthnRequest,
    ) -> Result<services::ServiceMutationResponse, VtaError> {
        self.rpc(
            protocol_management::UPDATE_WEBAUTHN,
            serde_json::to_value(&req)?,
            protocol_management::UPDATE_WEBAUTHN_RESULT,
            30,
            |c, url| c.post(format!("{url}/services/webauthn/update")).json(&req),
        )
        .await
    }

    /// Remove the `#vta-webauthn` entry AND strip passkey VMs from
    /// every DID this VTA controls (hard-disable semantics).
    /// Refused with `LastServiceRefused` when removing WebAuthn
    /// would leave no transport advertised.
    pub async fn disable_webauthn(
        &self,
        req: services::DisableWebauthnRequest,
    ) -> Result<services::ServiceMutationResponse, VtaError> {
        // Longer timeout than REST/DIDComm disable because the
        // passkey-VM cleanup iterates every DID this VTA controls
        // and publishes a WebVH update per affected DID.
        self.rpc(
            protocol_management::DISABLE_WEBAUTHN,
            serde_json::to_value(&req)?,
            protocol_management::DISABLE_WEBAUTHN_RESULT,
            300,
            |c, url| {
                c.post(format!("{url}/services/webauthn/disable"))
                    .json(&req)
            },
        )
        .await
    }

    /// Fail-forward the most recent WebAuthn mutation by re-applying
    /// the snapshotted prior state.
    pub async fn rollback_webauthn(
        &self,
        req: services::RollbackWebauthnRequest,
    ) -> Result<services::RollbackResponse, VtaError> {
        self.rpc(
            protocol_management::ROLLBACK_WEBAUTHN,
            serde_json::to_value(&req)?,
            protocol_management::ROLLBACK_WEBAUTHN_RESULT,
            300,
            |c, url| {
                c.post(format!("{url}/services/webauthn/rollback"))
                    .json(&req)
            },
        )
        .await
    }

    /// Fail-forward the most recent DIDComm mutation. Threads
    /// `drain_ttl_secs` through to the dispatched forward op for
    /// the disable / update arms.
    pub async fn rollback_didcomm(
        &self,
        req: services::RollbackDidcommRequest,
    ) -> Result<services::RollbackResponse, VtaError> {
        self.rpc(
            protocol_management::ROLLBACK_DIDCOMM,
            serde_json::to_value(&req)?,
            protocol_management::ROLLBACK_DIDCOMM_RESULT,
            120,
            |c, url| {
                c.post(format!("{url}/services/didcomm/rollback"))
                    .json(&req)
            },
        )
        .await
    }

    // ── Read-only inspection (P4 server, P5 client surface) ──────

    /// Inspect the VTA's currently-advertised transport services.
    /// Returns one entry per kind in canonical DIDComm-then-REST
    /// order.
    pub async fn list_services(&self) -> Result<services::ServicesListResponse, VtaError> {
        self.rpc(
            protocol_management::LIST_SERVICES,
            serde_json::Value::Null,
            protocol_management::LIST_SERVICES_RESULT,
            30,
            |c, url| c.get(format!("{url}/services")),
        )
        .await
    }

    /// List currently-draining mediators. Empty list is normal.
    pub async fn list_drain(&self) -> Result<services::DrainListResponse, VtaError> {
        self.rpc(
            protocol_management::LIST_DRAIN,
            serde_json::Value::Null,
            protocol_management::LIST_DRAIN_RESULT,
            30,
            |c, url| c.get(format!("{url}/services/didcomm/drain")),
        )
        .await
    }
}

/// Request body for `POST /services/didcomm/update`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[must_use]
pub struct UpdateDidcommRequest {
    pub new_mediator_did: String,
    pub drain_ttl_secs: u64,
    #[serde(default)]
    pub force: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handshake_timeout_secs: Option<u64>,
    /// Tag the operation as a rollback in telemetry.
    #[serde(default)]
    pub rollback: bool,
}

impl UpdateDidcommRequest {
    pub fn new(new_mediator_did: impl Into<String>, drain_ttl_secs: u64) -> Self {
        Self {
            new_mediator_did: new_mediator_did.into(),
            drain_ttl_secs,
            force: false,
            handshake_timeout_secs: None,
            rollback: false,
        }
    }

    pub fn force(mut self, force: bool) -> Self {
        self.force = force;
        self
    }

    pub fn rollback(mut self, rollback: bool) -> Self {
        self.rollback = rollback;
        self
    }

    pub fn handshake_timeout_secs(mut self, secs: u64) -> Self {
        self.handshake_timeout_secs = Some(secs);
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateDidcommResponse {
    pub new_version_id: String,
    pub prior_mediator_did: String,
    pub active_mediator_did: String,
    pub active_mediator_endpoint: String,
    pub drains_until: String,
    /// The VTA's own DID. See [`EnableDidcommResponse::vta_did`].
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub vta_did: String,
    /// True when the VTA's DID is self-hosted. See
    /// [`EnableDidcommResponse::serverless`].
    #[serde(default)]
    pub serverless: bool,
}

/// Request body for `POST /mediators/drain/cancel`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DrainCancelRequest {
    pub mediator_did: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DrainCancelResponse {
    pub mediator_did: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediatorStats {
    pub mediator_did: String,
    pub inbound_count: u64,
    pub first_seen: String,
    pub last_seen: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SenderLastSeen {
    pub sender_did: String,
    pub last_seen_mediator: String,
    pub last_seen_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediatorReport {
    #[serde(default)]
    pub since: Option<String>,
    pub until: String,
    pub mediators: Vec<MediatorStats>,
    pub senders: Vec<SenderLastSeen>,
}

#[cfg(feature = "client")]
impl VtaClient {
    /// Cancel a drain entry early, dropping the listener for that
    /// mediator immediately. Refuses if the named DID is the
    /// active mediator (use `services disable didcomm` instead) or
    /// not registered at all.
    pub async fn drain_cancel(
        &self,
        req: DrainCancelRequest,
    ) -> Result<DrainCancelResponse, VtaError> {
        self.rpc(
            protocol_management::DRAIN_CANCEL,
            serde_json::to_value(&req)?,
            protocol_management::DRAIN_CANCEL_RESULT,
            30,
            |c, url| c.post(format!("{url}/mediators/drain/cancel")).json(&req),
        )
        .await
    }

    /// Query the mediator-attribution report. `since`/`until` are
    /// optional RFC 3339 timestamps. Returns per-mediator inbound
    /// counts and per-sender last-seen mediator (so operators can
    /// spot senders still using the prior mediator after a
    /// migrate).
    pub async fn mediator_report(
        &self,
        since: Option<&str>,
        until: Option<&str>,
    ) -> Result<MediatorReport, VtaError> {
        let since_owned = since.map(str::to_string);
        let until_owned = until.map(str::to_string);
        let qs = build_report_query(since_owned.as_deref(), until_owned.as_deref());
        self.rpc(
            protocol_management::MEDIATOR_REPORT,
            serde_json::json!({
                "since": since_owned,
                "until": until_owned,
            }),
            protocol_management::MEDIATOR_REPORT_RESULT,
            30,
            move |c, url| {
                let url = if qs.is_empty() {
                    format!("{url}/mediators/report")
                } else {
                    format!("{url}/mediators/report?{qs}")
                };
                c.get(url)
            },
        )
        .await
    }
}

#[cfg(feature = "client")]
fn build_report_query(since: Option<&str>, until: Option<&str>) -> String {
    let mut parts: Vec<String> = Vec::new();
    if let Some(s) = since {
        parts.push(format!("since={}", url_encode(s)));
    }
    if let Some(u) = until {
        parts.push(format!("until={}", url_encode(u)));
    }
    parts.join("&")
}

#[cfg(feature = "client")]
fn url_encode(s: &str) -> String {
    // RFC 3339 timestamps contain `:` and `+`; the latter is the
    // form-urlencoded representation of a space and would mangle
    // the timestamp on the server side. Encode the unsafe chars
    // explicitly.
    s.chars()
        .flat_map(|c| match c {
            ':' => "%3A".chars().collect::<Vec<_>>(),
            '+' => "%2B".chars().collect::<Vec<_>>(),
            _ => vec![c],
        })
        .collect()
}