nostr-did 0.1.1

Generate W3C-compliant DID Documents from did:nostr identifiers
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
//! DID Document generation for the `did:nostr` method.
//!
//! Produces fully W3C-compliant DID Documents matching the
//! [Nostr DID Method Specification v0.0.11](https://nostrcg.github.io/did-nostr/),
//! including Multikey verification methods, relay service endpoints,
//! profile metadata, social graph (follows), and cross-platform identity
//! linking (alsoKnownAs).

use nostr_did_key::public_key_to_multikey;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// DID Document
// ---------------------------------------------------------------------------

/// A fully W3C-compliant DID Document for the `did:nostr` method.
///
/// Implements all fields defined in the Nostr DID Method Specification
/// v0.0.11: `@context`, `id`, `type`, `alsoKnownAs`, `verificationMethod`,
/// `authentication`, `assertionMethod`, `service`, `profile`, and `follows`.
///
/// # Example (Minimal — spec §2.3.1)
///
/// ```json
/// {
///   "@context": [
///     "https://www.w3.org/ns/did/v1",
///     "https://w3id.org/nostr/context"
///   ],
///   "id": "did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2",
///   "type": "DIDNostr",
///   "verificationMethod": [
///     {
///       "id": "did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2#key1",
///       "type": "Multikey",
///       "controller": "did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2",
///       "publicKeyMultibase": "fe70102124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2"
///     }
///   ],
///   "authentication": ["did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2#key1"],
///   "assertionMethod": ["did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2#key1"]
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DidDocument {
    /// JSON-LD contexts for DID Core and Nostr.
    #[serde(rename = "@context")]
    pub context: Vec<String>,

    /// The DID identifier (e.g., `did:nostr:<pubkey>`).
    pub id: String,

    /// Document type. MUST be `"DIDNostr"` per the specification.
    #[serde(rename = "type")]
    pub doc_type: String,

    /// Cross-platform identity assertions (WebID, ActivityPub, AT Protocol, etc.).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    #[serde(rename = "alsoKnownAs")]
    pub also_known_as: Vec<String>,

    /// Cryptographic verification methods (Multikey).
    #[serde(rename = "verificationMethod")]
    pub verification_method: Vec<VerificationMethod>,

    /// Verification methods used for authentication.
    #[serde(rename = "authentication")]
    pub authentication: Vec<String>,

    /// Verification methods used for assertion/issuance.
    #[serde(rename = "assertionMethod")]
    pub assertion_method: Vec<String>,

    /// Service endpoints (relays, follows endpoint).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub service: Vec<Service>,

    /// Profile metadata from Nostr kind 0 events.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile: Option<Profile>,

    /// Followed DIDs from Nostr kind 3 contact lists.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub follows: Vec<String>,
}

// ---------------------------------------------------------------------------
// Verification Method
// ---------------------------------------------------------------------------

/// A Multikey verification method as defined by W3C Controlled Identifiers.
///
/// Uses the `publicKeyMultibase` property with a multicodec-wrapped,
/// multibase-encoded compressed secp256k1 public key.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationMethod {
    /// DID URL fragment identifier (e.g., `did:nostr:...<pubkey>#key1`).
    pub id: String,
    /// MUST be `"Multikey"`.
    #[serde(rename = "type")]
    pub vm_type: String,
    /// The DID of the controller (same as the document `id`).
    pub controller: String,
    /// The public key in Multikey format.
    #[serde(rename = "publicKeyMultibase")]
    pub public_key_multibase: String,
}

// ---------------------------------------------------------------------------
// Service
// ---------------------------------------------------------------------------

/// A service endpoint entry.
///
/// Per the did:nostr spec, service types include:
/// - `"Relay"` — a Nostr relay WebSocket URL
/// - `"FollowsEndpoint"` — an HTTP endpoint for retrieving the full follow list
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Service {
    /// DID URL fragment identifier.
    pub id: String,
    /// Service type: `"Relay"` or `"FollowsEndpoint"`.
    #[serde(rename = "type")]
    pub service_type: String,
    /// The service endpoint URL(s).
    #[serde(rename = "serviceEndpoint")]
    pub service_endpoint: ServiceEndpoint,
}

