Skip to main content

hyprstream_core/services/oauth/
federate_source.rs

1//! Exact configured-host Federate source/possession verification.
2//!
3//! This verifies cryptographic evidence, NOT account authority, callback execution,
4//! PKCE redemption, key freshness, or global replay consumption. Policy must
5//! supply authority and durable replay admission. No evidence is a credential.
6
7use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64, Engine};
8use ed25519_dalek::{Signature, VerifyingKey};
9use hyprstream_rpc::crypto::pq::{ml_dsa_verify, ml_dsa_vk_from_bytes};
10use jsonwebtoken::{crypto, Algorithm, DecodingKey};
11use serde::{
12    de::{self, MapAccess, SeqAccess, Visitor},
13    Deserialize, Deserializer,
14};
15use serde_json::Value;
16use sha2::{Digest, Sha256};
17use std::{
18    collections::BTreeMap,
19    fmt,
20    time::{Duration, Instant},
21};
22use subtle::ConstantTimeEq;
23use tokio::sync::Mutex;
24
25pub(crate) const ISSUER: &str = "https://login.federate.to";
26pub(crate) const CLIENT: &str = hyprstream_rpc::auth::claims::FEDERATE_STAGING_CLIENT;
27/// Session profile string of the second (TUI) client class. Distinct from
28/// the www `federate-session-v1` suite/inventory markers: a credential of
29/// this class takes NORMAL JWT verification, not the deferred branch.
30pub(crate) const TUI_PROFILE: &str = "federate-tui-v1";
31/// Challenge profile of the W1b device variant: the commitment binds
32/// `device_code` instead of `state`/`pkce`, and the holder Ed25519 key is
33/// authenticated by the issuer-signed `binding_key` claim (W5f/D1) instead
34/// of the `nonce`/`c_hash` pair. Accepted only for a configured non-staging
35/// class; the www staging class keeps the authorization-code flow only.
36pub(crate) const TUI_DEVICE_PROFILE: &str = "federate-session-v2-device";
37pub(crate) const WEBSITE: &str = "https://www.staging.lab.hyprstream.com";
38pub(crate) const CALLBACK: &str = "https://www.staging.lab.hyprstream.com/federate/callback";
39#[cfg(test)]
40pub(crate) const HOST: &str = hyprstream_rpc::auth::claims::FEDERATE_STAGING_HOST;
41pub(crate) use hyprstream_rpc::auth::claims::FederateHost;
42const JWKS: &str = "https://login.federate.to/keys";
43const SUITE: &str = "hs-cose-sign-ed25519-mldsa65-wns-v1";
44const MAX_JWS: usize = 16 * 1024;
45const MAX_JWKS: usize = 64 * 1024;
46const MAX_TRANSCRIPT: usize = 8 * 1024;
47const MAX_AUTHORITY_TEXT: usize = 256;
48const MAX_SCOPE_BYTES: usize = 1024;
49const KEY_TTL: Duration = Duration::from_secs(60);
50const MAX_CLIENT_TEXT: usize = 256;
51const MAX_CONNECTOR_TEXT: usize = 64;
52
53/// One accepted Federate client class (W1).
54///
55/// The staging class is the hardcoded www pin. A second class (the TUI
56/// harness) may be configured per issuer; it carries IDENTICAL source
57/// verification invariants — pinned RS256, kid-keyed JWKS, `exp - iat <=
58/// 300s`, nonce/c_hash binding (at_hash is value-checked only when an
59/// access token is supplied, otherwise encoding-only, per D8), the
60/// connector pin, and did:plc / host-form did:web validation. The class
61/// only selects the pinned identifiers, and every commitment binds its
62/// exact `client_id` in both the nonce preimage and the possession
63/// transcript. This is source-verification acceptance only: the output
64/// credential profile and its dispatch treatment are owned by W1.3/W1.4.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub(crate) struct ClientClass {
67    client_id: String,
68    aud: String,
69    connector: String,
70}
71
72impl ClientClass {
73    /// The hardcoded staging www class (`aud` == `client_id`, `atproto`).
74    pub(crate) fn staging() -> Self {
75        Self {
76            client_id: CLIENT.into(),
77            aud: CLIENT.into(),
78            connector: "atproto".into(),
79        }
80    }
81
82    /// Fail-closed construction of the configured second class. The class
83    /// must stay disjoint from the reserved staging pin so the
84    /// reserved-credential predicate (`iss`, `client_id`) can never match
85    /// this class — predicate-level behavior only; the minted-profile path
86    /// and dispatch treatment are decided by later slices, not here.
87    pub(crate) fn new(client_id: &str, aud: &str, connector: Option<&str>) -> Result<Self> {
88        let text = |value: &str, max: usize| {
89            require(!value.is_empty() && value.len() <= max)?;
90            require(value.bytes().all(|b| (0x21..=0x7e).contains(&b)))?;
91            Ok(())
92        };
93        text(client_id, MAX_CLIENT_TEXT)?;
94        text(aud, MAX_CLIENT_TEXT)?;
95        let connector = connector.unwrap_or("atproto");
96        text(connector, MAX_CONNECTOR_TEXT)?;
97        require(client_id != CLIENT && aud != CLIENT)?;
98        Ok(Self {
99            client_id: client_id.into(),
100            aud: aud.into(),
101            connector: connector.into(),
102        })
103    }
104
105    pub(crate) fn client_id(&self) -> &str {
106        &self.client_id
107    }
108
109    /// The session profile string this class mints and accepts on the wire.
110    /// The staging class keeps `federate-session-v1` byte-for-byte; the
111    /// configured second class uses its own distinct TUI profile string.
112    pub(crate) fn profile(&self) -> &'static str {
113        if self.client_id == CLIENT {
114            "federate-session-v1"
115        } else {
116            TUI_PROFILE
117        }
118    }
119}
120
121#[derive(Debug, PartialEq, Eq, thiserror::Error)]
122pub(crate) enum Error {
123    #[error("Federate verifier disabled")]
124    Disabled,
125    #[error("invalid Federate evidence")]
126    Invalid,
127    #[error("Federate signing authority unavailable")]
128    Unavailable,
129}
130type Result<T> = std::result::Result<T, Error>;
131fn require(ok: bool) -> Result<()> {
132    if ok {
133        Ok(())
134    } else {
135        Err(Error::Invalid)
136    }
137}
138fn sha(bytes: &[u8]) -> [u8; 32] {
139    Sha256::digest(bytes).into()
140}
141fn equal(a: &[u8], b: &[u8]) -> bool {
142    bool::from(a.ct_eq(b))
143}
144fn decode(value: &str, max: usize) -> Result<Vec<u8>> {
145    require(value.len() <= max.saturating_mul(4).div_ceil(3))?;
146    let bytes = B64.decode(value).map_err(|_| Error::Invalid)?;
147    require(bytes.len() <= max && B64.encode(&bytes) == value)?;
148    Ok(bytes)
149}
150fn fixed<const N: usize>(value: &str) -> Result<[u8; N]> {
151    decode(value, N)?.try_into().map_err(|_| Error::Invalid)
152}
153fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str> {
154    let s = value
155        .get(key)
156        .and_then(Value::as_str)
157        .ok_or(Error::Invalid)?;
158    require(!s.is_empty() && s.len() <= 2048)?;
159    Ok(s)
160}
161fn frame(domain: &str, fields: &[&[u8]]) -> Vec<u8> {
162    let mut out = domain.as_bytes().to_vec();
163    out.push(0);
164    out.extend_from_slice(&(fields.len() as u32).to_be_bytes());
165    for field in fields {
166        out.extend_from_slice(&(field.len() as u32).to_be_bytes());
167        out.extend_from_slice(field);
168    }
169    out
170}
171
172// Reject duplicate members at every nesting level, including unknown claims.
173struct Unique(Value);
174impl<'de> Deserialize<'de> for Unique {
175    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
176        struct V;
177        impl<'de> Visitor<'de> for V {
178            type Value = Unique;
179            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
180                f.write_str("unique-key JSON")
181            }
182            fn visit_map<M: MapAccess<'de>>(
183                self,
184                mut m: M,
185            ) -> std::result::Result<Unique, M::Error> {
186                let mut out = serde_json::Map::new();
187                while let Some((k, v)) = m.next_entry::<String, Unique>()? {
188                    if out.insert(k, v.0).is_some() {
189                        return Err(de::Error::custom("duplicate member"));
190                    }
191                }
192                Ok(Unique(Value::Object(out)))
193            }
194            fn visit_seq<S: SeqAccess<'de>>(
195                self,
196                mut s: S,
197            ) -> std::result::Result<Unique, S::Error> {
198                let mut out = Vec::new();
199                while let Some(v) = s.next_element::<Unique>()? {
200                    out.push(v.0);
201                }
202                Ok(Unique(Value::Array(out)))
203            }
204            fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<Unique, E> {
205                Ok(Unique(Value::String(v.into())))
206            }
207            fn visit_bool<E: de::Error>(self, v: bool) -> std::result::Result<Unique, E> {
208                Ok(Unique(Value::Bool(v)))
209            }
210            fn visit_u64<E: de::Error>(self, v: u64) -> std::result::Result<Unique, E> {
211                Ok(Unique(v.into()))
212            }
213            fn visit_i64<E: de::Error>(self, v: i64) -> std::result::Result<Unique, E> {
214                Ok(Unique(v.into()))
215            }
216            fn visit_f64<E: de::Error>(self, v: f64) -> std::result::Result<Unique, E> {
217                Ok(Unique(v.into()))
218            }
219            fn visit_unit<E: de::Error>(self) -> std::result::Result<Unique, E> {
220                Ok(Unique(Value::Null))
221            }
222        }
223        d.deserialize_any(V)
224    }
225}
226fn json(bytes: &[u8]) -> Result<Value> {
227    serde_json::from_slice::<Unique>(bytes)
228        .map(|v| v.0)
229        .map_err(|_| Error::Invalid)
230}
231
232/// Validated commitment inputs. The host cannot prove client key freshness.
233pub(crate) struct Commitment {
234    host: FederateHost,
235    /// The client class this commitment is bound to (W1). Binds the nonce
236    /// preimage and the possession transcript to the exact class, so a
237    /// nonce or transcript minted for one class is useless for another.
238    client: ClientClass,
239    random: [u8; 32],
240    /// The session-establishment flow this commitment binds (W1b).
241    flow: Flow,
242    ed: [u8; 32],
243    pq: Vec<u8>,
244}
245
246/// Flow-specific commitment fields (W1b). The authorization-code flow binds
247/// the browser `state` and the PKCE challenge and is pinned by the token's
248/// `nonce`/`c_hash` claims. The device flow binds the RFC 8628
249/// `device_code` instead; the token pins it through the issuer-signed
250/// `binding_key` claim that authenticates the holder Ed25519 key, exactly
251/// as `nonce` binds the code flow (D1). The two preimages are separated by
252/// distinct framing domains, so no value is valid under both flows.
253enum Flow {
254    Code { state: String, pkce: String },
255    Device { device_code: String },
256}
257impl Commitment {
258    #[cfg(test)]
259    pub(crate) fn new(random: &str, state: &str, pkce: &str, ed: &str, pq: &str) -> Result<Self> {
260        Self::for_host(
261            FederateHost::new(HOST).map_err(|_| Error::Invalid)?,
262            random,
263            state,
264            pkce,
265            ed,
266            pq,
267        )
268    }
269    /// Commitment for the hardcoded staging www class.
270    pub(crate) fn for_host(
271        host: FederateHost,
272        random: &str,
273        state: &str,
274        pkce: &str,
275        ed: &str,
276        pq: &str,
277    ) -> Result<Self> {
278        Self::for_class(host, &ClientClass::staging(), random, state, pkce, ed, pq)
279    }
280    /// Commitment for one accepted client class (staging or configured).
281    pub(crate) fn for_class(
282        host: FederateHost,
283        client: &ClientClass,
284        random: &str,
285        state: &str,
286        pkce: &str,
287        ed: &str,
288        pq: &str,
289    ) -> Result<Self> {
290        let (ed, pq) = Self::keys(ed, pq)?;
291        fixed::<32>(state)?;
292        fixed::<32>(pkce)?;
293        Ok(Self {
294            host,
295            client: client.clone(),
296            random: fixed(random)?,
297            flow: Flow::Code {
298                state: state.into(),
299                pkce: pkce.into(),
300            },
301            ed,
302            pq,
303        })
304    }
305    /// Device-flow commitment for one accepted client class (W1b). The
306    /// caller (the exchange wire) restricts this variant to a configured
307    /// non-staging class; the constructor itself only validates inputs.
308    pub(crate) fn for_class_device(
309        host: FederateHost,
310        client: &ClientClass,
311        random: &str,
312        device_code: &str,
313        ed: &str,
314        pq: &str,
315    ) -> Result<Self> {
316        let (ed, pq) = Self::keys(ed, pq)?;
317        require(
318            !device_code.is_empty()
319                && device_code.len() <= MAX_AUTHORITY_TEXT
320                && device_code.is_ascii(),
321        )?;
322        Ok(Self {
323            host,
324            client: client.clone(),
325            random: fixed(random)?,
326            flow: Flow::Device {
327                device_code: device_code.into(),
328            },
329            ed,
330            pq,
331        })
332    }
333    fn keys(ed: &str, pq: &str) -> Result<([u8; 32], Vec<u8>)> {
334        let ed = fixed(ed)?;
335        let vk = VerifyingKey::from_bytes(&ed).map_err(|_| Error::Invalid)?;
336        require(!vk.is_weak())?;
337        let pq = decode(pq, 1952)?;
338        ml_dsa_vk_from_bytes(&pq).map_err(|_| Error::Invalid)?;
339        Ok((ed, pq))
340    }
341    fn preimage(&self) -> Vec<u8> {
342        match &self.flow {
343            Flow::Code { state, pkce } => frame(
344                "hyprstream.federate.session-primary.nonce.v1",
345                &[
346                    ISSUER.as_bytes(),
347                    self.client.client_id.as_bytes(),
348                    WEBSITE.as_bytes(),
349                    CALLBACK.as_bytes(),
350                    self.host.as_str().as_bytes(),
351                    self.host.as_str().as_bytes(),
352                    &self.random,
353                    &self.ed,
354                    &self.pq,
355                    &sha(state.as_bytes()),
356                    pkce.as_bytes(),
357                ],
358            ),
359            // W1b/D6: exactly (login_random, device_code, client_id, holder
360            // ed/pq keys). The holder key is authenticated by the signed
361            // `binding_key` claim, not by this preimage.
362            Flow::Device { device_code } => frame(
363                "hyprstream.federate.session-primary.device-nonce.v1",
364                &[
365                    &self.random,
366                    device_code.as_bytes(),
367                    self.client.client_id.as_bytes(),
368                    &self.ed,
369                    &self.pq,
370                ],
371            ),
372        }
373    }
374    pub(crate) fn nonce(&self) -> String {
375        format!("hsn1.{}", B64.encode(sha(&self.preimage())))
376    }
377    fn kids(&self) -> [[u8; 32]; 2] {
378        session_primary_kids(&self.ed, &self.pq)
379    }
380}
381
382// Shared by possession verification and the disabled request-proof consumer.
383pub(super) fn session_primary_kids(ed: &[u8; 32], pq: &[u8]) -> [[u8; 32]; 2] {
384    [
385        sha(&frame(
386            "hyprstream.session-primary.kid.v1",
387            &[b"Ed25519", ed],
388        )),
389        sha(&frame(
390            "hyprstream.session-primary.kid.v1",
391            &[b"ML-DSA-65", pq],
392        )),
393    ]
394}
395
396struct Keys {
397    fetched: Instant,
398    keys: BTreeMap<String, DecodingKey>,
399}
400fn parse_keys(bytes: &[u8]) -> Result<BTreeMap<String, DecodingKey>> {
401    require(bytes.len() <= MAX_JWKS)?;
402    let doc = json(bytes)?;
403    let entries = doc
404        .get("keys")
405        .and_then(Value::as_array)
406        .ok_or(Error::Invalid)?;
407    require(!entries.is_empty() && entries.len() <= 16)?;
408    let mut keys = BTreeMap::new();
409    for entry in entries {
410        let obj = entry.as_object().ok_or(Error::Invalid)?;
411        require(
412            obj.keys()
413                .all(|k| ["kid", "kty", "use", "alg", "n", "e", "key_ops"].contains(&k.as_str())),
414        )?;
415        require(text(entry, "kty")? == "RSA")?;
416        for (k, expected) in [("alg", "RS256"), ("use", "sig")] {
417            if let Some(v) = entry.get(k) {
418                require(v.as_str() == Some(expected))?;
419            }
420        }
421        if let Some(ops) = entry.get("key_ops") {
422            require(*ops == serde_json::json!(["verify"]))?;
423        }
424        let n = text(entry, "n")?;
425        let e = text(entry, "e")?;
426        let modulus = decode(n, 512)?;
427        require(
428            (256..=512).contains(&modulus.len())
429                && modulus[0] >= 128
430                && modulus.last().is_some_and(|b| b & 1 == 1),
431        )?;
432        let exponent = decode(e, 4)?;
433        require(!exponent.is_empty() && exponent[0] != 0)?;
434        let exponent = exponent.iter().fold(0u64, |n, b| (n << 8) | u64::from(*b));
435        require(exponent >= 3 && exponent % 2 == 1)?;
436        let key = DecodingKey::from_rsa_components(n, e).map_err(|_| Error::Invalid)?;
437        require(keys.insert(text(entry, "kid")?.into(), key).is_none())?;
438    }
439    Ok(keys)
440}
441
442/// Disabled by default; enabled only with a validated server-configured host.
443#[derive(Default)]
444pub(crate) struct Verifier {
445    host: Option<FederateHost>,
446    /// Optional configured second client class beside the hardcoded staging
447    /// pin (W1: the TUI harness). `None` = staging-only, exactly the
448    /// previous behavior.
449    tui_client: Option<ClientClass>,
450    client: Option<reqwest::Client>,
451    keys: Mutex<Option<Keys>>,
452    #[cfg(test)]
453    responses: Option<parking_lot::Mutex<Vec<Result<Vec<u8>>>>>,
454}
455
456#[cfg(test)]
457impl Verifier {
458    /// Queue canned JWKS fetch responses (offline issuer-level fixtures).
459    pub(crate) fn set_test_responses(&mut self, responses: Vec<Result<Vec<u8>>>) {
460        self.responses = Some(parking_lot::Mutex::new(responses));
461    }
462}
463impl Verifier {
464    #[cfg(test)]
465    pub(crate) fn fixed_staging() -> Result<Self> {
466        Self::for_host(FederateHost::new(HOST).map_err(|_| Error::Invalid)?)
467    }
468    pub(crate) fn host(&self) -> Result<&FederateHost> {
469        self.host.as_ref().ok_or(Error::Disabled)
470    }
471    pub(crate) fn for_host(host: FederateHost) -> Result<Self> {
472        let client = reqwest::Client::builder()
473            .redirect(reqwest::redirect::Policy::none())
474            .timeout(Duration::from_secs(2))
475            .build()
476            .map_err(|_| Error::Unavailable)?;
477        Ok(Self {
478            host: Some(host),
479            tui_client: None,
480            client: Some(client),
481            keys: Mutex::new(None),
482            #[cfg(test)]
483            responses: None,
484        })
485    }
486    /// Accept an additional configured client class (W1). Both classes
487    /// verify under identical invariants.
488    pub(crate) fn with_client_class(mut self, class: ClientClass) -> Self {
489        self.tui_client = Some(class);
490        self
491    }
492    /// Resolve a wire `client_id` to the one accepted class it names.
493    /// Anything but the staging pin or the configured class fails closed
494    /// before any signature or claim work.
495    pub(crate) fn resolve_client_class(&self, client_id: &str) -> Result<ClientClass> {
496        if client_id == CLIENT {
497            return Ok(ClientClass::staging());
498        }
499        match &self.tui_client {
500            Some(class) if class.client_id == client_id => Ok(class.clone()),
501            _ => Err(Error::Invalid),
502        }
503    }
504
505    /// The configured second client class, if any. `None` means
506    /// staging-only: the exact previous behavior (W1.1 default-deny).
507    pub(crate) fn tui_client(&self) -> Option<&ClientClass> {
508        self.tui_client.as_ref()
509    }
510
511    /// The configured second client class's `client_id`, if any. `None`
512    /// means staging-only: the exact previous behavior (W1.1 default-deny).
513    pub(crate) fn tui_client_id(&self) -> Option<&str> {
514        self.tui_client
515            .as_ref()
516            .map(|class| class.client_id.as_str())
517    }
518    async fn fetch(&self, client: &reqwest::Client) -> Result<Vec<u8>> {
519        #[cfg(test)]
520        if let Some(responses) = &self.responses {
521            let mut responses = responses.lock();
522            return if responses.is_empty() {
523                Err(Error::Unavailable)
524            } else {
525                responses.remove(0)
526            };
527        }
528        let mut response = client
529            .get(JWKS)
530            .send()
531            .await
532            .map_err(|_| Error::Unavailable)?;
533        if !response.status().is_success()
534            || response
535                .content_length()
536                .is_some_and(|n| n > MAX_JWKS as u64)
537        {
538            return Err(Error::Unavailable);
539        }
540        let mut bytes = Vec::new();
541        while let Some(chunk) = response.chunk().await.map_err(|_| Error::Unavailable)? {
542            if bytes.len() + chunk.len() > MAX_JWKS {
543                return Err(Error::Unavailable);
544            }
545            bytes.extend_from_slice(&chunk);
546        }
547        Ok(bytes)
548    }
549    async fn key(&self, kid: &str) -> Result<DecodingKey> {
550        let client = self.client.as_ref().ok_or(Error::Disabled)?;
551        // A single-flight cache; the deadline also bounds queue wait/body reads.
552        tokio::time::timeout(Duration::from_secs(2), async {
553            let mut cache = self.keys.lock().await;
554            if let Some(keys) = cache.as_ref().filter(|k| k.fetched.elapsed() < KEY_TTL) {
555                if let Some(key) = keys.keys.get(kid) {
556                    return Ok(key.clone());
557                }
558            }
559            // One fixed-authority refresh per lookup; never follow JWS URLs.
560            let bytes = self.fetch(client).await?;
561            let keys = parse_keys(&bytes).map_err(|_| Error::Unavailable)?;
562            let key = keys.get(kid).cloned().ok_or(Error::Invalid);
563            *cache = Some(Keys {
564                fetched: Instant::now(),
565                keys,
566            });
567            key
568        })
569        .await
570        .map_err(|_| Error::Unavailable)?
571    }
572    pub(crate) async fn source(
573        &self,
574        token: &str,
575        code: &str,
576        commitment: Commitment,
577        now: u64,
578        access_token: Option<&str>,
579    ) -> Result<Source> {
580        require(self.host()? == &commitment.host)?;
581        // The commitment must carry EXACTLY this verifier's canonical class
582        // for its client_id: client_id, aud and connector are all compared.
583        // A caller-built class that reuses a configured client_id with a
584        // different aud or connector is rejected here, before any claim is
585        // validated against the commitment's pins. Default-deny: an
586        // unconfigured client_id resolves to an error.
587        require(
588            self.resolve_client_class(commitment.client.client_id.as_str())? == commitment.client,
589        )?;
590        require(token.len() <= MAX_JWS && !token.is_empty())?;
591        let parts: Vec<_> = token.split('.').collect();
592        require(parts.len() == 3)?;
593        let header = json(&decode(parts[0], 2048)?)?;
594        require(
595            header
596                .as_object()
597                .ok_or(Error::Invalid)?
598                .keys()
599                .all(|k| ["alg", "kid", "typ"].contains(&k.as_str())),
600        )?;
601        require(text(&header, "alg")? == "RS256")?;
602        if let Some(typ) = header.get("typ") {
603            require(typ.as_str() == Some("JWT"))?;
604        }
605        let claims = json(&decode(parts[1], MAX_JWS)?)?;
606        let sig = decode(parts[2], 512)?;
607        require((256..=512).contains(&sig.len()))?;
608        let key = self.key(text(&header, "kid")?).await?;
609        let signed = &token[..token.len() - parts[2].len() - 1];
610        require(
611            crypto::verify(parts[2], signed.as_bytes(), &key, Algorithm::RS256)
612                .map_err(|_| Error::Invalid)?,
613        )?;
614        validate_claims(&claims, code, &commitment, now, access_token)?;
615        Ok(Source {
616            subject: text(&claims, "sub")?.into(),
617            atproto_did: atproto_account_did(&claims, &commitment.client.connector)?,
618            jti: text(&claims, "jti")?.into(),
619            issued_at: number(&claims, "iat")?,
620            expires_at: number(&claims, "exp")?,
621            token_hash: sha(token.as_bytes()),
622            code_hash: sha(code.as_bytes()),
623            commitment,
624        })
625    }
626}
627fn number(v: &Value, k: &str) -> Result<u64> {
628    v.get(k).and_then(Value::as_u64).ok_or(Error::Invalid)
629}
630fn times(iat: u64, exp: u64, now: u64) -> Result<()> {
631    require(
632        exp <= i64::MAX as u64
633            && exp > iat
634            && exp - iat <= 300
635            && iat <= now.saturating_add(30)
636            && now.saturating_sub(iat) <= 120
637            && now < exp,
638    )
639}
640fn hash_claim(claim: &str, input: &str) -> Result<()> {
641    require(!input.is_empty() && input.len() <= MAX_JWS && input.is_ascii())?;
642    require(equal(&fixed::<16>(claim)?, &sha(input.as_bytes())[..16]))
643}
644
645pub(super) fn atproto_account_did(
646    v: &Value,
647    connector: &str,
648) -> std::result::Result<String, Error> {
649    let claims = v
650        .get("federated_claims")
651        .and_then(Value::as_object)
652        .ok_or(Error::Invalid)?;
653    require(claims.get("connector_id").and_then(Value::as_str) == Some(connector))?;
654    let did = claims
655        .get("user_id")
656        .and_then(Value::as_str)
657        .ok_or(Error::Invalid)?;
658    require(did.len() <= 255 && did.is_ascii())?;
659    // The configured Dex connector supports ATProto's did:plc and did:web
660    // identifiers. The pinned connector resolves the account during login.
661    let method_specific = did.strip_prefix("did:").ok_or(Error::Invalid)?;
662    let (method, specific) = method_specific.split_once(':').ok_or(Error::Invalid)?;
663    match method {
664        "plc" => {
665            require(
666                specific.len() == 24
667                    && specific
668                        .bytes()
669                        .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b)),
670            )?;
671        }
672        "web" => {
673            // ATProto repo/account identifiers use host-form did:web only;
674            // a literal colon introduces a path-form DID that the ATProto
675            // identity profile does not accept. Keep this aligned with the
676            // repo-authority validator while allowing encoded host ports.
677            require(!hyprstream_pds::repo_authority::is_path_form_did_web(did))?;
678            require(
679                !specific.is_empty()
680                    && specific.split(':').all(|part| !part.is_empty())
681                    && specific.bytes().all(|b| {
682                        b.is_ascii_alphanumeric()
683                            || b == b'.'
684                            || b == b'-'
685                            || b == b'%'
686                            || b == b':'
687                    }),
688            )?;
689            let bytes = specific.as_bytes();
690            for (i, byte) in bytes.iter().enumerate() {
691                if *byte == b'%' {
692                    require(
693                        i + 2 < bytes.len()
694                            && bytes[i + 1].is_ascii_hexdigit()
695                            && bytes[i + 2].is_ascii_hexdigit(),
696                    )?;
697                }
698            }
699        }
700        _ => return Err(Error::Invalid),
701    }
702    Ok(did.to_owned())
703}
704
705fn validate_claims(
706    v: &Value,
707    code: &str,
708    c: &Commitment,
709    now: u64,
710    access: Option<&str>,
711) -> Result<()> {
712    // The pinned identifiers come from the commitment's client class, so a
713    // token minted for one class cannot be replayed against another.
714    let class = &c.client;
715    require(text(v, "iss")? == ISSUER)?;
716    require(v.get("aud").is_some_and(|a| {
717        a.as_str() == Some(class.aud.as_str()) || *a == serde_json::json!([class.aud.as_str()])
718    }))?;
719    // azp is the only signed client binding when the class's audience does
720    // not itself name the client: require it there. When aud == client_id
721    // (the staging www shape), the aud check above already pins the client
722    // and azp stays optional, exactly as before.
723    match v.get("azp") {
724        Some(azp) => require(azp.as_str() == Some(class.client_id.as_str()))?,
725        None => require(class.aud == class.client_id)?,
726    }
727    text(v, "sub")?;
728    atproto_account_did(v, &class.connector)?;
729    text(v, "jti")?;
730    let iat = number(v, "iat")?;
731    let exp = number(v, "exp")?;
732    times(iat, exp, now)?;
733    if v.get("nbf").is_some() {
734        let n = number(v, "nbf")?;
735        require(n <= now.saturating_add(30) && n <= exp)?;
736    }
737    match &c.flow {
738        Flow::Code { .. } => {
739            require(equal(text(v, "nonce")?.as_bytes(), c.nonce().as_bytes()))?;
740            hash_claim(text(v, "c_hash")?, code)?;
741        }
742        // W1b/D1: the device flow carries no nonce/c_hash binding. The
743        // issuer-signed `binding_key` claim (W5f) must be exactly the
744        // canonical base64url encoding of the committed holder Ed25519 key;
745        // the comparison target is canonical by construction, so any
746        // noncanonical or foreign key fails closed. This binds the signed
747        // token to the possession key exactly as `nonce` binds the code
748        // flow, and a code-flow token (no binding_key) fails here.
749        Flow::Device { .. } => {
750            require(text(v, "binding_key")? == B64.encode(c.ed))?;
751        }
752    }
753    if v.get("at_hash").is_some() {
754        let claim = text(v, "at_hash")?;
755        fixed::<16>(claim)?;
756        if let Some(access) = access {
757            hash_claim(claim, access)?;
758        }
759    }
760    Ok(())
761}
762
763/// Private fields, no Deserialize/Clone/Debug: not forgeable from a browser flag.
764pub(crate) struct Source {
765    subject: String,
766    atproto_did: String,
767    jti: String,
768    issued_at: u64,
769    expires_at: u64,
770    token_hash: [u8; 32],
771    code_hash: [u8; 32],
772    commitment: Commitment,
773}
774impl Source {
775    /// OIDC provenance paired with the independently verified ATProto DID.
776    /// The upstream `sub` is deliberately opaque and never becomes the
777    /// Hyprstream principal.
778    pub(crate) fn provenance(&self) -> (&str, &str) {
779        (ISSUER, &self.subject)
780    }
781
782    /// The nonce-committed proof keys must be pinned by Policy at prepare time.
783    /// Only a verified `Source` exposes this pair to the authenticated adapter.
784    #[allow(dead_code)] // Consumed by the B1b Policy adapter, not the disabled issuer.
785    pub(crate) fn proof_public_keys(&self) -> (&[u8; 32], &[u8]) {
786        (&self.commitment.ed, &self.commitment.pq)
787    }
788
789    /// The verified client class's exact `client_id`. This is authenticated
790    /// data: the verifier resolved the wire `client_id` to an accepted class
791    /// and the signed `aud`/`azp` claims were checked against that class
792    /// before this `Source` existed. Policy uses it as the per-client
793    /// grant/profile table selector (W1.2); it is never browser-chosen.
794    pub(crate) fn client_id(&self) -> &str {
795        self.commitment.client.client_id.as_str()
796    }
797
798    /// True when this source was verified through the W1b device flow: the
799    /// commitment binds `device_code` and the issuer-signed `binding_key`
800    /// claim — not a signed nonce — authenticated the holder key. Replay
801    /// admission must use only the nonce-free identity for such sources
802    /// (D2): their commitment nonce is client-controlled.
803    #[cfg(feature = "postgres")]
804    pub(crate) fn is_device_flow(&self) -> bool {
805        matches!(self.commitment.flow, Flow::Device { .. })
806    }
807
808    #[cfg(feature = "postgres")]
809    pub(crate) fn store_source(&self) -> hyprstream_session_store::Source {
810        hyprstream_session_store::Source {
811            issuer: ISSUER.into(),
812            subject: self.subject.clone(),
813            atproto_did: self.atproto_did.clone(),
814            jti: self.jti.clone(),
815            nonce: self.commitment.nonce(),
816            token_hash: self.token_hash,
817            issued_at: self.issued_at as i64,
818            expires_at: self.expires_at as i64,
819        }
820    }
821}
822/// Supplied only by a future Policy integration; this verifier does NOT authorize it.
823#[derive(Clone)]
824pub(crate) struct AuthorityBinding {
825    pub account: String,
826    pub subject: String,
827    pub tenant: String,
828    pub requested: String,
829    pub granted: String,
830    pub revision: String,
831}
832pub(crate) fn scopes(s: &str) -> Result<()> {
833    // Keep the browser and verifier scope grammar/limit identical. Scope
834    // tokens are printable ASCII separated by exactly one ASCII space.
835    require(!s.is_empty() && s.len() <= MAX_SCOPE_BYTES)?;
836    let mut previous = "";
837    for token in s.split(' ') {
838        require(
839            !token.is_empty()
840                && token
841                    .bytes()
842                    .all(|b| b == 0x21 || (0x23..=0x5b).contains(&b) || (0x5d..=0x7e).contains(&b))
843                && token > previous,
844        )?;
845        previous = token;
846    }
847    Ok(())
848}
849fn authority_text(s: &str) -> Result<()> {
850    require(
851        !s.is_empty()
852            && s.len() <= MAX_AUTHORITY_TEXT
853            && !s.bytes().any(|b| b <= 0x1f || b == 0x7f),
854    )
855}
856pub(crate) struct Challenge {
857    source: Source,
858    binding: AuthorityBinding,
859    id: [u8; 32],
860    created: u64,
861    expires: u64,
862    transcript: Vec<u8>,
863}
864impl Source {
865    pub(crate) fn challenge(
866        self,
867        binding: AuthorityBinding,
868        id: [u8; 32],
869        created: u64,
870    ) -> Result<Challenge> {
871        times(self.issued_at, self.expires_at, created)?;
872        for s in [
873            &binding.account,
874            &binding.subject,
875            &binding.tenant,
876            &binding.revision,
877        ] {
878            authority_text(s)?;
879        }
880        require(binding.tenant != "*")?;
881        scopes(&binding.requested)?;
882        scopes(&binding.granted)?;
883        require(
884            binding
885                .granted
886                .split(' ')
887                .all(|s| binding.requested.split(' ').any(|r| r == s)),
888        )?;
889        let expires = created
890            .saturating_add(60)
891            .min(self.expires_at)
892            .min(self.issued_at.saturating_add(120));
893        require(expires > created)?;
894        let kids = self.commitment.kids();
895        let transcript = frame(
896            "hyprstream.session-primary.possession.v1",
897            &[
898                self.commitment.host.as_str().as_bytes(),
899                self.commitment.host.token_endpoint().as_bytes(),
900                ISSUER.as_bytes(),
901                self.commitment.client.client_id.as_bytes(),
902                WEBSITE.as_bytes(),
903                &id,
904                &self.token_hash,
905                self.commitment.nonce().as_bytes(),
906                &self.code_hash,
907                &sha(&self.commitment.preimage()),
908                binding.account.as_bytes(),
909                binding.subject.as_bytes(),
910                binding.tenant.as_bytes(),
911                self.commitment.host.as_str().as_bytes(),
912                binding.requested.as_bytes(),
913                binding.granted.as_bytes(),
914                &created.to_be_bytes(),
915                &expires.to_be_bytes(),
916                SUITE.as_bytes(),
917                &kids[0],
918                &kids[1],
919                binding.revision.as_bytes(),
920            ],
921        );
922        // Match the A2 browser verifier's hard bound even if this encoding is
923        // extended later; never hand back a transcript that the browser will
924        // reject or truncate.
925        require(transcript.len() <= MAX_TRANSCRIPT)?;
926        Ok(Challenge {
927            source: self,
928            binding,
929            id,
930            created,
931            expires,
932            transcript,
933        })
934    }
935}
936/// Consuming a challenge prevents local reuse only. Durable replay is H1's job.
937pub(crate) struct VerifiedPossession {
938    source: Source,
939    binding: AuthorityBinding,
940    challenge_id: [u8; 32],
941    created_at: u64,
942    expires_at: u64,
943}
944impl Challenge {
945    pub(crate) fn transcript(&self) -> &[u8] {
946        &self.transcript
947    }
948    pub(crate) fn expires_at(&self) -> u64 {
949        self.expires
950    }
951    pub(crate) fn challenge_id(&self) -> [u8; 32] {
952        self.id
953    }
954    pub(crate) fn granted_scope(&self) -> &str {
955        &self.binding.granted
956    }
957    pub(crate) fn expected_session(&self) -> (AuthorityBinding, [u8; 32], Vec<u8>) {
958        (
959            self.binding.clone(),
960            self.source.commitment.ed,
961            self.source.commitment.pq.clone(),
962        )
963    }
964    pub(crate) fn verify(
965        self,
966        source: Source,
967        id: &[u8; 32],
968        ed_sig: &[u8],
969        pq_sig: &[u8],
970        now: u64,
971    ) -> Result<VerifiedPossession> {
972        require(
973            now >= self.created
974                && now < self.expires
975                && equal(id, &self.id)
976                && equal(&source.token_hash, &self.source.token_hash)
977                && equal(&source.code_hash, &self.source.code_hash)
978                && equal(
979                    &source.commitment.preimage(),
980                    &self.source.commitment.preimage(),
981                ),
982        )?;
983        times(source.issued_at, source.expires_at, now)?;
984        require(ed_sig.len() == 64 && pq_sig.len() == 3309)?;
985        let c = &source.commitment;
986        let vk = VerifyingKey::from_bytes(&c.ed).map_err(|_| Error::Invalid)?;
987        vk.verify_strict(
988            &self.transcript,
989            &Signature::from_slice(ed_sig).map_err(|_| Error::Invalid)?,
990        )
991        .map_err(|_| Error::Invalid)?;
992        ml_dsa_verify(
993            &ml_dsa_vk_from_bytes(&c.pq).map_err(|_| Error::Invalid)?,
994            &self.transcript,
995            pq_sig,
996        )
997        .map_err(|_| Error::Invalid)?;
998        Ok(VerifiedPossession {
999            source,
1000            binding: self.binding,
1001            challenge_id: self.id,
1002            created_at: self.created,
1003            expires_at: self.expires,
1004        })
1005    }
1006}
1007
1008impl VerifiedPossession {
1009    /// The verified client class's exact `client_id` (authenticated data —
1010    /// see [`Source::client_id`]). Used by the Policy adapter as the wire
1011    /// client selector for the per-client grant/profile table (W1.2).
1012    #[cfg(feature = "postgres")]
1013    pub(crate) fn client_id(&self) -> &str {
1014        self.source.commitment.client.client_id.as_str()
1015    }
1016
1017    /// Consumed only by the authenticated Policy admission adapter. The
1018    /// verified keys/source are never reconstructed from the exchange form.
1019    /// The trailing flag reports the W1b device flow so Policy replay
1020    /// admission can skip the nonce-bearing legacy key (D2/W1b).
1021    #[cfg(feature = "postgres")]
1022    pub(crate) fn into_admission_parts(
1023        self,
1024    ) -> (
1025        hyprstream_session_store::Source,
1026        [u8; 32],
1027        Vec<u8>,
1028        AuthorityBinding,
1029        [u8; 32],
1030        u64,
1031        u64,
1032        bool,
1033    ) {
1034        let device_flow = self.source.is_device_flow();
1035        let source = self.source.store_source();
1036        (
1037            source,
1038            self.source.commitment.ed,
1039            self.source.commitment.pq,
1040            self.binding,
1041            self.challenge_id,
1042            self.created_at,
1043            self.expires_at,
1044            device_flow,
1045        )
1046    }
1047}
1048
1049#[cfg(test)]
1050mod tests;