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
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Auth types
//
// Wire shapes conform to the cross-cutting `spec/auth/*/0.1` canonical
// Trust-Task specs in the trusttasks-tf registry. Field names mirror
// OIDC Core §2 / RFC 8176 / RFC 6749 §5.1 so off-the-shelf identity
// libraries deserialise the payloads into their native types
// unchanged.
// ---------------------------------------------------------------------------

/// Wire shape for `POST /api/auth/challenge`. Conforms to
/// `spec/auth/challenge/0.1`: the `did` field serialises as `subject`
/// per the canonical payload schema. The Rust identifier stays `did`
/// for consistency with the rest of the codebase. `alias = "did"`
/// keeps clients that still send the legacy name working through one
/// upgrade cycle.
#[derive(Debug, Serialize, Deserialize)]
pub struct ChallengeRequest {
    #[serde(rename = "subject", alias = "did")]
    pub did: String,
}

/// Canonical `spec/auth/challenge/0.1#response`:
/// `{ challenge, sessionId, expiresAt }`. Flat shape — the framework
/// dropped the `data: {}` envelope; binary fields move to `ext` when
/// vendor extensions are needed.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChallengeResponse {
    pub challenge: String,
    pub session_id: String,
    /// ISO-8601 / RFC 3339 timestamp after which the challenge MUST
    /// NOT be honored.
    pub expires_at: String,
}

/// Payload of the `did-hosting/auth/authenticate/1.0` Trust-Task
/// envelope (SIOPv2 self-issued login).
///
/// The browser wallet self-issues an `id_token` (a compact EdDSA JWS
/// signed by its `did:key`) and carries it in the Trust-Task
/// envelope's `payload`. The server verifies the token by resolving
/// the issuer DID, then binds the session.
///
/// Field naming is `snake_case` on the wire to match the wallet's
/// emitted payload (`id_token`, `session_id`, `session_pubkey_b58btc`).
/// This is the *inner* Trust-Task payload, not a top-level response
/// type, so it intentionally does not use the `camelCase` convention
/// the response types do.
#[derive(Serialize, Deserialize)]
pub struct AuthenticatePayload {
    /// SIOPv2 self-issued `id_token` — a compact EdDSA JWS
    /// (`header.payload.signature`, base64url no-pad).
    pub id_token: String,
    /// The challenge session this login answers. The token's `nonce`
    /// must equal the session's issued challenge.
    pub session_id: String,
    /// Optional ephemeral session pubkey (Ed25519 multikey,
    /// base58btc-encoded with the `z` prefix). Bound to the issued JWT
    /// so subsequent Trust-Task Data-Integrity proofs can be tied to
    /// the same browser session. Only `z6Mk…` (Ed25519) is accepted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_pubkey_b58btc: Option<String>,
}

// Manual Debug that redacts the bearer-equivalent `id_token`. A
// `tracing::debug!(?payload, ...)` anywhere on the auth path would
// otherwise log the live SIOPv2 token. Same redaction pattern as
// `CreateInviteResponse` in passkey/routes.rs (wave-2).
impl std::fmt::Debug for AuthenticatePayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthenticatePayload")
            .field("id_token", &"<redacted>")
            .field("session_id", &self.session_id)
            .field("session_pubkey_b58btc", &self.session_pubkey_b58btc)
            .finish()
    }
}

/// Canonical `Session` from `spec/auth/_shared/0.1/session.schema.json`.
///
/// Aligns with OIDC Core §2 / RFC 8176:
/// - `amr`: authentication method references. did-hosting vocabulary
///   uses `"did"` (SIOPv2 id_token), `"passkey"` (WebAuthn assertion),
///   `"vta"` (VTA approval token), `"cli"` (process-local synthesis).
/// - `acr`: authentication context class. `"aal1"` for single-factor
///   DID, `"aal2"` after a step-up (passkey or VTA approval).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Session {
    pub id: String,
    pub subject: String,
    /// ISO-8601 timestamp the session was created.
    pub issued_at: String,
    /// ISO-8601 timestamp the session ceases to be valid.
    pub expires_at: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub amr: Vec<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub acr: String,
}