/// A service endpoint — single URL or array of URLs.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ServiceEndpoint {
    /// Single URL string (e.g., `wss://relay.damus.io/`).
    Single(String),
    /// Array of URL strings.
    Multiple(Vec<String>),
}

// ---------------------------------------------------------------------------
// Profile
// ---------------------------------------------------------------------------

/// Profile metadata from Nostr kind 0 events.
///
/// All fields are optional. The `timestamp` field contains the
/// `created_at` value from the source Nostr event (Unix seconds),
/// enabling cache freshness checks.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Profile {
    /// Display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Bio or description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub about: Option<String>,
    /// Avatar/profile picture URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub picture: Option<String>,
    /// NIP-05 internet identifier (e.g., `alice@example.com`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nip05: Option<String>,
    /// Lightning address per LUD-16 (e.g., `alice@getalby.com`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lud16: Option<String>,
    /// Personal or project website.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub website: Option<String>,
    /// Unix timestamp (seconds) of the source kind 0 event.
    /// Corresponds to Nostr `event.created_at`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<u64>,
}

// ---------------------------------------------------------------------------
// Default Relays
// ---------------------------------------------------------------------------

/// High-availability, reliable Nostr relays used as defaults.
///
/// Sourced from active public relays with near 100% uptime:
/// - `wss://nos.lol` — General purpose, high uptime
/// - `wss://relay.damus.io` — General purpose, Damus ecosystem
/// - `wss://relay.primal.net` — General purpose, Primal ecosystem
/// - `wss://relay.nostr.band` — Full-text search, network trends
/// - `wss://purplepag.es` — Long-form content, user profiles
const DEFAULT_RELAYS: &[&str] = &[
    "wss://nos.lol",
    "wss://relay.damus.io",
    "wss://relay.primal.net",
    "wss://relay.nostr.band",
    "wss://purplepag.es",
];

// ---------------------------------------------------------------------------
// Document Builder
// ---------------------------------------------------------------------------

/// Builds W3C-compliant DID Documents from `did:nostr` identifiers.
///
/// Uses `nostr-did-key` for BIP-340 → Multikey cryptographic transformation
/// and produces documents matching the Nostr DID Method Specification v0.0.11.
///
/// # Relay deduplication
///
/// Relay URLs are normalized (trim trailing slash, lowercase) before
/// comparison. Duplicate URLs are silently ignored. This means calling
/// `with_relay("wss://relay.damus.io")` followed by
/// `with_relay("wss://relay.damus.io/")` adds the relay only once.
///
/// # Example — Minimal document (§2.3.1)
///
/// ```rust
/// use nostr_did::DocumentBuilder;
///
/// let doc = DocumentBuilder::new()
///     .build("did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2")
///     .unwrap();
///
/// assert_eq!(doc.doc_type, "DIDNostr");
/// assert_eq!(doc.verification_method[0].vm_type, "Multikey");
/// ```
///
/// # Example — Complete document (§2.3.3)
///
/// ```rust
/// use nostr_did::{DocumentBuilder, Profile};
///
/// let profile = Profile {
///     name: Some("Alice".into()),
///     about: Some("Building the decentralized web".into()),
///     picture: Some("https://example.com/alice.jpg".into()),
///     nip05: Some("alice@example.com".into()),
///     lud16: Some("alice@getalby.com".into()),
///     website: Some("https://alice.example.com".into()),
///     timestamp: Some(1737906600),
/// };
///
/// let doc = DocumentBuilder::new()
///     .with_relay("wss://relay.damus.io")
///     .with_profile(profile)
///     .with_also_known_as(vec![
///         "https://alice.example.com/#me".into(),
///         "at://alice.bsky.social".into(),
///     ])
///     .with_follows(vec![
///         "did:nostr:32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245".into(),
///     ])
///     .build("did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2")
///     .unwrap();
/// ```
pub struct DocumentBuilder {
    /// Collected relay URLs (normalized: no trailing slash, lowercase).
    relay_urls: Vec<String>,
    /// Profile metadata.
    profile: Option<Profile>,
    /// Cross-platform identity links.
    also_known_as: Vec<String>,
    /// Followed DIDs.
    follows: Vec<String>,
    /// Set of normalized relay URLs already seen — used for O(1) dedup.
    seen_relays: std::collections::HashSet<String>,
}

