Skip to main content

hyprstream_core/services/oauth/
did_document.rs

1//! did:web document endpoints (Phase 0c).
2//!
3//! Serves DID documents at:
4//!   - `GET /.well-known/did.json` — root deployment DID (controller for all keys
5//!     under this issuer's authority)
6//!   - `GET /users/:username/did.json` — hard error while path-form account DID
7//!     minting is frozen (#1159)
8//!   - `GET /clients/:client_id/did.json` — per-client DID document (for Tier 3
9//!     confidential clients with registered keys)
10//!
11//! All documents follow the W3C DID Core 1.0 + did:web 1.0 conventions. All
12//! key-bearing verification methods use the `Multikey` type with a
13//! multicodec-prefixed `publicKeyMultibase` (ed25519 z6Mk form; p256 / ML-DSA-65
14//! likewise), matching the atproto `#atproto` VM and the `did:key` encoding.
15//!
16//! The **root** document is additionally **atproto-compatible** (#154): when an
17//! ES256 key store is present it carries a P-256 `#atproto` `Multikey`, an
18//! `#atproto_pds` service, and `alsoKnownAs at://{handle}` — the shape existing
19//! atproto resolvers expect. Our Ed25519 mesh verification method and any typed
20//! transport `service` entries (IrohTransport/QuicTransport/OnionTransport) are
21//! **optional, additive**, and ignored by atproto (which matches by id/type).
22//! P-256 satisfies atproto (it accepts p256/k256); k256 is not used.
23//!
24//! The format produced here matches the architecture-doc Subject Identity
25//! Format section and is consumed by:
26//!   - Federation peers verifying did:web subjects in tokens
27//!   - Clients that want to discover an issuer's signing keys without OAuth
28//!     metadata fetch
29//!   - The Phase 1c `private_key_jwt` flow's client-key lookup
30
31use std::sync::Arc;
32
33use axum::{
34    extract::{Path, State},
35    http::{header, StatusCode},
36    response::{IntoResponse, Response},
37    Json,
38};
39use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
40use ed25519_dalek::VerifyingKey;
41use serde_json::{json, Value};
42
43use super::state::{atproto_service_did_for_origin, OAuthState};
44
45/// The node's live, self-certifying at9p identity.
46///
47/// The canonical capsule bytes and their CID are built together from the same
48/// in-process key that renders the root did:web document, so the two public
49/// representations cannot drift apart.
50#[derive(Clone, Debug)]
51pub(crate) struct RenderedAt9pIdentity {
52    pub did: String,
53    pub cid512: String,
54    pub capsule: Arc<[u8]>,
55}
56
57/// Build the multibase z-encoded Ed25519 public-key string per the
58/// `Ed25519VerificationKey2020` spec.
59///
60/// The multibase prefix `z` means base58btc; the actual key payload is
61/// `0xed 0x01 || raw_pubkey_bytes` (multicodec ed25519-pub varint header).
62fn ed25519_to_multibase(vk: &VerifyingKey) -> String {
63    // 0xed01 is the multicodec prefix for ed25519-pub (RFC: did:key spec).
64    let mut payload = Vec::with_capacity(34);
65    payload.push(0xed);
66    payload.push(0x01);
67    payload.extend_from_slice(vk.as_bytes());
68    format!("z{}", bs58::encode(payload).into_string())
69}
70
71/// Extract the origin (scheme://authority) from the OAuth issuer URL.
72///
73/// atproto's `#atproto_pds` serviceEndpoint must be an origin only — scheme,
74/// host, optional port — with no path. (atproto/specs/did)
75fn issuer_origin(issuer_url: &str) -> Option<String> {
76    let (scheme, rest) = issuer_url.split_once("://")?;
77    let authority = rest.split('/').next().unwrap_or(rest);
78    if authority.is_empty() {
79        None
80    } else {
81        Some(format!("{scheme}://{authority}"))
82    }
83}
84
85/// Render the node's at9p genesis capsule from keys already held by
86/// hyprstream.
87pub(crate) fn render_at9p_identity(
88    issuer_url: &str,
89    ed_sk: &ed25519_dalek::SigningKey,
90    pq_sk: &hyprstream_rpc::crypto::pq::MlDsaSigningKey,
91) -> anyhow::Result<RenderedAt9pIdentity> {
92    use hyprstream_pds::at9p::{
93        CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
94    };
95    use hyprstream_pds::at9p_sign::sign_capsule;
96
97    let did = atproto_service_did_for_origin(issuer_url)
98        .ok_or_else(|| anyhow::anyhow!("OAuth issuer URL has no supported service DID"))?;
99    let origin = issuer_origin(issuer_url)
100        .ok_or_else(|| anyhow::anyhow!("OAuth issuer URL has no origin"))?;
101    anyhow::ensure!(
102        origin.starts_with("https://"),
103        "at9p identity publication requires an HTTPS OAuth issuer"
104    );
105
106    let subject_key = HybridKeyPair::new(
107        ed_sk.verifying_key().to_bytes(),
108        hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(pq_sk),
109    )?;
110    let endpoint = ServiceEndpoint::new(Transport::Https, origin)?;
111    let service = ServiceEntry::new("#pds", ServiceType::AtprotoPds, endpoint)?;
112    let mut body = CapsuleBody::new(vec![subject_key], vec![service])?;
113    body.also_known_as = Some(vec![did]);
114
115    let capsule = sign_capsule(body, ed_sk, pq_sk)?;
116    let capsule_bytes = capsule.to_dag_cbor()?;
117    let cid512 = capsule.cid512()?;
118    Ok(RenderedAt9pIdentity {
119        did: format!("did:at9p:{cid512}"),
120        cid512,
121        capsule: Arc::from(capsule_bytes),
122    })
123}
124
125fn normalize_atproto_handle(handle: &str) -> Option<String> {
126    let handle = handle.trim_end_matches('.').to_ascii_lowercase();
127    if handle.len() > 253 || handle.split('.').count() < 2 {
128        return None;
129    }
130    let valid = handle.split('.').all(|label| {
131        !label.is_empty()
132            && label.len() <= 63
133            && !label.starts_with('-')
134            && !label.ends_with('-')
135            && label
136                .bytes()
137                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
138    });
139    valid.then_some(handle)
140}
141
142fn configured_handle_host(issuer_url: &str) -> Option<String> {
143    let url = url::Url::parse(issuer_url).ok()?;
144    match url.host()? {
145        url::Host::Domain(host) => normalize_atproto_handle(host),
146        url::Host::Ipv4(_) | url::Host::Ipv6(_) => None,
147    }
148}
149
150#[cfg(test)]
151fn account_handle(username: &str, issuer_url: &str) -> Option<String> {
152    let host = configured_handle_host(issuer_url)?;
153    normalize_atproto_handle(&format!("{username}.{host}"))
154}
155
156/// Build the multibase z-encoded P-256 public key per the `Multikey` /
157/// did:key conventions used by atproto.
158///
159/// Multibase prefix `z` (base58btc); payload is the multicodec `p256-pub`
160/// unsigned-varint header (`0x1200` → bytes `0x80 0x24`) followed by the
161/// **compressed** SEC1 point (33 bytes). atproto requires compressed pubkeys.
162fn p256_to_multibase(vk: &p256::ecdsa::VerifyingKey) -> String {
163    let point = vk.to_encoded_point(true); // compressed
164    let compressed = point.as_bytes();
165    let mut payload = Vec::with_capacity(2 + compressed.len());
166    payload.push(0x80);
167    payload.push(0x24);
168    payload.extend_from_slice(compressed);
169    format!("z{}", bs58::encode(payload).into_string())
170}
171
172/// multicodec `ml-dsa-65-pub` unsigned-varint prefix.
173///
174/// Code point `0x1211` (FIPS 204 / ML-DSA-65 public key) from the multiformats
175/// multicodec registry (status: draft); see also draft-ietf-cose-mldsa. As an
176/// unsigned varint `0x1211` encodes to the two bytes `0x91 0x24` — same shape as
177/// `p256-pub` (`0x1200` → `0x80 0x24`).
178const MULTICODEC_ML_DSA_65_PUB: [u8; 2] = [0x91, 0x24];
179
180/// Build the multibase z-encoded ML-DSA-65 public key as a `Multikey`-compatible
181/// `publicKeyMultibase` value.
182///
183/// Multibase prefix `z` (base58btc); payload is the multicodec `ml-dsa-65-pub`
184/// unsigned-varint header (`0x1211` → bytes `0x91 0x24`) followed by the raw
185/// ML-DSA-65 verifying-key bytes (1952 bytes, FIPS 204). The input is the raw
186/// public-key bytes (e.g. from `Signer::pq_pubkey()` / `ml_dsa_vk_bytes`), so
187/// this helper stays decoupled from the concrete `ml_dsa` key type and can be
188/// called by #157 when it publishes the `#mesh` PQ key.
189fn mldsa65_to_multibase(vk_bytes: &[u8]) -> String {
190    let mut payload = Vec::with_capacity(MULTICODEC_ML_DSA_65_PUB.len() + vk_bytes.len());
191    payload.extend_from_slice(&MULTICODEC_ML_DSA_65_PUB);
192    payload.extend_from_slice(vk_bytes);
193    format!("z{}", bs58::encode(payload).into_string())
194}
195
196/// The node's atproto-native identity to embed in the root DID document:
197/// the active P-256 signing key plus the account handle. Bounded overlap keys
198/// use distinct fragments so stock atproto resolvers continue selecting only
199/// the active `#atproto` method.
200pub struct AtprotoIdentity<'a> {
201    pub p256_vk: &'a p256::ecdsa::VerifyingKey,
202    pub handle: &'a str,
203    pub drain: Option<AtprotoOverlapKey<'a>>,
204    pub lead: Option<AtprotoOverlapKey<'a>>,
205}
206
207/// A bounded verification-only overlap key. It is never selected for signing.
208pub struct AtprotoOverlapKey<'a> {
209    pub vk: &'a p256::ecdsa::VerifyingKey,
210    pub nbf: i64,
211    pub exp: i64,
212}
213
214/// An optional, additive transport endpoint advertised as a typed `service`
215/// entry (DIDComm-style map). atproto resolvers ignore these; the mesh dial
216/// resolves by `service.type`.
217pub struct TransportEndpoint {
218    /// Fragment id, e.g. `"iroh"` → `{did}#iroh`.
219    pub fragment: String,
220    /// Service `type`, e.g. `"IrohTransport"`.
221    pub vm_type: String,
222    /// The `serviceEndpoint` map (e.g. `{ "uri": ..., "accept": [...] }`).
223    pub endpoint: Value,
224}
225
226/// Build the atproto `#atproto` verification method (P-256 `Multikey`).
227pub(crate) fn atproto_verification_method(did: &str, vk: &p256::ecdsa::VerifyingKey) -> Value {
228    json!({
229        "id": format!("{did}#atproto"),
230        "type": "Multikey",
231        "controller": did,
232        "publicKeyMultibase": p256_to_multibase(vk),
233    })
234}
235
236fn atproto_overlap_verification_method(
237    did: &str,
238    fragment: &str,
239    key: &AtprotoOverlapKey<'_>,
240) -> Value {
241    json!({
242        "id": format!("{did}#{fragment}"),
243        "type": "Multikey",
244        "controller": did,
245        "publicKeyMultibase": p256_to_multibase(key.vk),
246        "nbf": key.nbf,
247        "exp": key.exp,
248    })
249}
250
251/// Build the active plus bounded drain/lead VMs used by the producer. The
252/// auxiliary fragments are deliberately distinct: upstream resolvers select
253/// the first exact `#atproto` fragment and ignore these entries.
254pub fn atproto_verification_methods(
255    did: &str,
256    active: &p256::ecdsa::VerifyingKey,
257    drain: Option<AtprotoOverlapKey<'_>>,
258    lead: Option<AtprotoOverlapKey<'_>>,
259) -> Vec<Value> {
260    let mut methods = vec![atproto_verification_method(did, active)];
261    if let Some(drain) = drain {
262        methods.push(atproto_overlap_verification_method(
263            did,
264            "atproto_drain",
265            &drain,
266        ));
267    }
268    if let Some(lead) = lead {
269        methods.push(atproto_overlap_verification_method(
270            did,
271            "atproto_lead",
272            &lead,
273        ));
274    }
275    methods
276}
277
278/// Build the verification-method JSON for a single Ed25519 key under a
279/// did:web subject.
280///
281/// Emitted as `type: "Multikey"` (W3C / atproto canonical VM type): the
282/// `publicKeyMultibase` value `ed25519_to_multibase` produces is already the
283/// multicodec-prefixed (`0xed01`) base58btc form `Multikey` requires, so this
284/// is the same shape used for `#atproto` (p256) and matches the `did:key`
285/// encoding (multicodec/multibase) for cross-tool interop.
286fn ed25519_verification_method(did: &str, key_id: &str, vk: &VerifyingKey) -> Value {
287    json!({
288        "id": format!("{did}#{key_id}"),
289        "type": "Multikey",
290        "controller": did,
291        "publicKeyMultibase": ed25519_to_multibase(vk),
292    })
293}
294
295/// Build the verification-method JSON for an ML-DSA-65 (post-quantum) key under
296/// a did:web subject, emitted as a `Multikey` with the registered
297/// `ml-dsa-65-pub` multicodec (`0x1211`).
298///
299/// `vk_bytes` is the raw ML-DSA-65 verifying-key (1952 bytes). The root DID
300/// document publishes the node's mesh ML-DSA-65 key as `#mesh-pq` (#157) so
301/// peers can anchor it in their `KeyedPqTrustStore`.
302fn mldsa65_verification_method(did: &str, key_id: &str, vk_bytes: &[u8]) -> Value {
303    json!({
304        "id": format!("{did}#{key_id}"),
305        "type": "Multikey",
306        "controller": did,
307        "publicKeyMultibase": mldsa65_to_multibase(vk_bytes),
308    })
309}
310
311// ============================================================================
312// #mesh-kem hybrid keyAgreement identity (S1 / #552, epic #550)
313// ============================================================================
314
315/// multicodec `x25519-pub` unsigned-varint prefix (`0xec` → bytes `0xec 0x01`).
316const MULTICODEC_X25519_PUB: [u8; 2] = [0xec, 0x01];
317
318/// multicodec `mlkem-768-pub` unsigned-varint prefix.
319///
320/// Code point `0x120c` (ML-KEM-768 / FIPS 203 encapsulation key) from the
321/// multiformats multicodec registry (`table.csv`, status: draft) — confirmed
322/// against the upstream registry (NOT `0x120b`, which is `mlkem-512-pub`; a
323/// one-code-point mixup there would silently anchor peers to the wrong key
324/// size). As an unsigned varint, `0x120c` encodes to the two bytes `0x8c 0x24`
325/// (same shape as `ml-dsa-65-pub` `0x1211` → `0x91 0x24`).
326const MULTICODEC_ML_KEM_768_PUB: [u8; 2] = [0x8c, 0x24];
327
328/// Multibase z-encode (base58btc, multicodec-prefixed) a raw X25519 encapsulation
329/// key (32 bytes) as a `Multikey` `publicKeyMultibase`.
330fn x25519_to_multibase(ek_bytes: &[u8]) -> String {
331    let mut payload = Vec::with_capacity(MULTICODEC_X25519_PUB.len() + ek_bytes.len());
332    payload.extend_from_slice(&MULTICODEC_X25519_PUB);
333    payload.extend_from_slice(ek_bytes);
334    format!("z{}", bs58::encode(payload).into_string())
335}
336
337/// Multibase z-encode a raw ML-KEM-768 encapsulation key (1184 bytes) as a
338/// `Multikey` `publicKeyMultibase`.
339fn mlkem768_to_multibase(ek_bytes: &[u8]) -> String {
340    let mut payload = Vec::with_capacity(MULTICODEC_ML_KEM_768_PUB.len() + ek_bytes.len());
341    payload.extend_from_slice(&MULTICODEC_ML_KEM_768_PUB);
342    payload.extend_from_slice(ek_bytes);
343    format!("z{}", bs58::encode(payload).into_string())
344}
345
346/// Build the `#mesh-kem` **keyAgreement** verification methods for the node's
347/// hybrid-KEM identity (S1 / #552): one `Multikey` per suite leg (X25519 +
348/// ML-KEM-768). These belong in the DID document's `keyAgreement` relationship
349/// (NOT `verificationMethod`/`assertionMethod` — they are key-agreement, not
350/// signing, keys). Peers reconstruct the policy-pinned hybrid recipient
351/// (`SuiteId::HyKemX25519MlKem768`) from the two legs and anchor it in their
352/// `crate`-side `KemTrustStore`.
353///
354/// `x25519_ek` / `mlkem768_ek` are the raw encapsulation keys in suite-component
355/// order, from `hyprstream_rpc::node_identity::derive_mesh_kem_recipient(..)
356/// .public().eks`.
357fn mesh_kem_key_agreement_methods(did: &str, x25519_ek: &[u8], mlkem768_ek: &[u8]) -> Vec<Value> {
358    vec![
359        json!({
360            "id": format!("{did}#mesh-kem-x25519"),
361            "type": "Multikey",
362            "controller": did,
363            "publicKeyMultibase": x25519_to_multibase(x25519_ek),
364        }),
365        json!({
366            "id": format!("{did}#mesh-kem-mlkem768"),
367            "type": "Multikey",
368            "controller": did,
369            "publicKeyMultibase": mlkem768_to_multibase(mlkem768_ek),
370        }),
371    ]
372}
373
374/// Build the `keyAgreement` entries for a node's `#mesh-kem` recipient public
375/// material, embedding the VMs directly in the `keyAgreement` relationship
376/// array (did:key convention — not cross-referenced via `verificationMethod`,
377/// since these are key-agreement-only keys, never used for signing).
378///
379/// Validates the suite shape defensively (exactly the 2 components of
380/// `SuiteId::HyKemX25519MlKem768`, X25519 then ML-KEM-768) before emitting —
381/// `recipient_public` only ever comes from this node's own
382/// `derive_mesh_kem_recipient`, but a shape mismatch must fail closed (publish
383/// an empty `keyAgreement` relationship) rather than publish a malformed or
384/// misordered key that a peer would silently mis-anchor.
385fn mesh_kem_key_agreement(
386    did: &str,
387    recipient_public: Option<&hyprstream_rpc::crypto::hybrid_kem::RecipientPublic>,
388) -> Vec<Value> {
389    use hyprstream_rpc::crypto::hybrid_kem::SuiteId;
390    let Some(pub_material) = recipient_public else {
391        return Vec::new();
392    };
393    // `SuiteId::HyKemX25519MlKem768.components()` is `[X25519, MlKem768]` by
394    // construction, so pinning the suite id here also pins the component
395    // order below.
396    if pub_material.suite_id != SuiteId::HyKemX25519MlKem768 {
397        return Vec::new();
398    }
399    let [x25519_ek, mlkem768_ek] = &pub_material.eks[..] else {
400        return Vec::new();
401    };
402    mesh_kem_key_agreement_methods(did, x25519_ek, mlkem768_ek)
403}
404
405#[cfg(test)]
406#[allow(clippy::unwrap_used, clippy::expect_used)]
407mod mesh_kem_did_tests {
408    use super::*;
409
410    #[test]
411    fn mesh_kem_methods_shape_and_multicodec() {
412        let did = "did:web:example.com";
413        let x_ek = [0x11u8; 32];
414        let m_ek = [0x22u8; 1184];
415        let vms = mesh_kem_key_agreement_methods(did, &x_ek, &m_ek);
416        assert_eq!(vms.len(), 2);
417        assert_eq!(vms[0]["id"], format!("{did}#mesh-kem-x25519"));
418        assert_eq!(vms[0]["type"], "Multikey");
419        assert_eq!(vms[1]["id"], format!("{did}#mesh-kem-mlkem768"));
420        assert_eq!(vms[1]["type"], "Multikey");
421
422        // publicKeyMultibase = 'z' + base58btc(multicodec ‖ key); decode + check.
423        let mb = vms[0]["publicKeyMultibase"].as_str().unwrap();
424        assert!(mb.starts_with('z'));
425        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
426        assert_eq!(&decoded[..2], &MULTICODEC_X25519_PUB);
427        assert_eq!(decoded.len(), 2 + 32);
428
429        let mb2 = vms[1]["publicKeyMultibase"].as_str().unwrap();
430        let decoded2 = bs58::decode(&mb2[1..]).into_vec().unwrap();
431        assert_eq!(&decoded2[..2], &MULTICODEC_ML_KEM_768_PUB);
432        assert_eq!(decoded2.len(), 2 + 1184);
433    }
434}
435
436/// Build a JWK fallback verification method (useful for consumers that
437/// don't speak Multibase but understand JWK).
438fn ed25519_verification_method_jwk(did: &str, key_id: &str, vk: &VerifyingKey) -> Value {
439    json!({
440        "id": format!("{did}#{key_id}-jwk"),
441        "type": "JsonWebKey2020",
442        "controller": did,
443        "publicKeyJwk": {
444            "kty": "OKP",
445            "crv": "Ed25519",
446            "x": URL_SAFE_NO_PAD.encode(vk.as_bytes()),
447        },
448    })
449}
450
451/// Construct the DID document for a given did:web subject.
452///
453/// `did` is the full did:web identifier; `keys` is the ordered list of
454/// `(key_id, VerifyingKey)` pairs to include as verification methods.
455/// `atproto` (when `Some`) makes this an atproto-compatible identity document:
456/// the P-256 `#atproto` Multikey is listed FIRST in `verificationMethod`, an
457/// `#atproto_pds` service is added FIRST in `service`, and `alsoKnownAs` carries
458/// `at://{handle}`. The Ed25519 `keys` remain as additional (mesh) verification
459/// methods, and `transports` are additional typed `service` entries — both are
460/// ignored by atproto resolvers (which match by id/type) but used by our mesh.
461///
462/// `mesh_kem_public` (S1 / #552), when present, publishes the node's
463/// `#mesh-kem` hybrid keyAgreement recipient (X25519 + ML-KEM-768) as
464/// `keyAgreement` entries — additive and, like `mesh_pq_vk`, ignored by
465/// atproto resolvers.
466pub(crate) fn build_did_document(
467    did: &str,
468    issuer_url: &str,
469    keys: &[(String, VerifyingKey)],
470    atproto: Option<&AtprotoIdentity<'_>>,
471    transports: &[TransportEndpoint],
472    mesh_pq_vk: Option<&[u8]>,
473    mesh_kem_public: Option<&hyprstream_rpc::crypto::hybrid_kem::RecipientPublic>,
474) -> Value {
475    let mut verification_methods = Vec::with_capacity(keys.len() * 2 + 4);
476    let mut authentication_refs = Vec::with_capacity(keys.len() * 2 + 2);
477    let mut assertion_refs = Vec::with_capacity(keys.len() * 2 + 2);
478
479    // The active key stays FIRST. Upstream resolvers select this exact fragment;
480    // bounded overlap keys use distinct fragments and are Hyprstream-only.
481    if let Some(at) = atproto {
482        verification_methods.extend(atproto_verification_methods(
483            did,
484            at.p256_vk,
485            at.drain.as_ref().map(|key| AtprotoOverlapKey {
486                vk: key.vk,
487                nbf: key.nbf,
488                exp: key.exp,
489            }),
490            at.lead.as_ref().map(|key| AtprotoOverlapKey {
491                vk: key.vk,
492                nbf: key.nbf,
493                exp: key.exp,
494            }),
495        ));
496        let atproto_vm_id = format!("{did}#atproto");
497        authentication_refs.push(Value::String(atproto_vm_id.clone()));
498        assertion_refs.push(Value::String(atproto_vm_id));
499    }
500
501    // Ed25519 mesh / OAuth verification methods (multibase + JWK).
502    for (key_id, vk) in keys {
503        let vm_id = format!("{did}#{key_id}");
504        let vm_id_jwk = format!("{did}#{key_id}-jwk");
505        verification_methods.push(ed25519_verification_method(did, key_id, vk));
506        verification_methods.push(ed25519_verification_method_jwk(did, key_id, vk));
507        authentication_refs.push(Value::String(vm_id.clone()));
508        authentication_refs.push(Value::String(vm_id_jwk.clone()));
509        assertion_refs.push(Value::String(vm_id));
510        assertion_refs.push(Value::String(vm_id_jwk));
511    }
512
513    // Mesh post-quantum verification method (#157): the node's ML-DSA-65 mesh
514    // key, published as `#mesh-pq` so peers can anchor it in their PQ trust
515    // store. Additive and ignored by atproto resolvers (matched by id/type).
516    if let Some(vk_bytes) = mesh_pq_vk {
517        verification_methods.push(mldsa65_verification_method(did, "mesh-pq", vk_bytes));
518        let vm_id = format!("{did}#mesh-pq");
519        authentication_refs.push(Value::String(vm_id.clone()));
520        assertion_refs.push(Value::String(vm_id));
521    }
522
523    // Services: atproto PDS first, then the legacy HyprstreamService, then any
524    // typed transport endpoints (optional, atproto-ignored).
525    let mut services = Vec::with_capacity(2 + transports.len());
526    if atproto.is_some() {
527        if let Some(origin) = issuer_origin(issuer_url) {
528            services.push(json!({
529                "id": format!("{did}#atproto_pds"),
530                "type": "AtprotoPersonalDataServer",
531                "serviceEndpoint": origin,
532            }));
533        }
534    }
535    services.push(json!({
536        "id": format!("{did}#hyprstream"),
537        "type": "HyprstreamService",
538        "serviceEndpoint": issuer_url,
539    }));
540    for t in transports {
541        services.push(json!({
542            "id": format!("{did}#{}", t.fragment),
543            "type": t.vm_type,
544            "serviceEndpoint": t.endpoint,
545        }));
546    }
547
548    // `#mesh-kem` hybrid keyAgreement (S1 / #552): embedded directly in the
549    // `keyAgreement` relationship (did:key convention) — these are
550    // key-agreement-only keys, never cross-referenced from
551    // `verificationMethod`/`authentication`/`assertionMethod`.
552    let key_agreement = mesh_kem_key_agreement(did, mesh_kem_public);
553
554    let mut doc = json!({
555        "@context": [
556            "https://www.w3.org/ns/did/v1",
557            "https://w3id.org/security/multikey/v1",
558            "https://w3id.org/security/suites/jws-2020/v1",
559        ],
560        "id": did,
561        "verificationMethod": verification_methods,
562        "authentication": authentication_refs,
563        "assertionMethod": assertion_refs,
564        "keyAgreement": key_agreement,
565        "service": services,
566    });
567
568    if let Some(at) = atproto {
569        doc["alsoKnownAs"] = json!([format!("at://{}", at.handle)]);
570    }
571
572    doc
573}
574
575#[derive(Clone)]
576struct RootIdentityMethod {
577    fragment: String,
578    vk: VerifyingKey,
579    pq_vk: Vec<u8>,
580    nbf: Option<i64>,
581    exp: Option<i64>,
582}
583
584fn root_identity_methods(
585    legacy_key: &ed25519_dalek::SigningKey,
586    legacy_pq: &[u8],
587    slots: Option<&crate::auth::key_rotation::KeySlots>,
588    now: i64,
589) -> Vec<RootIdentityMethod> {
590    let Some(slots) = slots else {
591        return vec![RootIdentityMethod {
592            fragment: "key-1".to_owned(),
593            vk: legacy_key.verifying_key(),
594            pq_vk: legacy_pq.to_vec(),
595            nbf: None,
596            exp: None,
597        }];
598    };
599
600    let legacy_bytes = legacy_key.verifying_key().to_bytes();
601    let legacy_slot = [&slots.active, &slots.drain, &slots.lead]
602        .into_iter()
603        .flatten()
604        .find(|slot| slot.verifying_key_bytes() == legacy_bytes && now < slot.exp);
605
606    let mut methods = Vec::new();
607    // Preserve the fleet's existing stable fragment during the bounded
608    // compatibility window. It aliases the exact same key and PQ binding as
609    // its named slot, so upgraded consumers can collapse it safely.
610    if let Some(slot) = legacy_slot {
611        methods.push(RootIdentityMethod {
612            fragment: "key-1".to_owned(),
613            vk: legacy_key.verifying_key(),
614            pq_vk: legacy_pq.to_vec(),
615            nbf: Some(slot.nbf),
616            exp: Some(slot.exp),
617        });
618    }
619
620    // Active is first for legacy order-based consumers after the compatibility
621    // alias retires. Drain and lead remain separately named and bounded.
622    for slot in [&slots.active, &slots.drain, &slots.lead]
623        .into_iter()
624        .flatten()
625    {
626        let pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&slot.key);
627        methods.push(RootIdentityMethod {
628            fragment: format!("mesh-{}", slot.kid()),
629            vk: slot.key.verifying_key(),
630            pq_vk: hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq),
631            nbf: Some(slot.nbf),
632            exp: Some(slot.exp),
633        });
634    }
635    methods
636}
637
638fn append_root_identity_methods(doc: &mut Value, did: &str, methods: &[RootIdentityMethod]) {
639    let Some(verification_methods) = doc
640        .get_mut("verificationMethod")
641        .and_then(Value::as_array_mut)
642    else {
643        return;
644    };
645    let mut relationship_ids = Vec::new();
646
647    for method in methods {
648        let mut ed = ed25519_verification_method(did, &method.fragment, &method.vk);
649        let mut ed_jwk = ed25519_verification_method_jwk(did, &method.fragment, &method.vk);
650        let pq_fragment = format!("{}-pq", method.fragment);
651        let mut pq = mldsa65_verification_method(did, &pq_fragment, &method.pq_vk);
652        for vm in [&mut ed, &mut ed_jwk, &mut pq] {
653            if let Some(nbf) = method.nbf {
654                vm["nbf"] = nbf.into();
655            }
656            if let Some(exp) = method.exp {
657                vm["exp"] = exp.into();
658            }
659        }
660        relationship_ids.extend([ed["id"].clone(), ed_jwk["id"].clone(), pq["id"].clone()]);
661        verification_methods.extend([ed, ed_jwk, pq]);
662    }
663
664    // Retain the old `#mesh-pq` DID URL as an alias for the first candidate's
665    // PQ half. Old consumers that pair by document order therefore preserve
666    // hybrid assurance in both mixed-version directions.
667    if let Some(first) = methods.first() {
668        let mut legacy_pq = mldsa65_verification_method(did, "mesh-pq", &first.pq_vk);
669        if let Some(nbf) = first.nbf {
670            legacy_pq["nbf"] = nbf.into();
671        }
672        if let Some(exp) = first.exp {
673            legacy_pq["exp"] = exp.into();
674        }
675        relationship_ids.push(legacy_pq["id"].clone());
676        verification_methods.push(legacy_pq);
677    }
678
679    for relationship in ["authentication", "assertionMethod"] {
680        if let Some(values) = doc.get_mut(relationship).and_then(Value::as_array_mut) {
681            values.extend(relationship_ids.iter().cloned());
682        }
683    }
684}
685
686/// `GET /.well-known/did.json` — root deployment DID document.
687///
688/// `id` is the canonical issuer-root did:web (non-default port encoded as
689/// `%3A`). Verification methods: the OAuth issuer's
690/// current signing key (entity-signing key from OAuthState). Acts as the
691/// trust anchor that controls user/client DIDs under this authority.
692pub async fn root_did_document(State(state): State<Arc<OAuthState>>) -> Response {
693    let did = match state.atproto_service_did() {
694        Some(a) => a,
695        None => {
696            return (
697                StatusCode::INTERNAL_SERVER_ERROR,
698                "issuer URL has no supported service DID",
699            )
700                .into_response()
701        }
702    };
703
704    // Use the OAuth signing key as the root verification method.
705    let Some(ref sk) = state.signing_key else {
706        return (
707            StatusCode::SERVICE_UNAVAILABLE,
708            "OAuth signing key not configured",
709        )
710            .into_response();
711    };
712    let root_slots = if let Some(store) = &state.root_identity_key_store {
713        Some(store.slots_snapshot().await)
714    } else {
715        None
716    };
717    let now = chrono::Utc::now().timestamp();
718    let root_methods = root_identity_methods(
719        sk,
720        state.mesh_pq_verifying_key.as_deref().unwrap_or_default(),
721        root_slots.as_ref(),
722        now,
723    );
724
725    // The active key signs new commits. Bounded drain/lead slots are published
726    // only for verification overlap; they are never signing candidates.
727    let slots = state
728        .es256_key_store
729        .as_ref()
730        .map(|store| store.slots_snapshot())
731        .unwrap_or_default();
732    let (active_slot, drain_slot, lead_slot) = (slots.active, slots.drain, slots.lead);
733    let handle = configured_handle_host(&state.issuer_url);
734    let atproto = active_slot
735        .as_ref()
736        .zip(handle.as_deref())
737        .map(|(active, handle)| AtprotoIdentity {
738            p256_vk: active.key.verifying_key(),
739            handle,
740            drain: drain_slot.as_ref().map(|slot| AtprotoOverlapKey {
741                vk: slot.key.verifying_key(),
742                nbf: slot.nbf,
743                exp: slot.exp,
744            }),
745            lead: lead_slot.as_ref().map(|slot| AtprotoOverlapKey {
746                vk: slot.key.verifying_key(),
747                nbf: slot.nbf,
748                exp: slot.exp,
749            }),
750        });
751
752    // Transport `service` entries: populate QUIC entry when cert hash is available (#185).
753    // The cert hash was set at OAuthService startup from the node's QUIC TLS cert,
754    // closing the two-trust-roots gap: peers dialing by DID can now pin the cert
755    // instead of accepting it on TOFU.
756    let mut transports: Vec<TransportEndpoint> = Vec::new();
757    if !state.quic_cert_hashes.is_empty() {
758        if let Some(ref quic_uri) = state.quic_public_uri {
759            let auth = match hyprstream_rpc::transport::QuicServerAuth::pinned(
760                state.quic_cert_hashes.clone(),
761            ) {
762                Ok(auth) => auth,
763                Err(_) => hyprstream_rpc::transport::QuicServerAuth::web_pki(),
764            };
765            transports.push(TransportEndpoint {
766                fragment: "quic".to_owned(),
767                vm_type: "QuicTransport".to_owned(),
768                endpoint: hyprstream_rpc::service_entry::encode_quic(
769                    quic_uri,
770                    &auth,
771                    &["hyprstream-rpc/1"],
772                ),
773            });
774        }
775    }
776
777    // #282: iroh transport entry — published ONLY when the iroh substrate is
778    // bound (the daemon set `iroh_node_id`). Advertises only an IrohTransport
779    // entry. NodeId is not a VM, JWKS key, or trust anchor.
780    if let Some(node_id) = state.iroh_node_id {
781        transports.push(TransportEndpoint {
782            fragment: "iroh".to_owned(),
783            vm_type: "IrohTransport".to_owned(),
784            endpoint: hyprstream_rpc::service_entry::encode_iroh(
785                &node_id,
786                &state.iroh_relays,
787                &["hyprstream-rpc/1"],
788            ),
789        });
790    }
791
792    let mut doc = build_did_document(
793        &did,
794        &state.issuer_url,
795        &[],
796        atproto.as_ref(),
797        &transports,
798        None,
799        state.mesh_kem_public.as_ref(),
800    );
801    append_root_identity_methods(&mut doc, &did, &root_methods);
802    if let Some(identity) = state.at9p_identity.as_ref() {
803        let mut aliases = doc
804            .get("alsoKnownAs")
805            .and_then(Value::as_array)
806            .cloned()
807            .unwrap_or_default();
808        aliases.push(Value::String(identity.did.clone()));
809        doc["alsoKnownAs"] = Value::Array(aliases);
810    }
811    (
812        StatusCode::OK,
813        [(header::CONTENT_TYPE, "application/did+json")],
814        Json(doc),
815    )
816        .into_response()
817}
818
819/// `GET /.well-known/at9p/{cid}.cbor` — this node's live at9p genesis capsule.
820///
821/// Only the CID rendered from the current in-process identity is served.
822pub async fn at9p_capsule(
823    State(state): State<Arc<OAuthState>>,
824    Path(cid): Path<String>,
825) -> Response {
826    let Some(cid) = cid.strip_suffix(".cbor") else {
827        return StatusCode::NOT_FOUND.into_response();
828    };
829    let Some(identity) = state.at9p_identity.as_ref() else {
830        return StatusCode::SERVICE_UNAVAILABLE.into_response();
831    };
832    if cid != identity.cid512 {
833        return StatusCode::NOT_FOUND.into_response();
834    }
835
836    (
837        StatusCode::OK,
838        [
839            (header::CONTENT_TYPE, "application/cbor"),
840            (header::CACHE_CONTROL, "no-store"),
841        ],
842        identity.capsule.to_vec(),
843    )
844        .into_response()
845}
846
847/// `GET /.well-known/atproto-did` — atproto handle→DID resolution (HTTP method).
848///
849/// Per the atproto Handle spec (https://atproto.com/specs/handle), the HTTPS
850/// well-known method returns the **bare DID string** as `text/plain` (no JSON
851/// or wrapper) so this deployment's handle (its authority hostname) resolves to
852/// its canonical issuer-root did:web. Companion to `/.well-known/did.json`, which serves
853/// the full W3C DID document for the same subject.
854///
855/// Consumed by the frontend handle resolver
856/// (`www-cyberdione-ai/src/api/atproto.ts:resolveHandleToDid`). This is a
857/// CORS-simple GET (no custom request headers → no preflight), so it needs only
858/// cross-origin readability from the public CORS layer, not permissive headers.
859pub async fn atproto_did(State(state): State<Arc<OAuthState>>) -> Response {
860    let Some(did) = state.atproto_service_did() else {
861        return (
862            StatusCode::INTERNAL_SERVER_ERROR,
863            "issuer URL has no supported service DID",
864        )
865            .into_response();
866    };
867    (
868        StatusCode::OK,
869        [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
870        did,
871    )
872        .into_response()
873}
874
875/// `GET /users/:username/did.json` — frozen path-form account DID endpoint.
876///
877/// This route previously synthesized `did:web:{authority}:users:{username}`.
878/// That shape is outside the atproto did:web profile, so serving it would mint
879/// another permanent invalid account identifier. Keep the route as an explicit
880/// hard error until the separately designed host-form mint path lands (#1163).
881pub async fn user_did_document(
882    State(_state): State<Arc<OAuthState>>,
883    Path(username): Path<String>,
884) -> Response {
885    tracing::debug!(%username, "deprecated path-form account DID route requested");
886    path_form_account_did_disabled_response()
887}
888
889fn path_form_account_did_disabled_response() -> Response {
890    (
891        StatusCode::GONE,
892        "did:web path-form account minting is disabled; host-form account minting is not available yet (#1159)",
893    )
894        .into_response()
895}
896
897/// `GET /clients/:client_id/did.json` — per-client DID document.
898///
899/// `id = {canonical issuer-root DID}:clients:{client_id}`. Verification methods:
900/// JWKS keys registered for the client via dynamic-client-registration's
901/// `jwks` field (Tier 3 confidential clients with `private_key_jwt`).
902pub async fn client_did_document(
903    State(state): State<Arc<OAuthState>>,
904    Path(client_id): Path<String>,
905) -> Response {
906    let did = match state.atproto_service_did() {
907        Some(a) => a,
908        None => {
909            return (
910                StatusCode::INTERNAL_SERVER_ERROR,
911                "issuer URL has no supported service DID",
912            )
913                .into_response()
914        }
915    };
916    if client_id.contains(['/', '#', '?', ':']) || client_id.is_empty() {
917        return (StatusCode::BAD_REQUEST, "invalid client_id").into_response();
918    }
919    let did = format!("{did}:clients:{client_id}");
920
921    // Client JWKS storage will be wired up in Phase 1b (client-key
922    // registration CLI + server-side JWKS persistence). For now,
923    // return an empty verificationMethod list — the DID document is
924    // structurally valid; consumers learn that no keys are bound yet.
925    //
926    // Once RegisteredClient grows a `jwks: Option<serde_json::Value>`
927    // field, replace this with a `clients.read().await.get(client_id)`
928    // lookup + extract_ed25519_keys_from_jwks call.
929    let keys: Vec<(String, VerifyingKey)> = Vec::new();
930
931    let doc = build_did_document(&did, &state.issuer_url, &keys, None, &[], None, None);
932    (
933        StatusCode::OK,
934        [(header::CONTENT_TYPE, "application/did+json")],
935        Json(doc),
936    )
937        .into_response()
938}
939
940/// Extract Ed25519 VerifyingKeys from a JWKS JSON value.
941///
942/// Currently unused: client JWKS storage is a Phase 1b deliverable. This
943/// helper is retained (and exercised by tests) so the call-site in
944/// `client_did_document` is a one-line activation once `RegisteredClient`
945/// grows a `jwks` field.
946#[allow(dead_code)]
947fn extract_ed25519_keys_from_jwks(jwks: &Option<Value>) -> Vec<(String, VerifyingKey)> {
948    let Some(jwks) = jwks else { return Vec::new() };
949    let Some(keys) = jwks.get("keys").and_then(|k| k.as_array()) else {
950        return Vec::new();
951    };
952    let mut out = Vec::new();
953    for (idx, key) in keys.iter().enumerate() {
954        if key.get("kty").and_then(|v| v.as_str()) != Some("OKP")
955            || key.get("crv").and_then(|v| v.as_str()) != Some("Ed25519")
956        {
957            continue;
958        }
959        let Some(x) = key.get("x").and_then(|v| v.as_str()) else {
960            continue;
961        };
962        let Ok(raw) = URL_SAFE_NO_PAD.decode(x) else {
963            continue;
964        };
965        let bytes: [u8; 32] = match raw.try_into() {
966            Ok(b) => b,
967            Err(_) => continue,
968        };
969        let Ok(vk) = VerifyingKey::from_bytes(&bytes) else {
970            continue;
971        };
972        let kid = key
973            .get("kid")
974            .and_then(|v| v.as_str())
975            .map(str::to_owned)
976            .unwrap_or_else(|| format!("key-{idx}"));
977        out.push((kid, vk));
978    }
979    out
980}
981
982#[cfg(test)]
983#[allow(clippy::unwrap_used, clippy::expect_used)]
984mod tests {
985    use super::*;
986    use ed25519_dalek::SigningKey;
987    use hyprstream_rpc::crypto::CryptoPolicy;
988    use rand::rngs::OsRng;
989
990    #[test]
991    fn rendered_at9p_capsule_is_key_owned_and_mutually_aliased() {
992        let sk = SigningKey::from_bytes(&[0x31; 32]);
993        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&sk);
994        let identity =
995            render_at9p_identity("https://discovery.hyprstream.com", &sk, &pq_sk).unwrap();
996
997        let verified =
998            hyprstream_pds::at9p_gate::verify_did_at9p(&identity.did, &identity.capsule).unwrap();
999        assert_eq!(verified.cid512(), identity.cid512);
1000        assert_eq!(
1001            verified.capsule().body.subject_keys[0].ed25519_pub,
1002            sk.verifying_key().to_bytes(),
1003        );
1004        assert_eq!(
1005            verified.capsule().body.subject_keys[0].mldsa65_pub,
1006            hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk),
1007        );
1008        assert_eq!(
1009            verified.capsule().body.also_known_as.as_deref(),
1010            Some(&["did:web:discovery.hyprstream.com".to_owned()][..]),
1011        );
1012    }
1013
1014    #[test]
1015    fn rendered_at9p_capsule_uses_canonical_service_did_alias() {
1016        let sk = SigningKey::from_bytes(&[0x31; 32]);
1017        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&sk);
1018        for (issuer, expected) in [
1019            (
1020                "https://pds.example:8443/oauth",
1021                "did:web:pds.example%3A8443",
1022            ),
1023            ("https://PDS.example:443/oauth", "did:web:pds.example"),
1024        ] {
1025            let identity = render_at9p_identity(issuer, &sk, &pq_sk).unwrap();
1026            let verified =
1027                hyprstream_pds::at9p_gate::verify_did_at9p(&identity.did, &identity.capsule)
1028                    .unwrap();
1029            assert_eq!(
1030                verified.capsule().body.also_known_as.as_deref(),
1031                Some(&[expected.to_owned()][..])
1032            );
1033        }
1034        for issuer in [
1035            "https://user@pds.example",
1036            "https://[::1]:8443",
1037            "not-a-url",
1038        ] {
1039            assert!(render_at9p_identity(issuer, &sk, &pq_sk).is_err());
1040        }
1041    }
1042
1043    #[test]
1044    fn rendered_at9p_capsule_refuses_non_https_identity_origin() {
1045        let sk = SigningKey::from_bytes(&[0x32; 32]);
1046        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&sk);
1047        let error = render_at9p_identity("http://discovery.example", &sk, &pq_sk).unwrap_err();
1048        assert!(error.to_string().contains("requires an HTTPS OAuth issuer"));
1049    }
1050
1051    #[tokio::test]
1052    async fn non_https_issuer_degrades_only_at9p_identity() {
1053        use axum::body::Body;
1054        use axum::http::Request;
1055        use tower::ServiceExt as _;
1056
1057        let state = Arc::new(state_with_issuer("http://discovery.example"));
1058        assert!(state.signing_key.is_some());
1059        assert!(state.mesh_pq_verifying_key.is_some());
1060        assert!(state.mesh_kem_public.is_some());
1061        assert!(state.at9p_identity.is_none());
1062
1063        let cors = crate::config::server::CorsConfig {
1064            enabled: false,
1065            ..Default::default()
1066        };
1067        let response = super::super::create_app(state, &cors)
1068            .oneshot(
1069                Request::get("/.well-known/at9p/unavailable.cbor")
1070                    .body(Body::empty())
1071                    .unwrap(),
1072            )
1073            .await
1074            .unwrap();
1075        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
1076    }
1077
1078    fn state_with_issuer(issuer_url: &str) -> OAuthState {
1079        use hyprstream_rpc::rpc_client::RpcClientImpl;
1080        use hyprstream_rpc::signer::LocalSigner;
1081        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
1082
1083        let local = SigningKey::from_bytes(&[0x33; 32]);
1084        let remote = SigningKey::from_bytes(&[0x34; 32]).verifying_key();
1085        let make_client = || {
1086            Arc::new(
1087                RpcClientImpl::new(
1088                    LocalSigner::new(local.clone()),
1089                    LazyUdsTransport::new("/dev/null/oauth-at9p-test.sock".into()),
1090                    Some(remote),
1091                )
1092                .with_response_verify_policy(CryptoPolicy::Classical),
1093            )
1094        };
1095        let mut config = crate::config::OAuthConfig::default();
1096        config.external_url = Some(issuer_url.to_owned());
1097        OAuthState::new(
1098            &config,
1099            hyprstream_rpc_std::policy_client::PolicyClient::new(make_client()),
1100            hyprstream_rpc_std::discovery_client::DiscoveryClient::new(make_client()),
1101            local.verifying_key().to_bytes(),
1102        )
1103        .with_signing_key(local, CryptoPolicy::Hybrid)
1104        .unwrap()
1105    }
1106
1107    fn state_with_live_identity() -> Arc<OAuthState> {
1108        Arc::new(state_with_issuer("https://discovery.hyprstream.com"))
1109    }
1110
1111    #[tokio::test]
1112    async fn public_router_serves_only_its_live_capsule_without_credentials() {
1113        use axum::body::{to_bytes, Body};
1114        use axum::http::Request;
1115        use tower::ServiceExt as _;
1116
1117        let state = state_with_live_identity();
1118        let identity = state.at9p_identity.as_ref().unwrap().clone();
1119        let cors = crate::config::server::CorsConfig {
1120            enabled: false,
1121            ..Default::default()
1122        };
1123        let app = super::super::create_app(Arc::clone(&state), &cors);
1124
1125        let response = app
1126            .clone()
1127            .oneshot(
1128                Request::get(format!("/.well-known/at9p/{}.cbor", identity.cid512))
1129                    .header(header::AUTHORIZATION, "Bearer must-be-ignored")
1130                    .header(header::COOKIE, "session=must-be-ignored")
1131                    .body(Body::empty())
1132                    .unwrap(),
1133            )
1134            .await
1135            .unwrap();
1136        assert_eq!(response.status(), StatusCode::OK);
1137        assert_eq!(
1138            response.headers().get(header::CONTENT_TYPE).unwrap(),
1139            "application/cbor",
1140        );
1141        assert_eq!(
1142            response.headers().get(header::CACHE_CONTROL).unwrap(),
1143            "no-store",
1144        );
1145        assert!(!response.headers().contains_key(header::SET_COOKIE));
1146        let bytes = to_bytes(response.into_body(), 4 * 1024 * 1024)
1147            .await
1148            .unwrap();
1149        assert_eq!(bytes.as_ref(), identity.capsule.as_ref());
1150        hyprstream_pds::at9p_gate::verify_did_at9p(&identity.did, &bytes).unwrap();
1151
1152        let wrong = app
1153            .clone()
1154            .oneshot(
1155                Request::get("/.well-known/at9p/not-this-node.cbor")
1156                    .body(Body::empty())
1157                    .unwrap(),
1158            )
1159            .await
1160            .unwrap();
1161        assert_eq!(wrong.status(), StatusCode::NOT_FOUND);
1162
1163        let did_response = app
1164            .oneshot(
1165                Request::get("/.well-known/did.json")
1166                    .body(Body::empty())
1167                    .unwrap(),
1168            )
1169            .await
1170            .unwrap();
1171        assert_eq!(did_response.status(), StatusCode::OK);
1172        let did_bytes = to_bytes(did_response.into_body(), 1024 * 1024)
1173            .await
1174            .unwrap();
1175        let document: Value = serde_json::from_slice(&did_bytes).unwrap();
1176        assert!(document["alsoKnownAs"]
1177            .as_array()
1178            .unwrap()
1179            .iter()
1180            .any(|alias| alias == &identity.did));
1181    }
1182
1183    /// `GET /users/:username/did.json` must be a deliberate 410 hard error,
1184    /// driven through the **production** OAuth router (`create_app`) — NOT by
1185    /// calling the `path_form_account_did_disabled_response()` helper directly.
1186    ///
1187    /// This is the regression guard for the #1159 path-form account freeze.
1188    /// The handler must return 410 *before* consulting any user store: a
1189    /// user-store spy whose `list_pubkeys` panics is wired into the state so
1190    /// that restoring the pre-PR document-serving body (which resolved user
1191    /// keys via `list_pubkeys`) fails this test loudly, instead of passing on
1192    /// a coincidental "no keys found → 200 with an empty document". Asserting
1193    /// only on the helper would pass either way — that tautology is what this
1194    /// test replaces.
1195    #[tokio::test]
1196    async fn path_form_account_document_endpoint_is_a_hard_error() {
1197        use crate::auth::user_store::{
1198            PubkeyEntry, UserFilter, UserProfile, UserProfilePatch, UserStore,
1199        };
1200        use crate::config::server::CorsConfig;
1201        use crate::config::OAuthConfig;
1202        use crate::services::oauth::create_app;
1203        use async_trait::async_trait;
1204        use axum::body::Body;
1205        use axum::http::Request as HttpRequest;
1206        use hyprstream_rpc::rpc_client::RpcClientImpl;
1207        use hyprstream_rpc::signer::LocalSigner;
1208        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
1209        use hyprstream_rpc_std::discovery_client::DiscoveryClient;
1210        use hyprstream_rpc_std::policy_client::PolicyClient;
1211        use tower::ServiceExt; // oneshot
1212
1213        /// User-store spy whose every method panics. The frozen account-DID
1214        /// handler must return 410 without ever consulting the store; if the
1215        /// old key-lookup/serving code path is reintroduced it touches
1216        /// `list_pubkeys` and this test aborts instead of passing.
1217        struct UntouchedUserStore;
1218        #[async_trait]
1219        impl UserStore for UntouchedUserStore {
1220            async fn get_profile(&self, _: &str) -> anyhow::Result<Option<UserProfile>> {
1221                unreachable!("frozen account-DID handler must not read profiles")
1222            }
1223            async fn register(&self, _: &str) -> anyhow::Result<String> {
1224                unreachable!()
1225            }
1226            async fn set_profile(&self, _: &str, _: UserProfilePatch) -> anyhow::Result<()> {
1227                unreachable!()
1228            }
1229            async fn remove(&self, _: &str) -> anyhow::Result<bool> {
1230                unreachable!()
1231            }
1232            async fn list_users(&self) -> anyhow::Result<Vec<String>> {
1233                unreachable!()
1234            }
1235            async fn search(&self, _: &UserFilter) -> anyhow::Result<Vec<(String, UserProfile)>> {
1236                unreachable!()
1237            }
1238            async fn set_active(&self, _: &str, _: bool) -> anyhow::Result<()> {
1239                unreachable!()
1240            }
1241            async fn list_pubkeys(&self, _: &str) -> anyhow::Result<Vec<PubkeyEntry>> {
1242                // This is the method the pre-PR `user_did_document` called to
1243                // resolve keys before minting the path-form DID. Reaching it
1244                // means the freeze was bypassed.
1245                unreachable!("frozen account-DID handler must not call list_pubkeys (#1159)")
1246            }
1247            async fn add_pubkey(
1248                &self,
1249                _: &str,
1250                _: VerifyingKey,
1251                _: Option<String>,
1252            ) -> anyhow::Result<String> {
1253                unreachable!()
1254            }
1255            async fn add_pubkey_hybrid(
1256                &self,
1257                _: &str,
1258                _: VerifyingKey,
1259                _: Vec<u8>,
1260                _: Option<String>,
1261            ) -> anyhow::Result<String> {
1262                unreachable!()
1263            }
1264            async fn remove_pubkey(&self, _: &str, _: &str) -> anyhow::Result<bool> {
1265                unreachable!()
1266            }
1267            async fn get_pubkey_user(&self, _: &str) -> anyhow::Result<Option<String>> {
1268                unreachable!()
1269            }
1270            async fn touch_pubkey(&self, _: &str, _: &str) -> anyhow::Result<()> {
1271                unreachable!()
1272            }
1273        }
1274
1275        // Minimal OAuthState over a LazyUdsTransport pointed at /dev/null.
1276        // The frozen handler returns before opening it, so this keeps the test
1277        // hermetic while still exercising the real router + handler wiring.
1278        let key = SigningKey::from_bytes(&[0x76; 32]);
1279        let vk = SigningKey::from_bytes(&[0x73; 32]).verifying_key();
1280        let dummy = std::path::PathBuf::from("/dev/null/did-doc-test.sock");
1281        let mk_client = || {
1282            let rpc = RpcClientImpl::new(
1283                LocalSigner::new(key.clone()),
1284                LazyUdsTransport::new(dummy.clone()),
1285                Some(vk),
1286            )
1287            .with_response_verify_policy(hyprstream_rpc::crypto::CryptoPolicy::Classical);
1288            Arc::new(rpc)
1289        };
1290        let state = Arc::new(
1291            OAuthState::new(
1292                &OAuthConfig::default(),
1293                PolicyClient::new(mk_client()),
1294                DiscoveryClient::new(mk_client()),
1295                [0x76; 32],
1296            )
1297            .with_user_service(Arc::new(
1298                crate::services::oauth::user_service::UserService::new(
1299                    crate::auth::ProductionUserStore::for_test(Arc::new(UntouchedUserStore)),
1300                ),
1301            )),
1302        );
1303
1304        let cors = CorsConfig {
1305            enabled: false,
1306            ..Default::default()
1307        };
1308        let app = create_app(state, &cors);
1309
1310        let response = app
1311            .oneshot(
1312                HttpRequest::builder()
1313                    .uri("/users/alice/did.json")
1314                    .body(Body::empty())
1315                    .unwrap(),
1316            )
1317            .await
1318            .unwrap();
1319        assert_eq!(response.status(), StatusCode::GONE);
1320        let body = axum::body::to_bytes(response.into_body(), 4096)
1321            .await
1322            .unwrap();
1323        assert!(
1324            std::str::from_utf8(&body)
1325                .unwrap()
1326                .contains("path-form account minting is disabled"),
1327            "body was: {}",
1328            std::str::from_utf8(&body).unwrap(),
1329        );
1330    }
1331
1332    #[test]
1333    fn ipv6_issuer_does_not_synthesize_atproto_handle() {
1334        assert_eq!(configured_handle_host("https://[::1]:6791"), None);
1335        assert_eq!(account_handle("alice", "https://[::1]:6791"), None);
1336    }
1337
1338    #[test]
1339    fn invalid_username_label_does_not_synthesize_atproto_handle() {
1340        assert_eq!(account_handle("alice_bad", "https://pds.example.com"), None);
1341        assert_eq!(
1342            account_handle("Alice", "https://PDS.Example.COM").as_deref(),
1343            Some("alice.pds.example.com")
1344        );
1345    }
1346
1347    #[test]
1348    fn ed25519_multibase_format() {
1349        let sk = SigningKey::generate(&mut OsRng);
1350        let mb = ed25519_to_multibase(&sk.verifying_key());
1351        assert!(mb.starts_with('z'), "must use base58btc multibase prefix");
1352        // Decode + check the multicodec prefix is ed25519-pub (0xed 0x01).
1353        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
1354        assert_eq!(decoded[0], 0xed);
1355        assert_eq!(decoded[1], 0x01);
1356        assert_eq!(&decoded[2..], sk.verifying_key().as_bytes());
1357    }
1358
1359    #[test]
1360    fn build_did_doc_minimum_structure() {
1361        let sk = SigningKey::generate(&mut OsRng);
1362        let did = "did:web:alice.hyprstream.example.com";
1363        let doc = build_did_document(
1364            did,
1365            "https://hyprstream.example.com",
1366            &[("key-1".to_owned(), sk.verifying_key())],
1367            None,
1368            &[],
1369            None,
1370            None,
1371        );
1372        assert_eq!(doc["id"].as_str().unwrap(), did);
1373        assert!(doc["@context"].is_array());
1374        assert_eq!(doc["verificationMethod"].as_array().unwrap().len(), 2); // multibase + jwk
1375                                                                            // The ed25519 VM is emitted as a Multikey (#280) with a multibase key.
1376        let vm = &doc["verificationMethod"][0];
1377        assert_eq!(vm["type"].as_str().unwrap(), "Multikey");
1378        assert!(vm["publicKeyMultibase"].as_str().unwrap().starts_with('z'));
1379        // The JWK fallback VM is retained.
1380        assert_eq!(
1381            doc["verificationMethod"][1]["type"].as_str().unwrap(),
1382            "JsonWebKey2020"
1383        );
1384        assert_eq!(
1385            doc["service"][0]["type"].as_str().unwrap(),
1386            "HyprstreamService"
1387        );
1388        assert_eq!(
1389            doc["service"][0]["serviceEndpoint"].as_str().unwrap(),
1390            "https://hyprstream.example.com",
1391        );
1392    }
1393
1394    #[test]
1395    fn build_did_doc_empty_keys_is_valid() {
1396        let did = "did:web:alice.example.com";
1397        let doc = build_did_document(did, "https://example.com", &[], None, &[], None, None);
1398        assert_eq!(doc["id"].as_str().unwrap(), did);
1399        assert_eq!(doc["verificationMethod"].as_array().unwrap().len(), 0);
1400        assert_eq!(doc["authentication"].as_array().unwrap().len(), 0);
1401    }
1402
1403    #[test]
1404    fn p256_multibase_format() {
1405        let sk = p256::ecdsa::SigningKey::random(&mut OsRng);
1406        let mb = p256_to_multibase(sk.verifying_key());
1407        assert!(mb.starts_with('z'), "must use base58btc multibase prefix");
1408        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
1409        // multicodec p256-pub = 0x1200 → unsigned-varint [0x80, 0x24].
1410        assert_eq!(decoded[0], 0x80);
1411        assert_eq!(decoded[1], 0x24);
1412        // Compressed SEC1 point: 33 bytes, leading 0x02/0x03.
1413        assert_eq!(decoded.len(), 2 + 33);
1414        assert!(decoded[2] == 0x02 || decoded[2] == 0x03);
1415    }
1416
1417    #[test]
1418    fn build_did_doc_atproto_identity() {
1419        let ed = SigningKey::generate(&mut OsRng);
1420        let p256_sk = p256::ecdsa::SigningKey::random(&mut OsRng);
1421        let p256_vk = p256_sk.verifying_key();
1422        let did = "did:web:hyprstream.example.com";
1423        let atproto = AtprotoIdentity {
1424            p256_vk,
1425            handle: "hyprstream.example.com",
1426            drain: None,
1427            lead: None,
1428        };
1429        let transports = [TransportEndpoint {
1430            fragment: "iroh".to_owned(),
1431            vm_type: "IrohTransport".to_owned(),
1432            endpoint: json!({ "uri": "iroh:abc", "accept": ["hyprstream-rpc/1", "moql"] }),
1433        }];
1434        let doc = build_did_document(
1435            did,
1436            // issuer URL with a path — origin must strip it for #atproto_pds.
1437            "https://hyprstream.example.com/oauth",
1438            &[("key-1".to_owned(), ed.verifying_key())],
1439            Some(&atproto),
1440            &transports,
1441            None,
1442            None,
1443        );
1444
1445        // #atproto Multikey is FIRST and p256.
1446        let vms = doc["verificationMethod"].as_array().unwrap();
1447        assert_eq!(vms[0]["id"].as_str().unwrap(), format!("{did}#atproto"));
1448        assert_eq!(vms[0]["type"].as_str().unwrap(), "Multikey");
1449        assert!(vms[0]["publicKeyMultibase"]
1450            .as_str()
1451            .unwrap()
1452            .starts_with('z'));
1453        // Ed25519 mesh VMs still present after it.
1454        assert_eq!(vms.len(), 1 + 2);
1455        // The ed25519 mesh VM is also a Multikey (#280), not the deprecated
1456        // Ed25519VerificationKey2020 type, with a multibase key; JWK fallback kept.
1457        assert_eq!(vms[1]["type"].as_str().unwrap(), "Multikey");
1458        assert!(vms[1]["publicKeyMultibase"]
1459            .as_str()
1460            .unwrap()
1461            .starts_with('z'));
1462        assert_eq!(vms[2]["type"].as_str().unwrap(), "JsonWebKey2020");
1463
1464        // #atproto_pds first, origin-only (no path), correct type.
1465        let svcs = doc["service"].as_array().unwrap();
1466        assert_eq!(
1467            svcs[0]["id"].as_str().unwrap(),
1468            format!("{did}#atproto_pds")
1469        );
1470        assert_eq!(
1471            svcs[0]["type"].as_str().unwrap(),
1472            "AtprotoPersonalDataServer"
1473        );
1474        assert_eq!(
1475            svcs[0]["serviceEndpoint"].as_str().unwrap(),
1476            "https://hyprstream.example.com"
1477        );
1478        // transport entry present as a typed map service.
1479        let iroh = svcs.iter().find(|s| s["type"] == "IrohTransport").unwrap();
1480        assert_eq!(iroh["id"].as_str().unwrap(), format!("{did}#iroh"));
1481        assert!(iroh["serviceEndpoint"]["accept"].is_array());
1482
1483        // alsoKnownAs handle.
1484        assert_eq!(
1485            doc["alsoKnownAs"][0].as_str().unwrap(),
1486            "at://hyprstream.example.com"
1487        );
1488    }
1489
1490    /// #1113 rev2 finding 2/7: the per-user atproto DID document (served at
1491    /// `/users/:u/did.json` for a `did:web:{authority}:users:{u}` token `sub`)
1492    /// carries an `AtprotoPersonalDataServer` service whose `serviceEndpoint`
1493    /// is THIS AS's origin — the round-trip the stock atproto client performs
1494    /// (resolve `sub` → PDS service → PDS metadata issuer == AS). Mirrors the
1495    /// `user_did_document` handler's construction exactly.
1496    #[test]
1497    fn per_user_atproto_doc_pds_service_points_at_issuer() {
1498        let p256_sk = p256::ecdsa::SigningKey::random(&mut OsRng);
1499        let p256_vk = p256_sk.verifying_key();
1500        let issuer = "https://pds.example.com";
1501        let did = "did:web:pds.example.com:users:alice";
1502        let handle = "alice.pds.example.com";
1503        let atproto = AtprotoIdentity {
1504            p256_vk,
1505            handle,
1506            drain: None,
1507            lead: None,
1508        };
1509        let doc = build_did_document(did, issuer, &[], Some(&atproto), &[], None, None);
1510
1511        // The atproto PDS service is present and points at the issuer origin.
1512        let pds = doc["service"]
1513            .as_array()
1514            .unwrap()
1515            .iter()
1516            .find(|s| s["type"] == "AtprotoPersonalDataServer")
1517            .expect("AtprotoPersonalDataServer service required for the sub→PDS round-trip");
1518        assert_eq!(
1519            pds["serviceEndpoint"].as_str().unwrap(),
1520            issuer,
1521            "PDS serviceEndpoint MUST equal the AS issuer (PDS = its own AS)"
1522        );
1523        // The account handle alias is present.
1524        assert_eq!(
1525            doc["alsoKnownAs"][0].as_str().unwrap(),
1526            "at://alice.pds.example.com"
1527        );
1528        // The hosted-account #atproto VM (P-256 Multikey) is present.
1529        assert!(doc["verificationMethod"]
1530            .as_array()
1531            .unwrap()
1532            .iter()
1533            .any(|vm| vm["id"].as_str() == Some(&format!("{did}#atproto"))));
1534    }
1535
1536    /// #918 producer side: active remains the exact `#atproto` VM, while drain
1537    /// and lead are bounded distinct-fragment overlap VMs.
1538    #[test]
1539    fn build_did_doc_publishes_bounded_overlap_slots() {
1540        let active_sk = p256::ecdsa::SigningKey::random(&mut OsRng);
1541        let active_vk = active_sk.verifying_key();
1542        let drain_sk = p256::ecdsa::SigningKey::random(&mut OsRng);
1543        let drain_vk = drain_sk.verifying_key();
1544        let lead_sk = p256::ecdsa::SigningKey::random(&mut OsRng);
1545        let lead_vk = lead_sk.verifying_key();
1546        let did = "did:web:hyprstream.example.com";
1547        let atproto = AtprotoIdentity {
1548            p256_vk: active_vk,
1549            handle: "hyprstream.example.com",
1550            drain: Some(AtprotoOverlapKey {
1551                vk: drain_vk,
1552                nbf: 1_000,
1553                exp: 2_000,
1554            }),
1555            lead: Some(AtprotoOverlapKey {
1556                vk: lead_vk,
1557                nbf: 1_500,
1558                exp: 3_000,
1559            }),
1560        };
1561        let doc = build_did_document(
1562            did,
1563            "https://hyprstream.example.com",
1564            &[],
1565            Some(&atproto),
1566            &[],
1567            None,
1568            None,
1569        );
1570        let vms = doc["verificationMethod"].as_array().unwrap();
1571        assert_eq!(vms[0]["id"].as_str().unwrap(), format!("{did}#atproto"));
1572        // Exactly one active #atproto: stock resolvers keep their existing
1573        // first-exact-fragment behavior.
1574        assert_eq!(
1575            vms.iter()
1576                .filter(|v| v["id"]
1577                    .as_str()
1578                    .map(|s| s.ends_with("#atproto"))
1579                    .unwrap_or(false))
1580                .count(),
1581            1,
1582            "exactly one active #atproto method"
1583        );
1584        let drain = vms
1585            .iter()
1586            .find(|v| v["id"] == format!("{did}#atproto_drain"))
1587            .unwrap();
1588        assert_eq!(drain["nbf"], 1_000);
1589        assert_eq!(drain["exp"], 2_000);
1590        let lead = vms
1591            .iter()
1592            .find(|v| v["id"] == format!("{did}#atproto_lead"))
1593            .unwrap();
1594        assert_eq!(lead["nbf"], 1_500);
1595        assert_eq!(lead["exp"], 3_000);
1596
1597        let published = hyprstream_pds::commit::PublishedAtprotoKeys::from_did_document(&doc, did)
1598            .expect("published overlap document parses");
1599        assert_eq!(published.len(), 3);
1600        assert_eq!(published.live_keys(1_250).count(), 2, "active + drain");
1601        assert_eq!(published.live_keys(2_500).count(), 2, "active + lead");
1602    }
1603
1604    #[test]
1605    fn root_identity_publisher_and_consumer_enforce_bounded_overlap() {
1606        use hyprstream_rpc::admission::AdmittedIdentity;
1607        use hyprstream_rpc::auth::mac::Assurance;
1608        use hyprstream_rpc::auth::AtprotoPerimeterGateway;
1609        use hyprstream_rpc::identity_resolver::{DidDocumentProvider, MethodDispatchResolver};
1610
1611        #[derive(Clone)]
1612        struct Docs(Value);
1613        impl DidDocumentProvider for Docs {
1614            fn document(&self, _did: &str) -> anyhow::Result<Value> {
1615                Ok(self.0.clone())
1616            }
1617        }
1618
1619        let old = SigningKey::generate(&mut OsRng);
1620        let new = SigningKey::generate(&mut OsRng);
1621        let lead = SigningKey::generate(&mut OsRng);
1622        let old_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&old);
1623        let old_pq = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&old_pq);
1624        let slots = crate::auth::key_rotation::KeySlots {
1625            drain: Some(crate::auth::key_rotation::KeySlot::new(
1626                old.clone(),
1627                100,
1628                200,
1629            )),
1630            active: Some(crate::auth::key_rotation::KeySlot::new(
1631                new.clone(),
1632                150,
1633                400,
1634            )),
1635            lead: Some(crate::auth::key_rotation::KeySlot::new(
1636                lead.clone(),
1637                350,
1638                550,
1639            )),
1640        };
1641        let methods = root_identity_methods(&old, &old_pq, Some(&slots), 175);
1642        let did = "did:web:peer.example";
1643        let mut doc = build_did_document(did, "https://peer.example", &[], None, &[], None, None);
1644        append_root_identity_methods(&mut doc, did, &methods);
1645
1646        let ids: Vec<_> = doc["verificationMethod"]
1647            .as_array()
1648            .unwrap()
1649            .iter()
1650            .filter_map(|vm| vm["id"].as_str())
1651            .collect();
1652        assert!(ids.contains(&format!("{did}#key-1").as_str()));
1653        assert!(ids.contains(&format!("{did}#key-1-pq").as_str()));
1654        assert!(ids.contains(&format!("{did}#mesh-pq").as_str()));
1655        assert!(
1656            ids.iter().any(|id| id.contains("#mesh-")),
1657            "named rotation slots must be published"
1658        );
1659        // Mixed-version producer direction: the pre-upgrade resolver chose the
1660        // first compatible Ed25519 and first compatible ML-DSA method. During
1661        // the compatibility window those are still the old exact pair.
1662        let vms = doc["verificationMethod"].as_array().unwrap();
1663        let first_ed = vms
1664            .iter()
1665            .filter_map(|vm| vm["publicKeyMultibase"].as_str())
1666            .find_map(|multibase| hyprstream_rpc::did_web::decode_ed25519_multikey(multibase).ok())
1667            .unwrap();
1668        let first_pq = vms
1669            .iter()
1670            .filter_map(|vm| vm["publicKeyMultibase"].as_str())
1671            .find_map(|multibase| {
1672                hyprstream_rpc::did_web::decode_multikey(
1673                    multibase,
1674                    &hyprstream_rpc::did_web::MULTICODEC_ML_DSA_65_PUB,
1675                )
1676                .ok()
1677            })
1678            .unwrap();
1679        assert_eq!(first_ed, old.verifying_key().to_bytes());
1680        assert_eq!(first_pq, old_pq);
1681
1682        let now = Arc::new(std::sync::atomic::AtomicI64::new(175));
1683        let clock = Arc::clone(&now);
1684        let resolver = MethodDispatchResolver::new(Docs(doc))
1685            .with_clock(move || clock.load(std::sync::atomic::Ordering::SeqCst));
1686        let gateway = AtprotoPerimeterGateway::new(resolver);
1687        let admitted = |key: &SigningKey| AdmittedIdentity {
1688            origin: "https://peer.example".to_owned(),
1689            did: Some(did.to_owned()),
1690            key: key.verifying_key().to_bytes(),
1691        };
1692
1693        let old_peer = gateway
1694            .enroll(&admitted(&old))
1695            .expect("drain signer accepted during overlap");
1696        let new_peer = gateway
1697            .enroll(&admitted(&new))
1698            .expect("active signer accepted during overlap");
1699        assert_eq!(old_peer.assurance, Assurance::PqHybrid);
1700        assert_eq!(new_peer.assurance, Assurance::PqHybrid);
1701        assert!(
1702            gateway.enroll(&admitted(&lead)).is_err(),
1703            "lead is published before use but not accepted before nbf"
1704        );
1705
1706        now.store(200, std::sync::atomic::Ordering::SeqCst);
1707        assert!(
1708            gateway.enroll(&admitted(&old)).is_err(),
1709            "retired signer must fail exactly when its bound closes"
1710        );
1711        assert!(gateway.enroll(&admitted(&new)).is_ok());
1712    }
1713
1714    #[test]
1715    fn extract_jwks_filters_non_ed25519() {
1716        let jwks = json!({
1717            "keys": [
1718                {"kty": "OKP", "crv": "Ed25519", "x": URL_SAFE_NO_PAD.encode([1u8; 32]), "kid": "good"},
1719                {"kty": "EC", "crv": "P-256", "kid": "p256-not-ed25519"},
1720                {"kty": "OKP", "crv": "X25519", "kid": "wrong-curve"},
1721            ]
1722        });
1723        let keys = extract_ed25519_keys_from_jwks(&Some(jwks));
1724        assert_eq!(keys.len(), 1);
1725        assert_eq!(keys[0].0, "good");
1726    }
1727
1728    #[test]
1729    fn mesh_ed25519_vm_is_multikey() {
1730        // The `#mesh` verification method must be emitted as a Multikey (#280),
1731        // not the deprecated Ed25519VerificationKey2020 type.
1732        let sk = SigningKey::generate(&mut OsRng);
1733        let did = "did:web:hyprstream.example.com";
1734        let vm = ed25519_verification_method(did, "mesh", &sk.verifying_key());
1735        assert_eq!(vm["id"].as_str().unwrap(), format!("{did}#mesh"));
1736        assert_eq!(vm["type"].as_str().unwrap(), "Multikey");
1737        assert_eq!(vm["controller"].as_str().unwrap(), did);
1738        let mb = vm["publicKeyMultibase"].as_str().unwrap();
1739        assert!(
1740            mb.starts_with('z'),
1741            "Multikey publicKeyMultibase must be base58btc multibase"
1742        );
1743        // The encoded key carries the ed25519-pub multicodec prefix (0xed 0x01).
1744        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
1745        assert_eq!(&decoded[..2], &[0xed, 0x01]);
1746        assert_eq!(&decoded[2..], sk.verifying_key().as_bytes());
1747    }
1748
1749    #[test]
1750    fn mldsa65_multibase_multicodec_round_trip() {
1751        // ML-DSA-65 public keys are 1952 bytes (FIPS 204). Use a stand-in buffer
1752        // of the correct length to exercise the multicodec/multibase encoding.
1753        let vk_bytes = vec![0xABu8; 1952];
1754        let mb = mldsa65_to_multibase(&vk_bytes);
1755        assert!(mb.starts_with('z'), "must use base58btc multibase prefix");
1756        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
1757        // multicodec ml-dsa-65-pub = 0x1211 → unsigned-varint [0x91, 0x24].
1758        assert_eq!(&decoded[..2], &[0x91, 0x24]);
1759        // Remaining bytes are the verifying-key payload, unmodified.
1760        assert_eq!(&decoded[2..], vk_bytes.as_slice());
1761        assert_eq!(decoded.len(), 2 + 1952);
1762    }
1763
1764    #[test]
1765    fn build_did_doc_publishes_mesh_pq_vm() {
1766        // #157: when a mesh ML-DSA-65 vk is provided, build_did_document emits a
1767        // `#mesh-pq` Multikey VM with the ml-dsa-65-pub multicodec, listed after
1768        // the Ed25519 VMs, and referenced in authentication/assertionMethod.
1769        let sk = SigningKey::generate(&mut OsRng);
1770        let did = "did:web:hyprstream.example.com";
1771        let vk_bytes = vec![0x42u8; 1952];
1772        let doc = build_did_document(
1773            did,
1774            "https://hyprstream.example.com",
1775            &[("key-1".to_owned(), sk.verifying_key())],
1776            None,
1777            &[],
1778            Some(&vk_bytes),
1779            None,
1780        );
1781        let vms = doc["verificationMethod"].as_array().unwrap();
1782        // key-1 multibase + key-1 jwk + mesh-pq = 3.
1783        assert_eq!(vms.len(), 3);
1784        let pq = vms
1785            .iter()
1786            .find(|v| v["id"] == format!("{did}#mesh-pq"))
1787            .unwrap();
1788        assert_eq!(pq["type"].as_str().unwrap(), "Multikey");
1789        let mb = pq["publicKeyMultibase"].as_str().unwrap();
1790        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
1791        assert_eq!(&decoded[..2], &[0x91, 0x24]); // ml-dsa-65-pub multicodec
1792        assert_eq!(&decoded[2..], vk_bytes.as_slice());
1793        // Referenced as both an authentication and assertion method.
1794        let mesh_pq_id = format!("{did}#mesh-pq");
1795        assert!(doc["authentication"]
1796            .as_array()
1797            .unwrap()
1798            .iter()
1799            .any(|v| *v == mesh_pq_id));
1800        assert!(doc["assertionMethod"]
1801            .as_array()
1802            .unwrap()
1803            .iter()
1804            .any(|v| *v == mesh_pq_id));
1805    }
1806
1807    #[test]
1808    fn mesh_pq_vm_matches_derived_signing_key() {
1809        // #157 scope #1/#2 consistency: the `#mesh-pq` VM published from the
1810        // OAuth signing key must equal the ML-DSA-65 verifying key the mesh
1811        // actually signs with (derive_mesh_mldsa_key over the same Ed25519 key).
1812        let sk = SigningKey::generate(&mut OsRng);
1813        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&sk);
1814        let pq_vk_bytes = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk);
1815
1816        let did = "did:web:hyprstream.example.com";
1817        let doc = build_did_document(
1818            did,
1819            "https://hyprstream.example.com",
1820            &[("key-1".to_owned(), sk.verifying_key())],
1821            None,
1822            &[],
1823            Some(&pq_vk_bytes),
1824            None,
1825        );
1826        let vms = doc["verificationMethod"].as_array().unwrap();
1827        let pq = vms
1828            .iter()
1829            .find(|v| v["id"] == format!("{did}#mesh-pq"))
1830            .unwrap();
1831        let mb = pq["publicKeyMultibase"].as_str().unwrap();
1832        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
1833        assert_eq!(
1834            &decoded[2..],
1835            pq_vk_bytes.as_slice(),
1836            "published #mesh-pq key must equal the derived mesh signing key's public key"
1837        );
1838    }
1839
1840    #[test]
1841    fn root_doc_advertises_iroh_only_as_transport_when_bound() {
1842        // #282: when the iroh substrate is bound, root_did_document adds the
1843        // IrohTransport service entry accepting both ALPNs, but no VM.
1844        let oauth_sk = SigningKey::generate(&mut OsRng);
1845        let node_sk = SigningKey::generate(&mut OsRng);
1846        let node_id = node_sk.verifying_key().to_bytes();
1847        let did = "did:web:hyprstream.example.com";
1848
1849        let keys = vec![("key-1".to_owned(), oauth_sk.verifying_key())];
1850        let transports = [TransportEndpoint {
1851            fragment: "iroh".to_owned(),
1852            vm_type: "IrohTransport".to_owned(),
1853            endpoint: hyprstream_rpc::service_entry::encode_iroh(
1854                &node_id,
1855                &[],
1856                &["hyprstream-rpc/1"],
1857            ),
1858        }];
1859        let doc = build_did_document(
1860            did,
1861            "https://hyprstream.example.com",
1862            &keys,
1863            None,
1864            &transports,
1865            None,
1866            None,
1867        );
1868
1869        // Equality to a valid Ed25519 key does not create identity authority.
1870        let vms = doc["verificationMethod"].as_array().unwrap();
1871        assert!(vms.iter().all(|v| v["id"] != format!("{did}#iroh")));
1872
1873        // The IrohTransport service entry accepts BOTH ALPNs.
1874        let svcs = doc["service"].as_array().unwrap();
1875        let iroh_svc = svcs
1876            .iter()
1877            .find(|s| s["type"] == "IrohTransport")
1878            .expect("IrohTransport service entry must be advertised");
1879        assert_eq!(iroh_svc["id"].as_str().unwrap(), format!("{did}#iroh"));
1880        let accept = iroh_svc["serviceEndpoint"]["accept"].as_array().unwrap();
1881        let accept: Vec<&str> = accept.iter().filter_map(|v| v.as_str()).collect();
1882        assert_eq!(accept, vec!["hyprstream-rpc/1"]);
1883    }
1884
1885    #[test]
1886    fn root_doc_omits_iroh_when_not_bound() {
1887        // No iroh transport configured → no IrohTransport entry.
1888        let sk = SigningKey::generate(&mut OsRng);
1889        let did = "did:web:hyprstream.example.com";
1890        let doc = build_did_document(
1891            did,
1892            "https://hyprstream.example.com",
1893            &[("key-1".to_owned(), sk.verifying_key())],
1894            None,
1895            &[],
1896            None,
1897            None,
1898        );
1899        let vms = doc["verificationMethod"].as_array().unwrap();
1900        assert!(
1901            !vms.iter().any(|v| v["id"] == format!("{did}#iroh")),
1902            "carrier NodeId is never a DID verification method"
1903        );
1904        let svcs = doc["service"].as_array().unwrap();
1905        assert!(
1906            !svcs.iter().any(|s| s["type"] == "IrohTransport"),
1907            "no IrohTransport entry when iroh is not bound"
1908        );
1909    }
1910
1911    #[test]
1912    fn build_did_doc_omits_key_agreement_when_mesh_kem_absent() {
1913        // No `#mesh-kem` public material provided → `keyAgreement` is present
1914        // but empty (a valid, empty DID-document relationship), never omitted
1915        // outright (omitting the key entirely would be a different, also-valid
1916        // shape, but an empty array is simpler for consumers to handle uniformly).
1917        let sk = SigningKey::generate(&mut OsRng);
1918        let did = "did:web:hyprstream.example.com";
1919        let doc = build_did_document(
1920            did,
1921            "https://hyprstream.example.com",
1922            &[("key-1".to_owned(), sk.verifying_key())],
1923            None,
1924            &[],
1925            None,
1926            None,
1927        );
1928        assert_eq!(doc["keyAgreement"].as_array().unwrap().len(), 0);
1929    }
1930
1931    #[test]
1932    fn build_did_doc_publishes_mesh_kem_key_agreement() {
1933        // S1 / #552: when a `#mesh-kem` recipient public is provided,
1934        // build_did_document emits both suite-component `keyAgreement` VMs
1935        // (X25519 + ML-KEM-768), embedded directly (not cross-referenced from
1936        // verificationMethod/authentication/assertionMethod — these are
1937        // key-agreement-only keys).
1938        let node_sk = SigningKey::generate(&mut OsRng);
1939        let kem_kp = hyprstream_rpc::node_identity::derive_mesh_kem_recipient(&node_sk)
1940            .expect("derive #mesh-kem recipient");
1941        let kem_pub = kem_kp.public();
1942
1943        let did = "did:web:hyprstream.example.com";
1944        let doc = build_did_document(
1945            did,
1946            "https://hyprstream.example.com",
1947            &[("key-1".to_owned(), node_sk.verifying_key())],
1948            None,
1949            &[],
1950            None,
1951            Some(&kem_pub),
1952        );
1953
1954        // keyAgreement carries exactly the two suite-component VMs, and they
1955        // are NOT duplicated into verificationMethod/authentication/assertionMethod.
1956        let kas = doc["keyAgreement"].as_array().unwrap();
1957        assert_eq!(kas.len(), 2);
1958        assert_eq!(
1959            kas[0]["id"].as_str().unwrap(),
1960            format!("{did}#mesh-kem-x25519")
1961        );
1962        assert_eq!(kas[0]["type"].as_str().unwrap(), "Multikey");
1963        assert_eq!(
1964            kas[1]["id"].as_str().unwrap(),
1965            format!("{did}#mesh-kem-mlkem768")
1966        );
1967        assert_eq!(kas[1]["type"].as_str().unwrap(), "Multikey");
1968
1969        let vms = doc["verificationMethod"].as_array().unwrap();
1970        assert!(!vms
1971            .iter()
1972            .any(|v| v["id"] == format!("{did}#mesh-kem-x25519")));
1973        assert!(!vms
1974            .iter()
1975            .any(|v| v["id"] == format!("{did}#mesh-kem-mlkem768")));
1976        assert!(!doc["authentication"]
1977            .as_array()
1978            .unwrap()
1979            .iter()
1980            .any(|v| v.as_str().map(|s| s.contains("mesh-kem")).unwrap_or(false)));
1981
1982        // The published X25519 leg round-trips to the exact bytes derived —
1983        // consistency between the DID doc and the key the node actually holds.
1984        let mb = kas[0]["publicKeyMultibase"].as_str().unwrap();
1985        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
1986        assert_eq!(&decoded[..2], &MULTICODEC_X25519_PUB);
1987        assert_eq!(&decoded[2..], kem_pub.eks[0].as_slice());
1988
1989        let mb2 = kas[1]["publicKeyMultibase"].as_str().unwrap();
1990        let decoded2 = bs58::decode(&mb2[1..]).into_vec().unwrap();
1991        assert_eq!(&decoded2[..2], &MULTICODEC_ML_KEM_768_PUB);
1992        assert_eq!(&decoded2[2..], kem_pub.eks[1].as_slice());
1993    }
1994
1995    #[test]
1996    fn mldsa65_verification_method_is_multikey() {
1997        let did = "did:web:hyprstream.example.com";
1998        let vk_bytes = vec![0x07u8; 1952];
1999        let vm = mldsa65_verification_method(did, "mesh-pq", &vk_bytes);
2000        assert_eq!(vm["id"].as_str().unwrap(), format!("{did}#mesh-pq"));
2001        assert_eq!(vm["type"].as_str().unwrap(), "Multikey");
2002        assert_eq!(vm["controller"].as_str().unwrap(), did);
2003        let mb = vm["publicKeyMultibase"].as_str().unwrap();
2004        let decoded = bs58::decode(&mb[1..]).into_vec().unwrap();
2005        assert_eq!(&decoded[..2], &[0x91, 0x24]); // ml-dsa-65-pub multicodec
2006        assert_eq!(&decoded[2..], vk_bytes.as_slice());
2007    }
2008}