/// Canonical `TokenBundle` from `spec/auth/_shared/0.1/tokens.schema.json`.
///
/// OAuth 2.0 (RFC 6749 §5.1) shape: `expiresIn` is seconds from
/// issuance, not an absolute timestamp.
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenBundle {
    pub access_token: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<String>,
    pub token_type: String,
    pub expires_in: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_expires_in: Option<u64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope: Vec<String>,
}

// Manual Debug. `access_token` is a live JWT; `refresh_token` extends
// the session indefinitely if leaked. Both must never reach logs.
// Non-secret fields stay visible so the bundle's structure is still
// useful for diagnostics.
impl std::fmt::Debug for TokenBundle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TokenBundle")
            .field("access_token", &"<redacted>")
            .field(
                "refresh_token",
                &self.refresh_token.as_ref().map(|_| "<redacted>"),
            )
            .field("token_type", &self.token_type)
            .field("expires_in", &self.expires_in)
            .field("refresh_expires_in", &self.refresh_expires_in)
            .field("scope", &self.scope)
            .finish()
    }
}

/// Canonical `spec/auth/authenticate/0.1#response`: `{ session, tokens }`.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticateResponse {
    pub session: Session,
    pub tokens: TokenBundle,
}

#[cfg(feature = "server-core")]
impl AuthenticateResponse {
    /// Absolute Unix-second expiry of the access token, computed from
    /// `session.issued_at + tokens.expires_in`. Returns `None` if
    /// `session.issued_at` fails to parse as RFC 3339. Feature-gated
    /// on `server-core` because chrono lives there in did-hosting-common.
    pub fn access_expires_at_epoch(&self) -> Option<u64> {
        let issued = chrono::DateTime::parse_from_rfc3339(&self.session.issued_at).ok()?;
        let issued_epoch = u64::try_from(issued.timestamp()).ok()?;
        Some(issued_epoch.saturating_add(self.tokens.expires_in))
    }

    /// Absolute Unix-second expiry of the refresh token, when issued.
    pub fn refresh_expires_at_epoch(&self) -> Option<u64> {
        let refresh_secs = self.tokens.refresh_expires_in?;
        let issued = chrono::DateTime::parse_from_rfc3339(&self.session.issued_at).ok()?;
        let issued_epoch = u64::try_from(issued.timestamp()).ok()?;
        Some(issued_epoch.saturating_add(refresh_secs))
    }
}

/// Refresh shares the authenticate shape — same canonical
/// `{ session, tokens }` body. Kept as a distinct type alias so
/// handlers and clients can be explicit about which endpoint they're
/// talking to without losing the wire-shape contract.
pub type RefreshResponse = AuthenticateResponse;

/// Convert a Unix-epoch second timestamp to the RFC 3339 / ISO-8601
/// string the canonical wire format uses. Feature-gated on
/// `server-core` because chrono is server-only in this crate.
#[cfg(feature = "server-core")]
pub fn epoch_to_rfc3339(epoch_secs: u64) -> String {
    let secs = i64::try_from(epoch_secs).unwrap_or(0);
    chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0)
        .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
        .unwrap_or_else(|| "1970-01-01T00:00:00Z".to_string())
}