impl Default for DocumentBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl DocumentBuilder {
    /// Create a new builder pre-seeded with high-availability default relays.
    ///
    /// Default relays:
    /// - `wss://nos.lol`
    /// - `wss://relay.damus.io`
    /// - `wss://relay.primal.net`
    /// - `wss://relay.nostr.band`
    /// - `wss://purplepag.es`
    ///
    /// These defaults are deduplicated against any relays added later
    /// via [`with_relay`] or [`with_relays`].
    pub fn new() -> Self {
        let mut seen_relays = std::collections::HashSet::new();
        let mut relay_urls = Vec::with_capacity(DEFAULT_RELAYS.len());

        for relay in DEFAULT_RELAYS {
            let normalized = relay.trim_end_matches('/').to_lowercase();
            if seen_relays.insert(normalized.clone()) {
                relay_urls.push(normalized);
            }
        }

        Self {
            relay_urls,
            profile: None,
            also_known_as: Vec::new(),
            follows: Vec::new(),
            seen_relays,
        }
    }

    /// Add a relay URL. Duplicates are silently ignored.
    ///
    /// URLs are normalized (trim trailing slash, lowercase) before
    /// comparison and storage. This means `"wss://relay.damus.io"`,
    /// `"wss://relay.damus.io/"`, and `"WSS://RELAY.DAMUS.IO"`
    /// are all treated as the same relay.
    ///
    /// The trailing `/` is re-appended during document construction
    /// per the did:nostr specification.
    pub fn with_relay(mut self, relay: impl Into<String>) -> Self {
        let normalized = relay.into().trim_end_matches('/').to_lowercase();
        if self.seen_relays.insert(normalized.clone()) {
            self.relay_urls.push(normalized);
        }
        self
    }

    /// Replace all relays (including defaults) with a custom set.
    ///
    /// Each URL in the provided list is normalized and deduplicated.
    /// To add relays on top of defaults, use [`with_relay`] instead.
    pub fn with_relays(mut self, relays: Vec<String>) -> Self {
        self.relay_urls.clear();
        self.seen_relays.clear();
        for relay in relays {
            self = self.with_relay(relay);
        }
        self
    }

    /// Set profile metadata (from Nostr kind 0).
    pub fn with_profile(mut self, profile: Profile) -> Self {
        self.profile = Some(profile);
        self
    }

    /// Set alsoKnownAs identifiers (cross-platform identity links).
    ///
    /// Common values: WebID URLs, ActivityPub handles, AT Protocol DIDs,
    /// other DID methods, social media profiles.
    pub fn with_also_known_as(mut self, identities: Vec<String>) -> Self {
        self.also_known_as = identities;
        self
    }

    /// Set followed DIDs (from Nostr kind 3 contact list).
    pub fn with_follows(mut self, follows: Vec<String>) -> Self {
        self.follows = follows;
        self
    }

    // -------------------------------------------------------------------
    // Build
    // -------------------------------------------------------------------

