Skip to main content

hyprstream_pds/
did_op.rs

1//! The permanent genesis operation for a hyprstream-hosted `did:web` account.
2//!
3//! This module deliberately implements only operation zero. Successor-chain
4//! validation, fork selection, and historical key-validity queries belong to
5//! C1 (#1167). The bytes emitted here are nevertheless the first record in that
6//! future log, so their grammar is a one-way door for every minted account.
7//!
8//! # Rotation custody is structural
9//!
10//! [`GenesisRotationKeys`] is not a `Vec`. It has exactly three ordered slots:
11//!
12//! 0. a required [`UserRotationKey`];
13//! 1. an enrolled recovery key or an explicit
14//!    [`RecoveryKeyEnrollment::Declined`];
15//! 2. an enrolled host key or an explicit [`HostKeyEnrollment::Absent`].
16//!
17//! A [`HostRotationKey`] therefore cannot be passed as priority zero:
18//!
19//! ```compile_fail
20//! use hyprstream_pds::{
21//!     GenesisRotationKeys, HostKeyEnrollment, HostRotationKey,
22//!     RecoveryKeyEnrollment,
23//! };
24//! # fn example(host: HostRotationKey) {
25//! let _ = GenesisRotationKeys::new(
26//!     host,
27//!     RecoveryKeyEnrollment::Declined,
28//!     HostKeyEnrollment::Absent,
29//! );
30//! # }
31//! ```
32//!
33//! The wire form preserves those slots as a fixed three-element
34//! `rotation_keys` array. A declined/absent slot is encoded as a role-bearing
35//! map whose `key` is `null`, so recovery absence is a signed decision rather
36//! than an omitted field or decoder default.
37//!
38//! # Hybrid pin
39//!
40//! Rotation is not an atproto interoperability surface. Every rotation key and
41//! the genesis signature therefore consists of Ed25519 + ML-DSA-65, with both
42//! components required. There is no classical constructor or verification
43//! mode.
44
45use std::collections::BTreeSet;
46
47use anyhow::{bail, ensure, Context, Result};
48use ed25519_dalek::{SigningKey, VerifyingKey};
49use hyprstream_crypto::cose_sign::{
50    assemble_composite_nested, sign_composite, split_composite, verify_composite,
51};
52use hyprstream_crypto::pq::{
53    ml_dsa_sk_to_vk_bytes, ml_dsa_vk_bytes, ml_dsa_vk_from_bytes, MlDsaSigningKey,
54};
55use hyprstream_rpc::identity::UNAUTHENTICATED_DID_SENTINEL;
56
57use crate::cid::Cid;
58use crate::dag_cbor::DagCbor;
59
60/// Version sealed into operation number zero.
61pub const DID_OP_VERSION: u16 = 1;
62/// Domain-separation context bound into both signature components.
63pub const DID_OP_SIGNATURE_CONTEXT: &str = "hyprstream-did-op/1";
64
65const COMPOSITE_ALGORITHM: &str = "id-MLDSA65-Ed25519";
66const ED25519_PUBLIC_KEY_LEN: usize = 32;
67const ED25519_SIGNATURE_LEN: usize = 64;
68const ML_DSA65_PUBLIC_KEY_LEN: usize = 1952;
69const ML_DSA65_SIGNATURE_LEN: usize = 3309;
70const GENESIS_ROTATION_SLOT_COUNT: usize = 3;
71
72/// A pinned-Hybrid public key authorized to control a hosted account.
73///
74/// The fields are private so malformed component lengths cannot be represented.
75#[derive(Clone, Debug, Eq, PartialEq)]
76pub struct HybridRotationKey {
77    ed25519: Vec<u8>,
78    mldsa65: Vec<u8>,
79}
80
81impl HybridRotationKey {
82    /// Construct a rotation key from its mandatory classical and PQ components.
83    pub fn new(ed25519: impl Into<Vec<u8>>, mldsa65: impl Into<Vec<u8>>) -> Result<Self> {
84        let key = Self {
85            ed25519: ed25519.into(),
86            mldsa65: mldsa65.into(),
87        };
88        key.validate()?;
89        Ok(key)
90    }
91
92    /// The Ed25519 verifying-key bytes.
93    pub fn ed25519(&self) -> &[u8] {
94        &self.ed25519
95    }
96
97    /// The ML-DSA-65 verifying-key bytes.
98    pub fn mldsa65(&self) -> &[u8] {
99        &self.mldsa65
100    }
101
102    fn validate(&self) -> Result<()> {
103        ensure!(
104            self.ed25519.len() == ED25519_PUBLIC_KEY_LEN,
105            "rotation Ed25519 key must be {ED25519_PUBLIC_KEY_LEN} bytes"
106        );
107        ensure!(
108            self.mldsa65.len() == ML_DSA65_PUBLIC_KEY_LEN,
109            "rotation ML-DSA-65 key must be {ML_DSA65_PUBLIC_KEY_LEN} bytes"
110        );
111        let ed: [u8; ED25519_PUBLIC_KEY_LEN] = self
112            .ed25519
113            .as_slice()
114            .try_into()
115            .context("rotation Ed25519 key has an invalid length")?;
116        VerifyingKey::from_bytes(&ed).context("rotation Ed25519 key is not a valid point")?;
117        ml_dsa_vk_from_bytes(&self.mldsa65).context("rotation ML-DSA-65 key is invalid")?;
118        Ok(())
119    }
120
121    fn identity(&self) -> Vec<u8> {
122        let mut identity = Vec::with_capacity(self.ed25519.len() + self.mldsa65.len());
123        identity.extend_from_slice(&self.ed25519);
124        identity.extend_from_slice(&self.mldsa65);
125        identity
126    }
127
128    fn to_value(&self) -> DagCbor {
129        DagCbor::str_map([
130            ("ed25519", DagCbor::Bytes(self.ed25519.clone())),
131            ("mldsa65", DagCbor::Bytes(self.mldsa65.clone())),
132        ])
133    }
134
135    fn from_value(value: &DagCbor) -> Result<Self> {
136        reject_unknown(value, &["ed25519", "mldsa65"], "rotation key")?;
137        Self::new(
138            required(value, "ed25519", "rotation key")?
139                .as_bytes()?
140                .to_vec(),
141            required(value, "mldsa65", "rotation key")?
142                .as_bytes()?
143                .to_vec(),
144        )
145    }
146}
147
148macro_rules! custody_key {
149    ($name:ident, $description:literal) => {
150        #[doc = $description]
151        #[derive(Clone, Debug, Eq, PartialEq)]
152        pub struct $name(HybridRotationKey);
153
154        impl $name {
155            /// Bind valid pinned-Hybrid public material to this custody role.
156            pub fn new(key: HybridRotationKey) -> Self {
157                Self(key)
158            }
159
160            /// The role-bound public key.
161            pub fn key(&self) -> &HybridRotationKey {
162                &self.0
163            }
164        }
165    };
166}
167
168custody_key!(
169    UserRotationKey,
170    "The required user-held key occupying genesis priority zero."
171);
172custody_key!(
173    RecoveryRotationKey,
174    "A user-held recovery key kept on a device distinct from the primary key."
175);
176custody_key!(
177    HostRotationKey,
178    "An optional host-held rotation key, representable only at priority two."
179);
180
181/// The deliberate outcome of the recovery-key enrollment offer.
182///
183/// There is intentionally no `Default`: the mint caller must record either a
184/// concrete recovery key or an explicit decline.
185#[derive(Clone, Debug, Eq, PartialEq)]
186pub enum RecoveryKeyEnrollment {
187    Enrolled(RecoveryRotationKey),
188    Declined,
189}
190
191/// Whether the deployment is enrolled as the lowest-priority rotation actor.
192///
193/// There is intentionally no `Default`; absence is sealed explicitly.
194#[derive(Clone, Debug, Eq, PartialEq)]
195pub enum HostKeyEnrollment {
196    Enrolled(HostRotationKey),
197    Absent,
198}
199
200/// A reference to one ordered genesis rotation slot.
201#[derive(Clone, Copy, Debug, Eq, PartialEq)]
202pub struct RotationSlotRef<'a> {
203    pub priority: u8,
204    pub role: &'static str,
205    pub key: Option<&'a HybridRotationKey>,
206}
207
208/// The only representable genesis rotation-key ordering.
209#[derive(Clone, Debug, Eq, PartialEq)]
210pub struct GenesisRotationKeys {
211    user: UserRotationKey,
212    recovery: RecoveryKeyEnrollment,
213    host: HostKeyEnrollment,
214}
215
216impl GenesisRotationKeys {
217    /// Establish the permanent priority order.
218    ///
219    /// Equal key material in two custody slots is rejected: a "recovery" key
220    /// that is the primary key is not recovery, and a host key equal to either
221    /// user-held key would blur the custody boundary.
222    pub fn new(
223        user: UserRotationKey,
224        recovery: RecoveryKeyEnrollment,
225        host: HostKeyEnrollment,
226    ) -> Result<Self> {
227        let keys = Self {
228            user,
229            recovery,
230            host,
231        };
232        keys.validate()?;
233        Ok(keys)
234    }
235
236    pub fn user(&self) -> &UserRotationKey {
237        &self.user
238    }
239
240    pub fn recovery(&self) -> &RecoveryKeyEnrollment {
241        &self.recovery
242    }
243
244    pub fn host(&self) -> &HostKeyEnrollment {
245        &self.host
246    }
247
248    /// Return all three priority slots, including deliberate empty slots.
249    pub fn ordered_slots(&self) -> [RotationSlotRef<'_>; GENESIS_ROTATION_SLOT_COUNT] {
250        let recovery = match &self.recovery {
251            RecoveryKeyEnrollment::Enrolled(key) => Some(key.key()),
252            RecoveryKeyEnrollment::Declined => None,
253        };
254        let host = match &self.host {
255            HostKeyEnrollment::Enrolled(key) => Some(key.key()),
256            HostKeyEnrollment::Absent => None,
257        };
258        [
259            RotationSlotRef {
260                priority: 0,
261                role: "user",
262                key: Some(self.user.key()),
263            },
264            RotationSlotRef {
265                priority: 1,
266                role: "recovery",
267                key: recovery,
268            },
269            RotationSlotRef {
270                priority: 2,
271                role: "host",
272                key: host,
273            },
274        ]
275    }
276
277    fn validate(&self) -> Result<()> {
278        self.user.key().validate()?;
279        let mut identities = BTreeSet::new();
280        ensure!(
281            identities.insert(self.user.key().identity()),
282            "duplicate primary user rotation key"
283        );
284        if let RecoveryKeyEnrollment::Enrolled(key) = &self.recovery {
285            key.key().validate()?;
286            ensure!(
287                identities.insert(key.key().identity()),
288                "recovery rotation key must differ from the primary user key"
289            );
290        }
291        if let HostKeyEnrollment::Enrolled(key) = &self.host {
292            key.key().validate()?;
293            ensure!(
294                identities.insert(key.key().identity()),
295                "host rotation key must differ from every user-held key"
296            );
297        }
298        Ok(())
299    }
300
301    fn to_value(&self) -> DagCbor {
302        DagCbor::list(self.ordered_slots().into_iter().map(|slot| {
303            DagCbor::str_map([
304                (
305                    "key",
306                    slot.key.map_or(DagCbor::Null, HybridRotationKey::to_value),
307                ),
308                ("role", DagCbor::Text(slot.role.to_owned())),
309            ])
310        }))
311    }
312
313    fn from_value(value: &DagCbor) -> Result<Self> {
314        let slots = value.as_list()?;
315        ensure!(
316            slots.len() == GENESIS_ROTATION_SLOT_COUNT,
317            "genesis rotation_keys must contain exactly {GENESIS_ROTATION_SLOT_COUNT} explicit slots"
318        );
319
320        let user = parse_slot(&slots[0], "user")?
321            .map(UserRotationKey::new)
322            .ok_or_else(|| anyhow::anyhow!("priority-zero user rotation key is required"))?;
323        let recovery = match parse_slot(&slots[1], "recovery")? {
324            Some(key) => RecoveryKeyEnrollment::Enrolled(RecoveryRotationKey::new(key)),
325            None => RecoveryKeyEnrollment::Declined,
326        };
327        let host = match parse_slot(&slots[2], "host")? {
328            Some(key) => HostKeyEnrollment::Enrolled(HostRotationKey::new(key)),
329            None => HostKeyEnrollment::Absent,
330        };
331        Self::new(user, recovery, host)
332    }
333}
334
335fn parse_slot(value: &DagCbor, expected_role: &str) -> Result<Option<HybridRotationKey>> {
336    reject_unknown(value, &["key", "role"], "rotation slot")?;
337    let role = required(value, "role", "rotation slot")?.as_str()?;
338    ensure!(
339        role == expected_role,
340        "genesis priority slot for {expected_role:?} cannot contain role {role:?}"
341    );
342    let key = required(value, "key", "rotation slot")?;
343    if key.is_null() {
344        Ok(None)
345    } else {
346        HybridRotationKey::from_value(key).map(Some)
347    }
348}
349
350/// The repo state deliberately recorded at genesis.
351///
352/// `EmptyRepo` encodes as `null`; it means the account has no repo head yet,
353/// not "skip head validation".
354#[derive(Clone, Copy, Debug, Eq, PartialEq)]
355pub enum GenesisRepoHead {
356    EmptyRepo,
357    Existing(Cid),
358}
359
360impl GenesisRepoHead {
361    fn to_value(self) -> DagCbor {
362        match self {
363            Self::EmptyRepo => DagCbor::Null,
364            Self::Existing(cid) => DagCbor::Link(cid),
365        }
366    }
367
368    fn from_value(value: &DagCbor) -> Result<Self> {
369        if value.is_null() {
370            Ok(Self::EmptyRepo)
371        } else {
372            Ok(Self::Existing(*value.as_link()?))
373        }
374    }
375}
376
377/// Operation zero without its signature.
378///
379/// All fields are private so operation zero cannot accidentally acquire a
380/// predecessor, a non-zero sequence, or omit its version.
381#[derive(Clone, Debug, Eq, PartialEq)]
382pub struct UnsignedGenesisDidOp {
383    did: String,
384    doc_cid: Cid,
385    rotation_keys: GenesisRotationKeys,
386    head_at_op: GenesisRepoHead,
387}
388
389impl UnsignedGenesisDidOp {
390    pub fn new(
391        did: impl Into<String>,
392        doc_cid: Cid,
393        rotation_keys: GenesisRotationKeys,
394        head_at_op: GenesisRepoHead,
395    ) -> Result<Self> {
396        let op = Self {
397            did: did.into(),
398            doc_cid,
399            rotation_keys,
400            head_at_op,
401        };
402        op.validate()?;
403        Ok(op)
404    }
405
406    pub fn version(&self) -> u16 {
407        DID_OP_VERSION
408    }
409
410    pub fn sequence(&self) -> u64 {
411        0
412    }
413
414    pub fn did(&self) -> &str {
415        &self.did
416    }
417
418    pub fn doc_cid(&self) -> Cid {
419        self.doc_cid
420    }
421
422    pub fn rotation_keys(&self) -> &GenesisRotationKeys {
423        &self.rotation_keys
424    }
425
426    pub fn head_at_op(&self) -> GenesisRepoHead {
427        self.head_at_op
428    }
429
430    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
431        self.validate()?;
432        Ok(self.to_value().encode())
433    }
434
435    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
436        let value = DagCbor::decode(bytes)?;
437        let op = Self::from_value(&value)?;
438        ensure!(
439            op.to_dag_cbor()? == bytes,
440            "genesis DidOp is not canonical DAG-CBOR"
441        );
442        Ok(op)
443    }
444
445    fn validate(&self) -> Result<()> {
446        ensure!(
447            self.did != UNAUTHENTICATED_DID_SENTINEL,
448            "{UNAUTHENTICATED_DID_SENTINEL} is reserved for the unauthenticated floor and cannot have a genesis operation"
449        );
450        validate_host_form_did_web(&self.did)?;
451        self.rotation_keys.validate()
452    }
453
454    fn to_value(&self) -> DagCbor {
455        DagCbor::str_map([
456            ("did", DagCbor::Text(self.did.clone())),
457            ("doc_cid", DagCbor::Link(self.doc_cid)),
458            ("head_at_op", self.head_at_op.to_value()),
459            ("prev", DagCbor::Null),
460            ("rotation_keys", self.rotation_keys.to_value()),
461            ("seq", DagCbor::Unsigned(0)),
462            ("version", DagCbor::Unsigned(u64::from(DID_OP_VERSION))),
463        ])
464    }
465
466    fn from_value(value: &DagCbor) -> Result<Self> {
467        reject_unknown(
468            value,
469            &[
470                "version",
471                "prev",
472                "seq",
473                "did",
474                "doc_cid",
475                "rotation_keys",
476                "head_at_op",
477            ],
478            "unsigned genesis DidOp",
479        )?;
480        let version = required(value, "version", "unsigned genesis DidOp")?.as_unsigned()?;
481        ensure!(
482            version == u64::from(DID_OP_VERSION),
483            "unsupported genesis DidOp version {version}"
484        );
485        ensure!(
486            required(value, "prev", "unsigned genesis DidOp")?.is_null(),
487            "genesis DidOp prev must be null"
488        );
489        ensure!(
490            required(value, "seq", "unsigned genesis DidOp")?.as_unsigned()? == 0,
491            "genesis DidOp seq must be zero"
492        );
493        Self::new(
494            required(value, "did", "unsigned genesis DidOp")?
495                .as_str()?
496                .to_owned(),
497            *required(value, "doc_cid", "unsigned genesis DidOp")?.as_link()?,
498            GenesisRotationKeys::from_value(required(
499                value,
500                "rotation_keys",
501                "unsigned genesis DidOp",
502            )?)?,
503            GenesisRepoHead::from_value(required(value, "head_at_op", "unsigned genesis DidOp")?)?,
504        )
505    }
506}
507
508/// The decomposed, context-bound composite signature stored in a `DidOp`.
509#[derive(Clone, Debug, Eq, PartialEq)]
510pub struct DidOpSignature {
511    protected: Vec<u8>,
512    ed25519: Vec<u8>,
513    mldsa65: Vec<u8>,
514}
515
516impl DidOpSignature {
517    /// Construct the canonical v1 signature wrapper from raw component
518    /// signatures returned by a user-side composite signer.
519    pub fn from_components(
520        ed25519: impl Into<Vec<u8>>,
521        mldsa65: impl Into<Vec<u8>>,
522    ) -> Result<Self> {
523        Self::new(signature_protected_header(), ed25519, mldsa65)
524    }
525
526    /// Construct from all wire components.
527    ///
528    /// Prefer [`Self::from_components`] for v1 signing. This form exists for
529    /// strict wire decoding and rejects any non-canonical protected header.
530    pub fn new(
531        protected: impl Into<Vec<u8>>,
532        ed25519: impl Into<Vec<u8>>,
533        mldsa65: impl Into<Vec<u8>>,
534    ) -> Result<Self> {
535        let signature = Self {
536            protected: protected.into(),
537            ed25519: ed25519.into(),
538            mldsa65: mldsa65.into(),
539        };
540        signature.validate()?;
541        Ok(signature)
542    }
543
544    pub fn protected(&self) -> &[u8] {
545        &self.protected
546    }
547
548    pub fn ed25519(&self) -> &[u8] {
549        &self.ed25519
550    }
551
552    pub fn mldsa65(&self) -> &[u8] {
553        &self.mldsa65
554    }
555
556    fn validate(&self) -> Result<()> {
557        ensure!(
558            self.protected == signature_protected_header(),
559            "DidOp signature protected header is not the canonical v1 binding"
560        );
561        ensure!(
562            self.ed25519.len() == ED25519_SIGNATURE_LEN,
563            "DidOp Ed25519 signature must be {ED25519_SIGNATURE_LEN} bytes"
564        );
565        ensure!(
566            self.mldsa65.len() == ML_DSA65_SIGNATURE_LEN,
567            "DidOp ML-DSA-65 signature must be {ML_DSA65_SIGNATURE_LEN} bytes"
568        );
569        Ok(())
570    }
571
572    fn to_value(&self) -> DagCbor {
573        DagCbor::str_map([
574            (
575                "context",
576                DagCbor::Text(DID_OP_SIGNATURE_CONTEXT.to_owned()),
577            ),
578            ("ed25519", DagCbor::Bytes(self.ed25519.clone())),
579            ("mldsa65", DagCbor::Bytes(self.mldsa65.clone())),
580            ("protected", DagCbor::Bytes(self.protected.clone())),
581        ])
582    }
583
584    fn from_value(value: &DagCbor) -> Result<Self> {
585        reject_unknown(
586            value,
587            &["context", "protected", "ed25519", "mldsa65"],
588            "DidOp signature",
589        )?;
590        ensure!(
591            required(value, "context", "DidOp signature")?.as_str()? == DID_OP_SIGNATURE_CONTEXT,
592            "DidOp signature context mismatch"
593        );
594        Self::new(
595            required(value, "protected", "DidOp signature")?
596                .as_bytes()?
597                .to_vec(),
598            required(value, "ed25519", "DidOp signature")?
599                .as_bytes()?
600                .to_vec(),
601            required(value, "mldsa65", "DidOp signature")?
602                .as_bytes()?
603                .to_vec(),
604        )
605    }
606}
607
608/// A sealed, self-signed genesis operation.
609#[derive(Clone, Debug, Eq, PartialEq)]
610pub struct GenesisDidOp {
611    unsigned: UnsignedGenesisDidOp,
612    signature: DidOpSignature,
613}
614
615impl GenesisDidOp {
616    /// Verify a user-produced signature and seal operation zero.
617    ///
618    /// Only the required priority-zero user key is accepted. Recovery and host
619    /// keys authorize future operations according to the ordered fork rules;
620    /// neither can self-sign genesis.
621    pub fn seal(unsigned: UnsignedGenesisDidOp, signature: DidOpSignature) -> Result<Self> {
622        unsigned.validate()?;
623        signature.validate()?;
624        verify_signature(
625            &unsigned.to_dag_cbor()?,
626            &signature,
627            unsigned.rotation_keys.user.key(),
628        )?;
629        Ok(Self {
630            unsigned,
631            signature,
632        })
633    }
634
635    pub fn unsigned(&self) -> &UnsignedGenesisDidOp {
636        &self.unsigned
637    }
638
639    pub fn signature(&self) -> &DidOpSignature {
640        &self.signature
641    }
642
643    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
644        self.unsigned.validate()?;
645        self.signature.validate()?;
646        Ok(self.to_value().encode())
647    }
648
649    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
650        let value = DagCbor::decode(bytes)?;
651        reject_unknown(
652            &value,
653            &[
654                "version",
655                "prev",
656                "seq",
657                "did",
658                "doc_cid",
659                "rotation_keys",
660                "head_at_op",
661                "sig",
662            ],
663            "genesis DidOp",
664        )?;
665        let unsigned_value = DagCbor::str_map([
666            ("did", required(&value, "did", "genesis DidOp")?.clone()),
667            (
668                "doc_cid",
669                required(&value, "doc_cid", "genesis DidOp")?.clone(),
670            ),
671            (
672                "head_at_op",
673                required(&value, "head_at_op", "genesis DidOp")?.clone(),
674            ),
675            ("prev", required(&value, "prev", "genesis DidOp")?.clone()),
676            (
677                "rotation_keys",
678                required(&value, "rotation_keys", "genesis DidOp")?.clone(),
679            ),
680            ("seq", required(&value, "seq", "genesis DidOp")?.clone()),
681            (
682                "version",
683                required(&value, "version", "genesis DidOp")?.clone(),
684            ),
685        ]);
686        let unsigned = UnsignedGenesisDidOp::from_value(&unsigned_value)?;
687        let signature = DidOpSignature::from_value(required(&value, "sig", "genesis DidOp")?)?;
688        let op = Self::seal(unsigned, signature)?;
689        ensure!(
690            op.to_dag_cbor()? == bytes,
691            "genesis DidOp is not canonical DAG-CBOR"
692        );
693        Ok(op)
694    }
695
696    pub fn cid(&self) -> Result<Cid> {
697        Ok(Cid::from_dag_cbor(&self.to_dag_cbor()?))
698    }
699
700    fn to_value(&self) -> DagCbor {
701        DagCbor::str_map([
702            ("did", DagCbor::Text(self.unsigned.did.clone())),
703            ("doc_cid", DagCbor::Link(self.unsigned.doc_cid)),
704            ("head_at_op", self.unsigned.head_at_op.to_value()),
705            ("prev", DagCbor::Null),
706            ("rotation_keys", self.unsigned.rotation_keys.to_value()),
707            ("seq", DagCbor::Unsigned(0)),
708            ("sig", self.signature.to_value()),
709            ("version", DagCbor::Unsigned(u64::from(DID_OP_VERSION))),
710        ])
711    }
712}
713
714/// Sign operation zero with the user-held priority-zero key.
715///
716/// This helper is suitable for a user-side signer. The host mint path consumes
717/// the returned signature but never needs either private key.
718pub fn sign_genesis(
719    unsigned: &UnsignedGenesisDidOp,
720    ed25519: &SigningKey,
721    mldsa65: &MlDsaSigningKey,
722) -> Result<DidOpSignature> {
723    unsigned.validate()?;
724    let user_key = unsigned.rotation_keys.user.key();
725    ensure!(
726        user_key.ed25519 == ed25519.verifying_key().to_bytes(),
727        "genesis Ed25519 signer does not match priority-zero user key"
728    );
729    ensure!(
730        user_key.mldsa65 == ml_dsa_sk_to_vk_bytes(mldsa65),
731        "genesis ML-DSA-65 signer does not match priority-zero user key"
732    );
733
734    let protected = signature_protected_header();
735    let composite = sign_composite(ed25519, Some(mldsa65), &unsigned.to_dag_cbor()?, &protected)
736        .context("genesis DidOp composite signing failed")?;
737    let (ed_signature, pq_signature) = split_composite(&composite)?;
738    let pq_signature = pq_signature
739        .ok_or_else(|| anyhow::anyhow!("genesis DidOp signing produced no ML-DSA-65 component"))?;
740    DidOpSignature::new(protected, ed_signature, pq_signature)
741}
742
743fn verify_signature(
744    payload: &[u8],
745    signature: &DidOpSignature,
746    key: &HybridRotationKey,
747) -> Result<()> {
748    signature.validate()?;
749    key.validate()?;
750    let ed_bytes: [u8; ED25519_PUBLIC_KEY_LEN] = key
751        .ed25519
752        .as_slice()
753        .try_into()
754        .context("rotation Ed25519 key has an invalid length")?;
755    let ed_vk = VerifyingKey::from_bytes(&ed_bytes).context("rotation Ed25519 key is invalid")?;
756    let pq_vk = ml_dsa_vk_from_bytes(&key.mldsa65).context("rotation ML-DSA-65 key is invalid")?;
757    let composite = assemble_composite_nested(
758        (ed_vk.to_bytes().to_vec(), signature.ed25519.clone()),
759        Some((ml_dsa_vk_bytes(&pq_vk), signature.mldsa65.clone())),
760    )
761    .context("failed to reassemble genesis DidOp composite signature")?;
762    let verified = verify_composite(
763        &composite,
764        &ed_vk,
765        Some(&pq_vk),
766        payload,
767        &signature_protected_header(),
768        true,
769    )
770    .context("genesis DidOp priority-zero signature verification failed")?;
771    ensure!(
772        verified.eddsa && verified.ml_dsa,
773        "genesis DidOp did not verify both pinned-Hybrid components"
774    );
775    Ok(())
776}
777
778fn signature_protected_header() -> Vec<u8> {
779    DagCbor::str_map([
780        ("alg", DagCbor::Text(COMPOSITE_ALGORITHM.to_owned())),
781        (
782            "context",
783            DagCbor::Text(DID_OP_SIGNATURE_CONTEXT.to_owned()),
784        ),
785    ])
786    .encode()
787}
788
789/// Validate the host-only `did:web` form used for accounts.
790///
791/// The future A2/A3 mint seam supplies an allocated label and deployment zone;
792/// this check independently refuses path-form, port-bearing, uppercase, or
793/// non-LDH DIDs before their value is permanently signed.
794pub(crate) fn validate_host_form_did_web(did: &str) -> Result<()> {
795    let host = did
796        .strip_prefix("did:web:")
797        .ok_or_else(|| anyhow::anyhow!("hosted account DID must use did:web"))?;
798    ensure!(!host.is_empty(), "hosted account did:web host is empty");
799    ensure!(
800        !host.contains(':') && !host.contains('/') && !host.contains('%'),
801        "hosted account DID must be host-form did:web without path, port, or percent encoding"
802    );
803    ensure!(
804        host == host.to_ascii_lowercase(),
805        "hosted account DID must already be lowercase"
806    );
807    let labels = host.split('.').collect::<Vec<_>>();
808    ensure!(
809        labels.len() >= 2,
810        "hosted account DID must contain a deployment-qualified DNS host"
811    );
812    ensure!(
813        host.len() <= 253,
814        "hosted account DID host exceeds DNS limit"
815    );
816    for label in labels {
817        ensure!(
818            !label.is_empty() && label.len() <= 63,
819            "hosted account DID contains an empty or oversized DNS label"
820        );
821        ensure!(
822            label
823                .bytes()
824                .all(|byte| { byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-' }),
825            "hosted account DID labels must be lowercase LDH"
826        );
827        ensure!(
828            !label.starts_with('-') && !label.ends_with('-'),
829            "hosted account DID labels must not start or end with a hyphen"
830        );
831    }
832    Ok(())
833}
834
835fn required<'a>(value: &'a DagCbor, key: &str, what: &str) -> Result<&'a DagCbor> {
836    value
837        .get(key)
838        .ok_or_else(|| anyhow::anyhow!("{what} missing required field {key:?}"))
839}
840
841fn reject_unknown(value: &DagCbor, allowed: &[&str], what: &str) -> Result<()> {
842    let allowed = allowed.iter().copied().collect::<BTreeSet<_>>();
843    for (key, _) in value.as_map()? {
844        let key = key.as_str()?;
845        if !allowed.contains(key) {
846            bail!("{what} contains unknown field {key:?}");
847        }
848    }
849    Ok(())
850}
851
852#[cfg(test)]
853mod tests {
854    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
855
856    use super::*;
857    use hyprstream_crypto::pq::{
858        ml_dsa_generate_keypair, ml_dsa_sk_from_seed, ml_dsa_sk_to_vk_bytes, ml_dsa_vk_bytes,
859        MlDsaSigningKey,
860    };
861    use rand::rngs::OsRng;
862    use sha2::{Digest as _, Sha256};
863
864    struct Signer {
865        ed: SigningKey,
866        pq: MlDsaSigningKey,
867        public: HybridRotationKey,
868    }
869
870    fn signer() -> Signer {
871        let ed = SigningKey::generate(&mut OsRng);
872        let (pq, pq_vk) = ml_dsa_generate_keypair();
873        let public =
874            HybridRotationKey::new(ed.verifying_key().to_bytes(), ml_dsa_vk_bytes(&pq_vk)).unwrap();
875        Signer { ed, pq, public }
876    }
877
878    fn unsigned(
879        user: &Signer,
880        recovery: RecoveryKeyEnrollment,
881        host: HostKeyEnrollment,
882    ) -> UnsignedGenesisDidOp {
883        UnsignedGenesisDidOp::new(
884            "did:web:alice.acct.example.com",
885            Cid::from_raw(b"sealed did document"),
886            GenesisRotationKeys::new(UserRotationKey::new(user.public.clone()), recovery, host)
887                .unwrap(),
888            GenesisRepoHead::EmptyRepo,
889        )
890        .unwrap()
891    }
892
893    #[test]
894    fn unauthenticated_sentinel_cannot_have_a_genesis_operation() {
895        let user = signer();
896        let rotations = GenesisRotationKeys::new(
897            UserRotationKey::new(user.public),
898            RecoveryKeyEnrollment::Declined,
899            HostKeyEnrollment::Absent,
900        )
901        .unwrap();
902
903        let error = UnsignedGenesisDidOp::new(
904            UNAUTHENTICATED_DID_SENTINEL,
905            Cid::from_raw(b"sentinel must not have a document"),
906            rotations,
907            GenesisRepoHead::EmptyRepo,
908        )
909        .unwrap_err();
910        assert!(
911            error.to_string().contains("unauthenticated floor"),
912            "{error:#}"
913        );
914    }
915
916    #[test]
917    fn host_role_at_priority_zero_is_rejected_on_decode() {
918        let user = signer();
919        let rotations = GenesisRotationKeys::new(
920            UserRotationKey::new(user.public),
921            RecoveryKeyEnrollment::Declined,
922            HostKeyEnrollment::Absent,
923        )
924        .unwrap();
925        let mut slots = rotations.to_value().as_list().unwrap().to_vec();
926        slots[0] = DagCbor::str_map([
927            ("key", slots[0].get("key").expect("slot key").clone()),
928            ("role", DagCbor::Text("host".to_owned())),
929        ]);
930        let error = GenesisRotationKeys::from_value(&DagCbor::List(slots)).unwrap_err();
931        assert!(error.to_string().contains("cannot contain role"));
932    }
933
934    #[test]
935    fn missing_priority_zero_user_key_is_rejected() {
936        let rotations = DagCbor::list([
937            DagCbor::str_map([
938                ("key", DagCbor::Null),
939                ("role", DagCbor::Text("user".to_owned())),
940            ]),
941            DagCbor::str_map([
942                ("key", DagCbor::Null),
943                ("role", DagCbor::Text("recovery".to_owned())),
944            ]),
945            DagCbor::str_map([
946                ("key", DagCbor::Null),
947                ("role", DagCbor::Text("host".to_owned())),
948            ]),
949        ]);
950        let error = GenesisRotationKeys::from_value(&rotations).unwrap_err();
951        assert!(error.to_string().contains("priority-zero user"));
952    }
953
954    #[test]
955    fn declined_recovery_is_explicit_in_signed_bytes() {
956        let user = signer();
957        let unsigned = unsigned(
958            &user,
959            RecoveryKeyEnrollment::Declined,
960            HostKeyEnrollment::Absent,
961        );
962        let value = DagCbor::decode(&unsigned.to_dag_cbor().unwrap()).unwrap();
963        let slots = value.get("rotation_keys").unwrap().as_list().unwrap();
964        assert_eq!(slots.len(), 3);
965        assert_eq!(slots[1].get("role").unwrap().as_str().unwrap(), "recovery");
966        assert!(slots[1].get("key").unwrap().is_null());
967
968        let roundtrip =
969            UnsignedGenesisDidOp::from_dag_cbor(&unsigned.to_dag_cbor().unwrap()).unwrap();
970        assert_eq!(
971            roundtrip.rotation_keys().recovery(),
972            &RecoveryKeyEnrollment::Declined
973        );
974    }
975
976    #[test]
977    fn sealed_ordering_roundtrips_byte_exactly() {
978        let user = signer();
979        let recovery = signer();
980        let host = signer();
981        let unsigned = unsigned(
982            &user,
983            RecoveryKeyEnrollment::Enrolled(RecoveryRotationKey::new(recovery.public.clone())),
984            HostKeyEnrollment::Enrolled(HostRotationKey::new(host.public.clone())),
985        );
986        let signature = sign_genesis(&unsigned, &user.ed, &user.pq).unwrap();
987        let sealed = GenesisDidOp::seal(unsigned, signature).unwrap();
988        let bytes = sealed.to_dag_cbor().unwrap();
989        let decoded = GenesisDidOp::from_dag_cbor(&bytes).unwrap();
990        assert_eq!(decoded.to_dag_cbor().unwrap(), bytes);
991
992        let slots = decoded.unsigned().rotation_keys().ordered_slots();
993        assert_eq!(
994            slots.map(|slot| (slot.priority, slot.role)),
995            [(0, "user"), (1, "recovery"), (2, "host")]
996        );
997        assert_eq!(slots[0].key, Some(&user.public));
998        assert_eq!(slots[1].key, Some(&recovery.public));
999        assert_eq!(slots[2].key, Some(&host.public));
1000    }
1001
1002    #[test]
1003    fn operation_zero_contains_version_from_first_signed_bytes() {
1004        let user = signer();
1005        let unsigned = unsigned(
1006            &user,
1007            RecoveryKeyEnrollment::Declined,
1008            HostKeyEnrollment::Absent,
1009        );
1010        let signature = sign_genesis(&unsigned, &user.ed, &user.pq).unwrap();
1011        let bytes = GenesisDidOp::seal(unsigned, signature)
1012            .unwrap()
1013            .to_dag_cbor()
1014            .unwrap();
1015        let value = DagCbor::decode(&bytes).unwrap();
1016        assert_eq!(
1017            value.get("version").unwrap().as_unsigned().unwrap(),
1018            u64::from(DID_OP_VERSION)
1019        );
1020        assert_eq!(value.get("seq").unwrap().as_unsigned().unwrap(), 0);
1021        assert!(value.get("prev").unwrap().is_null());
1022    }
1023
1024    #[test]
1025    fn tampering_a_signed_field_fails_closed() {
1026        let user = signer();
1027        let unsigned = unsigned(
1028            &user,
1029            RecoveryKeyEnrollment::Declined,
1030            HostKeyEnrollment::Absent,
1031        );
1032        let signature = sign_genesis(&unsigned, &user.ed, &user.pq).unwrap();
1033        let tampered = UnsignedGenesisDidOp::new(
1034            unsigned.did().to_owned(),
1035            Cid::from_raw(b"different document"),
1036            unsigned.rotation_keys().clone(),
1037            unsigned.head_at_op(),
1038        )
1039        .unwrap();
1040        assert!(GenesisDidOp::seal(tampered, signature).is_err());
1041    }
1042
1043    #[test]
1044    fn tampered_mldsa_component_cannot_downgrade_genesis_to_classical_only() {
1045        let user = signer();
1046        let unsigned = unsigned(
1047            &user,
1048            RecoveryKeyEnrollment::Declined,
1049            HostKeyEnrollment::Absent,
1050        );
1051        let signature = sign_genesis(&unsigned, &user.ed, &user.pq).unwrap();
1052        let mut tampered_pq = signature.mldsa65().to_vec();
1053        tampered_pq[0] ^= 1;
1054        let tampered =
1055            DidOpSignature::from_components(signature.ed25519().to_vec(), tampered_pq).unwrap();
1056
1057        assert!(
1058            GenesisDidOp::seal(unsigned, tampered).is_err(),
1059            "genesis sealing must require a valid ML-DSA-65 signature as well as Ed25519"
1060        );
1061    }
1062
1063    #[test]
1064    fn duplicate_custody_keys_are_rejected() {
1065        let user = signer();
1066        let error = GenesisRotationKeys::new(
1067            UserRotationKey::new(user.public.clone()),
1068            RecoveryKeyEnrollment::Enrolled(RecoveryRotationKey::new(user.public.clone())),
1069            HostKeyEnrollment::Absent,
1070        )
1071        .unwrap_err();
1072        assert!(error
1073            .to_string()
1074            .contains("recovery rotation key must differ"));
1075    }
1076
1077    #[test]
1078    fn path_form_did_is_never_sealable() {
1079        let user = signer();
1080        let rotations = GenesisRotationKeys::new(
1081            UserRotationKey::new(user.public),
1082            RecoveryKeyEnrollment::Declined,
1083            HostKeyEnrollment::Absent,
1084        )
1085        .unwrap();
1086        assert!(UnsignedGenesisDidOp::new(
1087            "did:web:example.com:users:alice",
1088            Cid::from_raw(b"doc"),
1089            rotations,
1090            GenesisRepoHead::EmptyRepo,
1091        )
1092        .is_err());
1093    }
1094
1095    #[test]
1096    fn genesis_v1_unsigned_wire_digest_is_frozen() {
1097        let ed = SigningKey::from_bytes(&[7_u8; 32]);
1098        let pq = ml_dsa_sk_from_seed(&[8_u8; 32]);
1099        let user =
1100            HybridRotationKey::new(ed.verifying_key().to_bytes(), ml_dsa_sk_to_vk_bytes(&pq))
1101                .unwrap();
1102        let op = UnsignedGenesisDidOp::new(
1103            "did:web:alice.acct.example.com",
1104            Cid::from_raw(b"canonical did document fixture"),
1105            GenesisRotationKeys::new(
1106                UserRotationKey::new(user),
1107                RecoveryKeyEnrollment::Declined,
1108                HostKeyEnrollment::Absent,
1109            )
1110            .unwrap(),
1111            GenesisRepoHead::EmptyRepo,
1112        )
1113        .unwrap();
1114        let digest: [u8; 32] = Sha256::digest(op.to_dag_cbor().unwrap()).into();
1115        assert_eq!(
1116            digest,
1117            [
1118                203, 83, 224, 124, 141, 189, 39, 233, 164, 155, 250, 243, 220, 177, 180, 209, 123,
1119                118, 237, 64, 150, 190, 19, 13, 216, 118, 245, 117, 206, 73, 156, 47,
1120            ]
1121        );
1122    }
1123}