// ---------------------------------------------------------------------------
// DID management types
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateDidRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CheckNameRequest {
    pub path: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CheckNameResponse {
    pub available: bool,
    pub path: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestUriResponse {
    pub mnemonic: String,
    pub did_url: String,
}

/// Atomic claim-and-publish request — see `MSG_DID_REGISTER` for the
/// motivation. `path` is required; the DID payload is supplied via
/// `did_data` (preferred) or `did_log` (legacy, webvh-only alias).
/// `force` is only honoured when the caller is an admin taking over a
/// slot owned by a different DID (no force needed when the caller is
/// already the owner; the operation is idempotent in that case).
///
/// Server-side validation rejects payloads whose embedded DID
/// identifier does not name this host or does not name `path`, so an
/// admin can't upload arbitrary content under a path they happen to
/// own.
///
/// ## Multi-method wire shape (T26)
///
/// - `method`: one of `"webvh"`, `"web"`. Optional; if omitted, the
///   server attempts to derive it from `did_data.id` and falls back to
///   `"webvh"` for backwards-compat (matching the pre-T26 wire shape
///   that only supports webvh).
/// - `did_data`: the method-specific payload. For `webvh` this is the
///   `did.jsonl` log (either a JSON string carrying the raw text, or a
///   JSON array of log entries that will be serialised to jsonl). For
///   `web` this is a `did.json` document (object).
/// - `domain`: the hosting domain this DID should be registered under.
///   Optional; defaults to the caller's ACL default-domain per spec
///   §3.
/// - `did_log`: deprecated legacy field. When set without `did_data`,
///   treated as `method = "webvh"` and the string is the jsonl
///   payload. Setting both `did_data` and `did_log` is a 400 (the
///   server can't tell which the caller meant).
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct DidRegisterRequest {
    pub path: String,

    /// Preferred T26 shape.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// The method-specific log payload. The v0.1 Trust Task wire spells
    /// this `didData` (camelCase, like every other did-management field);
    /// `did_data` is accepted as a snake_case alias for REST/legacy
    /// callers. Deserialize-only alias — serialization stays `did_data`.
    #[serde(default, alias = "didData", skip_serializing_if = "Option::is_none")]
    pub did_data: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,

    /// Legacy pre-T26 field — webvh-only. Use `did_data` + `method`
    /// for new clients; this field is accepted unchanged for v0.7
    /// backwards-compat and will be removed in a future release.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub did_log: Option<String>,

    /// Required when admin is replacing a slot they don't own; ignored
    /// when caller is already the owner or the slot is free. Defaults
    /// to false.
    #[serde(default)]
    pub force: bool,
}

impl DidRegisterRequest {
    /// Normalise the multi-shape wire form into `(method, payload_bytes)`
    /// pairs the server-side handlers can act on directly.
    ///
    /// Returns:
    /// - `Err` with `Validation` when the request is ambiguous (both
    ///   `did_data` and `did_log` set), missing payload entirely, or
    ///   the declared `method` mismatches the method derived from
    ///   `did_data.id`.
    /// - `Ok((method, payload))` where `method` is one of the known
    ///   strings (`"webvh"`, `"web"`) and `payload` is the bytes the
    ///   storage layer will persist (the jsonl text for webvh, the
    ///   did.json bytes for web).
    pub fn resolve(&self) -> Result<(String, Vec<u8>), String> {
        if self.did_data.is_some() && self.did_log.is_some() {
            return Err("request carries both `did_data` and `did_log`; supply exactly one".into());
        }

        if let Some(did_log) = &self.did_log {
            // Legacy: did_log implies webvh. If `method` is explicit
            // and contradicts, reject.
            let method = self.method.as_deref().unwrap_or("webvh");
            if method != "webvh" {
                return Err(format!(
                    "`did_log` legacy field is webvh-only; received method = '{method}'. \
                     Use `did_data` for non-webvh methods.",
                ));
            }
            return Ok(("webvh".to_string(), did_log.clone().into_bytes()));
        }

        let did_data = self
            .did_data
            .as_ref()
            .ok_or_else(|| "request requires either `did_data` or `did_log`".to_string())?;

        // Derive the method from `did_data.id` when present, then
        // cross-check with the explicit `method` if both supplied.
        let derived_method = derive_method_from_did_data(did_data);
        let method = match (&self.method, &derived_method) {
            (Some(m), Some(d)) if m != d => {
                return Err(format!(
                    "method mismatch: request declares `method = \"{m}\"` but \
                     `did_data.id` resolves to method `\"{d}\"`. \
                     Either remove `method` (it will be derived) or fix `did_data.id`.",
                ));
            }
            (Some(m), _) => m.clone(),
            (None, Some(d)) => d.clone(),
            (None, None) => {
                return Err(
                    "request requires `method` (or a `did_data.id` from which it can \
                     be derived)"
                        .into(),
                );
            }
        };

        let bytes = match method.as_str() {
            "webvh" => {
                // webvh payload is jsonl text. Accept either a JSON
                // string (preferred) or an array of objects (one per
                // log entry — serialise to jsonl).
                if let Some(s) = did_data.as_str() {
                    s.as_bytes().to_vec()
                } else if let Some(arr) = did_data.as_array() {
                    let mut buf = String::new();
                    for (i, entry) in arr.iter().enumerate() {
                        if i > 0 {
                            buf.push('\n');
                        }
                        buf.push_str(
                            &serde_json::to_string(entry).map_err(|e| format!("entry {i}: {e}"))?,
                        );
                    }
                    buf.into_bytes()
                } else {
                    return Err(
                        "webvh `did_data` must be a jsonl string or an array of log entries".into(),
                    );
                }
            }
            "web" => {
                if did_data.is_object() {
                    serde_json::to_vec(did_data).map_err(|e| e.to_string())?
                } else {
                    return Err("web `did_data` must be a did.json object".into());
                }
            }
            "webs" => {
                // The `keri.cesr` stream, as text. CESR is
                // JSON-plus-base64url throughout, so it travels as a
                // JSON string without encoding.
                //
                // `method` must be explicit for did:webs: a key event
                // log has no `id` field, so `derive_method_from_did_data`
                // cannot infer it. That is not a gap — a KEL establishes
                // an AID, and the DID it belongs to depends on where it
                // is published, which the payload does not know.
                if let Some(s) = did_data.as_str() {
                    s.as_bytes().to_vec()
                } else {
                    return Err("webs `did_data` must be the keri.cesr stream as a string".into());
                }
            }
            other => {
                return Err(format!(
                    "unknown or unsupported method `{other}`; known methods: webvh, web, webs",
                ));
            }
        };

        Ok((method, bytes))
    }
}

/// Best-effort extraction of `"<method>"` from `did_data.id`, e.g.
/// `did_data.id = "did:web:example.com:alice"` → `Some("web")`.
/// Returns `None` when `id` is missing or malformed.
fn derive_method_from_did_data(did_data: &serde_json::Value) -> Option<String> {
    let id = did_data.get("id")?.as_str()?;
    // Fast extraction: split on ':'; expect "did:<method>:<rest>".
    let mut parts = id.splitn(3, ':');
    let prefix = parts.next()?;
    let method = parts.next()?;
    let _rest = parts.next()?;
    if prefix != "did" || method.is_empty() {
        return None;
    }
    Some(method.to_string())
}

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

    fn req() -> DidRegisterRequest {
        DidRegisterRequest {
            path: "alpha".into(),
            ..Default::default()
        }
    }

    /// Contract: the canonical camelCase `didData` wire field
    /// (did-management/did/register/0.1, what the VTA sends) deserializes
    /// into `did_data`. Pins the field name so VTA<->host can't drift.
    #[test]
    fn camelcase_did_data_wire_field_deserializes() {
        let r: DidRegisterRequest = serde_json::from_value(json!({
            "path": "alpha",
            "method": "webvh",
            "didData": "line1\nline2",
        }))
        .expect("didData must deserialize");
        assert_eq!(r.did_data, Some(json!("line1\nline2")));
        assert!(r.did_log.is_none());
    }

    /// The snake_case `did_data` alias keeps working for REST/legacy callers.
    #[test]
    fn snake_case_did_data_alias_still_deserializes() {
        let r: DidRegisterRequest = serde_json::from_value(json!({
            "path": "alpha",
            "method": "webvh",
            "did_data": "line1",
        }))
        .expect("did_data must deserialize");
        assert_eq!(r.did_data, Some(json!("line1")));
    }

    #[test]
    fn legacy_did_log_resolves_as_webvh() {
        let r = DidRegisterRequest {
            did_log: Some("line1\nline2".into()),
            ..req()
        };
        let (method, payload) = r.resolve().unwrap();
        assert_eq!(method, "webvh");
        assert_eq!(payload, b"line1\nline2");
    }

    #[test]
    fn legacy_did_log_with_explicit_webvh_method_ok() {
        let r = DidRegisterRequest {
            method: Some("webvh".into()),
            did_log: Some("line".into()),
            ..req()
        };
        let (method, _) = r.resolve().unwrap();
        assert_eq!(method, "webvh");
    }

    #[test]
    fn legacy_did_log_with_non_webvh_method_rejected() {
        let r = DidRegisterRequest {
            method: Some("web".into()),
            did_log: Some("line".into()),
            ..req()
        };
        let err = r.resolve().expect_err("conflict must reject");
        assert!(err.contains("webvh-only"), "got: {err}");
    }

    #[test]
    fn both_did_data_and_did_log_rejected() {
        let r = DidRegisterRequest {
            did_data: Some(json!("line")),
            did_log: Some("line".into()),
            ..req()
        };
        let err = r.resolve().expect_err("ambiguous must reject");
        assert!(err.contains("both"), "got: {err}");
    }

    #[test]
    fn neither_did_data_nor_did_log_rejected() {
        let err = req().resolve().expect_err("missing payload must reject");
        assert!(err.contains("either"), "got: {err}");
    }

    #[test]
    fn did_data_webvh_string_passes_through() {
        let r = DidRegisterRequest {
            method: Some("webvh".into()),
            did_data: Some(json!("the\njsonl\nbytes")),
            ..req()
        };
        let (method, payload) = r.resolve().unwrap();
        assert_eq!(method, "webvh");
        assert_eq!(payload, b"the\njsonl\nbytes");
    }

    #[test]
    fn did_data_webvh_array_serialises_to_jsonl() {
        let r = DidRegisterRequest {
            method: Some("webvh".into()),
            did_data: Some(json!([{"v": 1}, {"v": 2}])),
            ..req()
        };
        let (_, payload) = r.resolve().unwrap();
        let text = String::from_utf8(payload).unwrap();
        assert_eq!(text, "{\"v\":1}\n{\"v\":2}");
    }

    #[test]
    fn did_data_web_object_serialises() {
        let r = DidRegisterRequest {
            method: Some("web".into()),
            did_data: Some(json!({ "id": "did:web:example.com:alice" })),
            ..req()
        };
        let (method, payload) = r.resolve().unwrap();
        assert_eq!(method, "web");
        let parsed: serde_json::Value = serde_json::from_slice(&payload).unwrap();
        assert_eq!(
            parsed.get("id").and_then(|v| v.as_str()).unwrap(),
            "did:web:example.com:alice"
        );
    }

    #[test]
    fn method_mismatch_explicit_vs_did_data_id_rejected() {
        let r = DidRegisterRequest {
            method: Some("webvh".into()),
            did_data: Some(json!({ "id": "did:web:example.com:alice" })),
            ..req()
        };
        let err = r.resolve().expect_err("method mismatch must reject");
        assert!(err.contains("mismatch"), "got: {err}");
    }

    #[test]
    fn method_derived_from_did_data_id_when_not_explicit() {
        let r = DidRegisterRequest {
            did_data: Some(json!({ "id": "did:web:example.com:bob" })),
            ..req()
        };
        let (method, _) = r.resolve().unwrap();
        assert_eq!(method, "web");
    }

    #[test]
    fn unknown_method_rejected() {
        let r = DidRegisterRequest {
            method: Some("webxyz".into()),
            did_data: Some(json!("some-bytes")),
            ..req()
        };
        let err = r.resolve().expect_err("unknown method must reject");
        assert!(err.contains("unsupported"), "got: {err}");
    }
}

/// Atomic register response. `mnemonic` equals `path` (custom paths are
/// their own mnemonic on the server side); included for symmetry with
/// `RequestUriResponse`.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DidRegisterResponse {
    pub mnemonic: String,
    pub did_url: String,
}