    /// Build the complete DID Document from the DID identifier.
    ///
    /// Constructs the document deterministically from the public key
    /// embedded in the DID. All enrichment (profile, follows, alsoKnownAs,
    /// relays) is layered on top of the cryptographic baseline.
    ///
    /// # Returns
    ///
    /// `Some(DidDocument)` if the DID is syntactically valid, `None` otherwise.
    pub fn build(&self, did: &str) -> Option<DidDocument> {
        let pubkey_hex = extract_pubkey(did)?;

        if pubkey_hex.len() != 64 || !pubkey_hex.chars().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }

        let multikey = public_key_to_multikey(pubkey_hex).ok()?;
        let key_id = format!("{did}#key1");

        // Build service endpoints from relay URLs.
        // Trailing `/` is re-appended per the did:nostr specification §2.6.
        let mut services = Vec::with_capacity(self.relay_urls.len());
        for (i, relay) in self.relay_urls.iter().enumerate() {
            let relay_id = if self.relay_urls.len() == 1 {
                format!("{did}#relay")
            } else {
                format!("{did}#relay{}", i + 1)
            };
            services.push(Service {
                id: relay_id,
                service_type: "Relay".to_string(),
                service_endpoint: ServiceEndpoint::Single(format!("{relay}/")),
            });
        }

        Some(DidDocument {
            context: vec![
                "https://www.w3.org/ns/did/v1".to_string(),
                "https://w3id.org/nostr/context".to_string(),
            ],
            id: did.to_string(),
            doc_type: "DIDNostr".to_string(),
            also_known_as: self.also_known_as.clone(),
            verification_method: vec![VerificationMethod {
                id: key_id.clone(),
                vm_type: "Multikey".to_string(),
                controller: did.to_string(),
                public_key_multibase: multikey,
            }],
            authentication: vec![key_id.clone()],
            assertion_method: vec![key_id],
            service: services,
            profile: self.profile.clone(),
            follows: self.follows.clone(),
        })
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Extract the 64-character hex public key from a did:nostr identifier.
fn extract_pubkey(did: &str) -> Option<&str> {
    let prefix = "did:nostr:";
    did.strip_prefix(prefix).filter(|p| p.len() == 64)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    const SPEC_DID: &str =
        "did:nostr:124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2";

    const SPEC_MULTIKEY: &str =
        "fe70102124c0fa99407182ece5a24fad9b7f6674902fc422843d3128d38a0afbee0fdd2";

    // ── §2.3.1 Minimal document ──

    #[test]
    fn minimal_document_matches_spec() {
        let doc = DocumentBuilder::new().build(SPEC_DID).unwrap();

        assert_eq!(doc.id, SPEC_DID);
        assert_eq!(doc.doc_type, "DIDNostr");
        assert_eq!(doc.verification_method.len(), 1);

        let vm = &doc.verification_method[0];
        assert_eq!(vm.vm_type, "Multikey");
        assert_eq!(vm.controller, SPEC_DID);
        assert_eq!(vm.public_key_multibase, SPEC_MULTIKEY);
        assert_eq!(vm.id, format!("{SPEC_DID}#key1"));
        assert_eq!(doc.authentication, vec![format!("{SPEC_DID}#key1")]);
        assert_eq!(doc.assertion_method, vec![format!("{SPEC_DID}#key1")]);
    }

    #[test]
    fn minimal_document_has_no_optional_fields() {
        let doc = DocumentBuilder::new().build(SPEC_DID).unwrap();
        assert!(doc.also_known_as.is_empty());
        assert!(doc.follows.is_empty());
        assert!(doc.profile.is_none());
    }

    // ── §2.3.2 Enhanced with relays ──

    #[test]
    fn enhanced_document_includes_default_relays() {
        let doc = DocumentBuilder::new().build(SPEC_DID).unwrap();
        assert_eq!(doc.service.len(), DEFAULT_RELAYS.len());

        let relay_urls: Vec<&str> = doc
            .service
            .iter()
            .filter_map(|s| match &s.service_endpoint {
                ServiceEndpoint::Single(url) => Some(url.as_str()),
                _ => None,
            })
            .collect();

        assert!(relay_urls.iter().any(|u| u.contains("nos.lol")));
        assert!(relay_urls.iter().any(|u| u.contains("relay.damus.io")));
        assert!(relay_urls.iter().any(|u| u.contains("relay.primal.net")));
    }

    #[test]
    fn enhanced_document_with_custom_relay() {
        let doc = DocumentBuilder::new()
            .with_relay("wss://custom.relay.com")
            .build(SPEC_DID)
            .unwrap();

        let custom = doc
            .service
            .iter()
            .find(|s| {
                matches!(&s.service_endpoint, ServiceEndpoint::Single(url) if url.contains("custom.relay.com"))
            })
            .unwrap();
        assert_eq!(custom.service_type, "Relay");
    }

    #[test]
    fn custom_relays_replace_defaults() {
        let doc = DocumentBuilder::new()
            .with_relays(vec!["wss://sole.relay.com".to_string()])
            .build(SPEC_DID)
            .unwrap();

        assert_eq!(doc.service.len(), 1);
        match &doc.service[0].service_endpoint {
            ServiceEndpoint::Single(url) => assert!(url.contains("sole.relay.com")),
            _ => panic!("Expected single endpoint"),
        }
    }

    // ── Relay deduplication ──

    #[test]
    fn duplicate_relay_same_url_ignored() {
        let doc = DocumentBuilder::new()
            .with_relay("wss://relay.damus.io")
            .with_relay("wss://relay.damus.io")
            .with_relay("wss://relay.damus.io")
            .build(SPEC_DID)
            .unwrap();

        // Should have 5 defaults + 1 unique custom = 6, not 8
        let damus_count = doc
            .service
            .iter()
            .filter(|s| {
                matches!(&s.service_endpoint, ServiceEndpoint::Single(url) if url.contains("relay.damus.io"))
            })
            .count();
        assert_eq!(damus_count, 1);
    }

    #[test]
    fn duplicate_relay_trailing_slash_ignored() {
        let doc = DocumentBuilder::new()
            .with_relay("wss://relay.damus.io")
            .with_relay("wss://relay.damus.io/")
            .with_relay("WSS://RELAY.DAMUS.IO")
            .build(SPEC_DID)
            .unwrap();

        let damus_count = doc
            .service
            .iter()
            .filter(|s| {
                matches!(&s.service_endpoint, ServiceEndpoint::Single(url) if url.contains("relay.damus.io"))
            })
            .count();
        assert_eq!(damus_count, 1);
    }

    #[test]
    fn duplicate_relay_via_defaults_and_explicit_add() {
        // Adding a relay that's already in defaults should not duplicate it
        let doc = DocumentBuilder::new()
            .with_relay("wss://relay.damus.io") // already in defaults
            .build(SPEC_DID)
            .unwrap();

        assert_eq!(doc.service.len(), DEFAULT_RELAYS.len());
    }

    // ── §2.3.3 Complete document ──

    #[test]
    fn complete_document_matches_spec_example() {
        let profile = Profile {
            name: Some("Alice".into()),
            about: Some("Building the decentralized web".into()),
            picture: Some("https://example.com/alice.jpg".into()),
            nip05: None,
            lud16: None,
            website: None,
            timestamp: Some(1737906600),
        };

        let doc = DocumentBuilder::new()
            .with_relays(vec!["wss://relay.damus.io".to_string()])
            .with_profile(profile)
            .with_also_known_as(vec![
                "https://alice.example.com/#me".into(),
                "https://social.example.com/@alice".into(),
                "at://alice.bsky.social".into(),
            ])
            .with_follows(vec![
                "did:nostr:32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245".into(),
                "did:nostr:46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184147700e3a8".into(),
            ])
            .build(SPEC_DID)
            .unwrap();

        // Profile
        let p = doc.profile.unwrap();
        assert_eq!(p.name.unwrap(), "Alice");
        assert_eq!(p.about.unwrap(), "Building the decentralized web");
        assert_eq!(p.timestamp.unwrap(), 1737906600);

        // Also known as
        assert_eq!(doc.also_known_as.len(), 3);
        assert!(doc
            .also_known_as
            .contains(&"at://alice.bsky.social".to_string()));

        // Follows
        assert_eq!(doc.follows.len(), 2);
        assert!(doc.follows[0].starts_with("did:nostr:"));

        // Verification method preserved
        assert_eq!(
            doc.verification_method[0].public_key_multibase,
            SPEC_MULTIKEY
        );
    }

    // ── JSON-LD compliance ──

    #[test]
    fn document_has_required_jsonld_contexts() {
        let doc = DocumentBuilder::new().build(SPEC_DID).unwrap();
        assert!(doc
            .context
            .contains(&"https://www.w3.org/ns/did/v1".to_string()));
        assert!(doc
            .context
            .contains(&"https://w3id.org/nostr/context".to_string()));
    }

    #[test]
    fn document_serializes_valid_jsonld() {
        let doc = DocumentBuilder::new().build(SPEC_DID).unwrap();
        let json = serde_json::to_value(&doc).unwrap();

        // Top-level structure
        assert_eq!(json["id"], SPEC_DID);
        assert_eq!(json["type"], "DIDNostr");

        // Context is an array
        assert!(json["@context"].is_array());

        // Verification method
        let vm = &json["verificationMethod"][0];
        assert_eq!(vm["type"], "Multikey");
        assert_eq!(vm["publicKeyMultibase"], SPEC_MULTIKEY);
        assert_eq!(vm["controller"], SPEC_DID);

        // Verification relationships
        assert!(json["authentication"].is_array());
        assert!(json["assertionMethod"].is_array());
    }

    #[test]
    fn document_roundtrip_json() {
        let doc = DocumentBuilder::new()
            .with_profile(Profile {
                name: Some("Test".into()),
                about: Some("Roundtrip test".into()),
                ..Default::default()
            })
            .with_also_known_as(vec!["https://example.com".into()])
            .with_follows(vec![
                "did:nostr:abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc1".into(),
            ])
            .build(SPEC_DID)
            .unwrap();

        let json = serde_json::to_string_pretty(&doc).unwrap();
        let parsed: DidDocument = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.id, doc.id);
        assert_eq!(parsed.doc_type, doc.doc_type);
        assert_eq!(parsed.profile.unwrap().name.unwrap(), "Test");
        assert_eq!(parsed.also_known_as.len(), 1);
        assert_eq!(parsed.follows.len(), 1);
    }

    // ── Edge cases ──

    #[test]
    fn builder_rejects_invalid_did() {
        assert!(DocumentBuilder::new().build("did:nostr:tooshort").is_none());
        assert!(DocumentBuilder::new().build("did:key:abc123").is_none());
        assert!(DocumentBuilder::new().build("not-a-did").is_none());
    }

    #[test]
    fn builder_rejects_non_hex_pubkey() {
        let bad = "did:nostr:gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg";
        assert!(DocumentBuilder::new().build(bad).is_none());
    }

    #[test]
    fn empty_optional_fields_omitted_from_json() {
        let doc = DocumentBuilder::new().build(SPEC_DID).unwrap();
        let json = serde_json::to_string_pretty(&doc).unwrap();
        assert!(!json.contains("\"alsoKnownAs\""));
        assert!(!json.contains("\"follows\""));
        assert!(!json.contains("\"profile\""));
    }

    #[test]
    fn profile_default_is_all_none() {
        let p = Profile::default();
        assert!(p.name.is_none());
        assert!(p.about.is_none());
        assert!(p.picture.is_none());
        assert!(p.nip05.is_none());
        assert!(p.lud16.is_none());
        assert!(p.website.is_none());
        assert!(p.timestamp.is_none());
    }
}