// ---------------------------------------------------------------------------
// DID list / stats types
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DidListEntry {
    pub mnemonic: String,
    pub owner: String,
    pub created_at: u64,
    pub updated_at: u64,
    pub version_count: u64,
    pub did_id: Option<String>,
    pub total_resolves: u64,
    #[serde(default)]
    pub disabled: bool,
    /// DID hosting method (`"webvh"` / `"web"`). Surfaced on the
    /// wire so the UI can render a method badge per row without
    /// loading the full record. Pre-T12 records that haven't been
    /// migrated yet ship as `None` and the UI hides the badge.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// Hosting domain (T12 / M-01). Same shape contract as
    /// `method` above — `None` for unmigrated records, populated
    /// for everything M-01 has run over.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    /// Cached `service[].type` values from the DID document, straight
    /// off `DidRecord::services`. Present so the list can render service
    /// badges without reading log bytes. `None` for slots with no
    /// document yet and for records M-02 hasn't swept; the UI hides the
    /// badge row in both cases.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub services: Option<Vec<String>>,
    /// The slot's agent names, straight off `DidRecord::agent_names` — the
    /// same registry shape `DidDetailResponse` serves, so a name renders
    /// identically in a list row and on the detail page without the list
    /// having to fetch each DID.
    ///
    /// Carries parked entries too (`enabled: false`) rather than pre-filtering
    /// here: the caller decides. The list view shows only served names, but a
    /// caller auditing reservations needs the parked ones, and a list that
    /// silently dropped them would be the wrong primitive to build that on.
    ///
    /// Empty (and omitted from the wire) for every slot with no names, which
    /// is every slot on a deployment that has never used the feature.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub agent_names: Vec<crate::did_ops::AgentNameEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DidStats {
    #[serde(alias = "total_resolves")]
    pub total_resolves: u64,
    #[serde(alias = "total_updates")]
    pub total_updates: u64,
    #[serde(alias = "last_resolved_at")]
    pub last_resolved_at: Option<u64>,
    #[serde(alias = "last_updated_at")]
    pub last_updated_at: Option<u64>,
}

// ---------------------------------------------------------------------------
// Stats sync (server → control plane)
// ---------------------------------------------------------------------------

/// Per-DID counter delta for a single sync interval.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DidStatsDelta {
    pub mnemonic: String,
    pub resolve_delta: u64,
    pub update_delta: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_resolved_at: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_updated_at: Option<u64>,
}

/// Payload sent by did-hosting-server to the control plane with per-DID deltas.
///
/// Pushed periodically (configurable via `stats.sync_interval_secs`).
/// Only sent when there are actual changes — empty syncs are skipped.
/// The control plane merges these deltas into its persistent per-DID stats.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsSyncPayload {
    /// DID of the reporting server.
    pub server_did: String,
    /// Monotonic sequence number (incremented on each sync). Used by the
    /// control plane to detect replayed or out-of-order payloads.
    pub seq: u64,
    /// Per-DID counter deltas since the last sync.
    pub did_deltas: Vec<DidStatsDelta>,
}

// ---------------------------------------------------------------------------
// High-level create result
// ---------------------------------------------------------------------------

/// Result of the high-level `create_did` operation.
#[derive(Debug)]
pub struct CreateDidResult {
    /// The mnemonic / path assigned to this DID on the server.
    pub mnemonic: String,
    /// The full public URL where the DID log is served.
    pub did_url: String,
    /// The self-certifying identifier derived from the log entry.
    pub scid: String,
    /// The final `did:webvh:...` identifier.
    pub did: String,
    /// The public key multibase of the signing key.
    pub public_key_multibase: String,
}

/// An update the control plane sends back for a DID that needs refreshing.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DidSyncUpdate {
    pub mnemonic: String,
    pub did_id: String,
    pub log_content: String,
    /// Absent means the slot holds no witness proofs, never "unchanged".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub witness_content: Option<String>,
    pub version_count: u64,
    /// Whether the source has disabled the slot. A replica stops serving a
    /// disabled slot and resumes only on an update carrying `false`.
    pub disabled: bool,
}

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

    #[test]
    fn did_list_entry_serializes_camel_case() {
        let entry = DidListEntry {
            mnemonic: "test".to_string(),
            owner: "did:example:owner".to_string(),
            created_at: 1000,
            updated_at: 2000,
            version_count: 1,
            did_id: Some("did:webvh:abc:host:path".to_string()),
            total_resolves: 42,
            disabled: false,
            method: None,
            domain: None,
            services: None,
            agent_names: Vec::new(),
        };
        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"createdAt\""));
        assert!(json.contains("\"updatedAt\""));
        assert!(json.contains("\"versionCount\""));
        assert!(json.contains("\"didId\""));
        assert!(json.contains("\"totalResolves\""));
        assert!(!json.contains("\"created_at\""));
        assert!(!json.contains("\"updated_at\""));
        assert!(!json.contains("\"version_count\""));
        assert!(!json.contains("\"did_id\""));
        assert!(!json.contains("\"total_resolves\""));
    }

    #[test]
    fn did_list_entry_did_id_none_serializes_as_null() {
        let entry = DidListEntry {
            mnemonic: "test".to_string(),
            owner: "did:example:owner".to_string(),
            created_at: 0,
            updated_at: 0,
            version_count: 0,
            did_id: None,
            total_resolves: 0,
            disabled: false,
            method: None,
            domain: None,
            services: None,
            agent_names: Vec::new(),
        };
        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"didId\":null"));
    }

    #[test]
    fn did_list_entry_roundtrip() {
        let entry = DidListEntry {
            mnemonic: "test".to_string(),
            owner: "did:example:owner".to_string(),
            created_at: 1000,
            updated_at: 2000,
            version_count: 3,
            did_id: Some("did:webvh:abc:host:path".to_string()),
            total_resolves: 99,
            disabled: false,
            method: Some("webvh".to_string()),
            domain: Some("host.example".to_string()),
            services: Some(vec![
                "WebVHHosting".to_string(),
                "TSPTransport".to_string(),
                "DIDCommMessaging".to_string(),
            ]),
            agent_names: vec![crate::did_ops::AgentNameEntry {
                name: "alice".to_string(),
                enabled: true,
                created_at: 5,
            }],
        };
        let json = serde_json::to_string(&entry).unwrap();
        let back: DidListEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(back.mnemonic, "test");
        assert_eq!(back.version_count, 3);
        assert_eq!(back.did_id, Some("did:webvh:abc:host:path".to_string()));
        assert_eq!(back.total_resolves, 99);
        assert_eq!(
            back.services,
            Some(vec![
                "WebVHHosting".to_string(),
                "TSPTransport".to_string(),
                "DIDCommMessaging".to_string(),
            ])
        );
        assert!(json.contains(r#""agentNames":[{"name":"alice","enabled":true,"createdAt":5}]"#));
        assert_eq!(back.agent_names.len(), 1);
        assert_eq!(back.agent_names[0].name, "alice");
    }

    /// A record written before the `services` field existed must still
    /// deserialize, landing on `None` — "not yet computed", not "no services".
    #[test]
    fn did_list_entry_legacy_json_has_no_services() {
        let legacy = r#"{
            "mnemonic": "test", "owner": "did:example:owner",
            "createdAt": 0, "updatedAt": 0, "versionCount": 1,
            "didId": null, "totalResolves": 0
        }"#;
        let back: DidListEntry = serde_json::from_str(legacy).unwrap();
        assert_eq!(back.services, None);
        // Same contract for names: absent is empty, and the field being new
        // must not make a pre-agent-name payload fail to parse.
        assert!(back.agent_names.is_empty());
    }

    #[test]
    fn did_stats_default_values() {
        let stats = DidStats::default();
        assert_eq!(stats.total_resolves, 0);
        assert_eq!(stats.total_updates, 0);
        assert_eq!(stats.last_resolved_at, None);
        assert_eq!(stats.last_updated_at, None);
    }

    #[test]
    fn did_stats_serializes_camel_case() {
        let stats = DidStats {
            total_resolves: 10,
            total_updates: 5,
            last_resolved_at: Some(1000),
            last_updated_at: Some(2000),
        };
        let json = serde_json::to_string(&stats).unwrap();
        assert!(json.contains("\"totalResolves\""));
        assert!(json.contains("\"totalUpdates\""));
        assert!(json.contains("\"lastResolvedAt\""));
        assert!(json.contains("\"lastUpdatedAt\""));
        assert!(!json.contains("\"total_resolves\""));
    }

    #[test]
    fn request_uri_response_camel_case() {
        let resp = RequestUriResponse {
            mnemonic: "test".to_string(),
            did_url: "http://example.com/test/did.jsonl".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("\"didUrl\""));
        assert!(!json.contains("\"did_url\""));
    }
}