Skip to main content

hyprstream_rpc/
wasm_token_exchange.rs

1//! Browser-side RFC 8693 token-exchange (#1314) for the wasm client.
2//!
3//! The browser `VfsShell` exchanges an atproto/external JWT for a short-lived
4//! hyprstream at+jwt Bearer, then presents that Bearer as the default JWT on
5//! every RPC. This module holds:
6//!
7//! - **Pure helpers** (`exchange_form_body`, `parse_exchange_response`,
8//!   `subject_from_access_token`) — target-agnostic, unit-tested on native.
9//! - **`fetch_exchange_token`** — the browser `fetch` glue, `wasm32`-only (it
10//!   uses `web_sys`), mirroring `browser_provisioning::fetch_browser_provisioning`.
11//!
12//! # Authority note
13//!
14//! `subject_from_access_token` decodes the at+jwt `sub` **without** signature
15//! verification. This is client-side bookkeeping only: it derives a display
16//! `Subject` from the freshly-exchanged Bearer. The token's authority is never
17//! trusted from this decode — the server re-verifies the bearer on every RPC
18//! (`require_bearer_token` / `validate_oauth_access_token`). The exchange
19//! response does not echo `sub`, and the mint stamps `sub = verified.sub`
20//! (`token_exchange.rs`), so the client decodes it from the minted token rather
21//! than extending the server response.
22
23use anyhow::{anyhow, ensure, Result};
24use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
25use serde::{Deserialize, Serialize};
26
27/// The RFC 8693 token-exchange grant type.
28pub const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
29/// Issued-token type the #1314 endpoint always mints (at+jwt / access_token).
30pub const ISSUED_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
31
32/// The well-known public `client_id` the browser VfsShell presents at the
33/// RFC 8693 token-exchange endpoint (#1425).
34///
35/// This is a **public client** identifier (RFC 9700 / OAuth 2.1 `none`
36/// token-endpoint auth method): it names the browser client so the AS can
37/// apply the public-client token-exchange contract, but it is **not a client
38/// secret and not a proof of identity**. There is no corresponding secret —
39/// the sender binding comes entirely from the RFC 9449 DPoP proof
40/// (`cnf.jkt`), not from this identifier. The same constant is the
41/// single source of truth the AS matches against (`hyprstream` imports it
42/// from this crate) so the wire contract cannot drift between client and
43/// server.
44pub const BROWSER_PUBLIC_CLIENT_ID: &str = "hyprstream-browser-vfs";
45/// Browser session exchange route on the hyprstream OAuth origin.
46pub const SESSION_EXCHANGE_PATH: &str = "/api/session/exchange";
47/// Server-derived viewer context route on the hyprstream OAuth origin.
48pub const WHOAMI_PATH: &str = "/api/session/whoami";
49
50/// Server-derived browser viewer authority.
51#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
52#[serde(rename_all = "camelCase")]
53pub struct SessionContext {
54    pub did: Option<String>,
55    pub kind: SessionKind,
56    pub tenant: Option<String>,
57    pub can_act_locally: bool,
58}
59
60#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
61#[serde(rename_all = "lowercase")]
62pub enum SessionKind {
63    Local,
64    Federated,
65    Unauthenticated,
66}
67
68/// A successfully exchanged short-lived access token (#1314 / #1425).
69///
70/// `token_type` records whether the AS minted a sender-bound (`DPoP`,
71/// RFC 9449) or bearer (`Bearer`) token. A `DPoP` token carries `cnf.jkt`
72/// and **must** be presented as `Authorization: DPoP` with a fresh matching
73/// proof on every resource request — the resource server rejects a
74/// `cnf.jkt`-bound token presented as `Bearer` (RFC 9449 §7).
75///
76/// `Debug` is manual and redacts `access_token` so an accidental `{:?}` log
77/// can't leak the credential.
78#[derive(Clone, PartialEq, Eq)]
79pub struct ExchangedToken {
80    /// The at+jwt `access_token` — presented as the client's default JWT.
81    pub access_token: String,
82    /// Lifetime in seconds, as reported by the endpoint. Informational: Lane C
83    /// uses a static default-JWT; a refresh path (`withTokenProvider`) is the
84    /// future-work follow-on the recon notes.
85    pub expires_in: i64,
86    /// The OAuth `token_type` the AS returned — `"DPoP"` for a sender-bound
87    /// token (the #1425 browser contract), `"Bearer"` otherwise. Drives
88    /// whether downstream RPC requests must carry a DPoP proof.
89    pub token_type: TokenType,
90    /// The server-issued `DPoP-Nonce` from a successful response (#1425 r1
91    /// P1#4). The caller persists this and supplies it on the next exchange
92    /// / resource request to avoid a `use_dpop_nonce` round-trip. `None` when
93    /// the AS did not return a nonce (e.g. a non-DPoP response).
94    pub nonce: Option<String>,
95}
96
97/// The OAuth `token_type` of an [`ExchangedToken`].
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum TokenType {
100    /// `token_type: Bearer` — no key binding.
101    Bearer,
102    /// `token_type: DPoP` (RFC 9449) — sender-bound via `cnf.jkt`; every
103    /// resource request needs a matching DPoP proof.
104    Dpop,
105}
106
107impl TokenType {
108    /// Parse the `token_type` field, case-insensitively. `None` (field
109    /// omitted) is treated as `Bearer` for backward compatibility with the
110    /// pre-#1424 endpoint shape.
111    fn parse(raw: Option<&str>) -> Result<Self, String> {
112        match raw.map(str::to_ascii_lowercase).as_deref() {
113            None | Some("bearer") => Ok(TokenType::Bearer),
114            Some("dpop") => Ok(TokenType::Dpop),
115            Some(other) => Err(format!("unsupported token_type: {other}")),
116        }
117    }
118}
119
120impl std::fmt::Debug for ExchangedToken {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        f.debug_struct("ExchangedToken")
123            .field("access_token", &"<redacted>")
124            .field("expires_in", &self.expires_in)
125            .field("token_type", &self.token_type)
126            .finish()
127    }
128}
129
130#[derive(Deserialize)]
131struct ExchangeResponse {
132    access_token: String,
133    #[serde(default)]
134    expires_in: Option<i64>,
135    #[serde(default)]
136    token_type: Option<String>,
137    #[serde(default)]
138    issued_token_type: Option<String>,
139}
140
141/// Build the `application/x-www-form-urlencoded` body for an RFC 8693 exchange.
142///
143/// #1425: the body now carries the required **public** `client_id`
144/// ([`BROWSER_PUBLIC_CLIENT_ID`]) and is sent alongside a `DPoP` proof
145/// header for sender-bound exchange. #1425 r2 P2: the body also carries the
146/// RFC 8707 `resource` the caller is targeting — the browser always knows
147/// this (it is the same origin `fetch_exchange_token` is calling), so the
148/// contract is explicit rather than the server inferring a default. `grant_type`
149/// and the `subject_token_type` constant are URL-safe; `subject_token`,
150/// `client_id`, and `resource` are percent-encoded defensively.
151pub fn exchange_form_body(
152    subject_token: &str,
153    subject_token_type: &str,
154    client_id: &str,
155    resource: &str,
156) -> String {
157    format!(
158        "grant_type={GRANT_TYPE}\
159         &subject_token={}\
160         &subject_token_type={}\
161         &client_id={}\
162         &resource={}",
163        percent_encode(subject_token),
164        percent_encode(subject_token_type),
165        percent_encode(client_id),
166        percent_encode(resource),
167    )
168}
169
170/// Minimal RFC 3986 unreserved percent-encoding.
171fn percent_encode(input: &str) -> String {
172    let mut out = String::with_capacity(input.len());
173    for &byte in input.as_bytes() {
174        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
175            out.push(byte as char);
176        } else {
177            out.push_str(&format!("%{:02X}", byte));
178        }
179    }
180    out
181}
182
183/// Parse the JSON body of a successful `POST /oauth/token` exchange.
184///
185/// Validates `access_token` is present and, when the endpoint sets them, that
186/// `token_type` is a supported value (`Bearer` or, since #1425, `DPoP` for a
187/// sender-bound token) and `issued_token_type` is the access-token type —
188/// defending against a misrouted/shape-changed response being treated as a
189/// valid credential. The parsed [`TokenType`] tells the caller whether
190/// downstream resource requests must carry a DPoP proof.
191pub fn parse_exchange_response(body: &str) -> Result<ExchangedToken> {
192    let resp: ExchangeResponse = serde_json::from_str(body)
193        .map_err(|e| anyhow!("token-exchange response is not valid JSON: {e}"))?;
194    ensure!(
195        !resp.access_token.is_empty(),
196        "token-exchange response omitted access_token"
197    );
198    let token_type =
199        TokenType::parse(resp.token_type.as_deref()).map_err(|e| anyhow!("token-exchange {e}"))?;
200    if let Some(issued) = &resp.issued_token_type {
201        ensure!(
202            issued == ISSUED_TOKEN_TYPE,
203            "token-exchange issued_token_type unexpected: {issued}"
204        );
205    }
206    Ok(ExchangedToken {
207        access_token: resp.access_token,
208        expires_in: resp.expires_in.unwrap_or(0).max(0),
209        token_type,
210        nonce: None,
211    })
212}
213
214/// Verify an [`ExchangedToken`] is actually sender-bound to `dpop_pubkey`
215/// before the caller (the browser sender-bound exchange) trusts it (#1425 r2
216/// P2).
217///
218/// [`parse_exchange_response`] treats an omitted or `Bearer` `token_type` as
219/// backward-compatible (other, non-browser callers of this endpoint shape
220/// still expect that). But `fetch_exchange_token` is *exclusively* the
221/// sender-bound browser exchange: a response that comes back as `Bearer` (a
222/// misrouted request, a downgraded/compatibility responder, or a proxy that
223/// stripped the DPoP semantics) must be rejected here rather than silently
224/// installed as if it were correctly bound — the caller only checks
225/// `token_type` `once, at parse time`, and every downstream RPC assumes the
226/// installed credential really is `cnf.jkt`-bound to this key.
227///
228/// This also independently confirms the token's `cnf.jkt` (decoded from the
229/// unverified JWT payload — the server re-verifies the signature and binding
230/// on every RPC; this is client-side defense in depth, not the trust
231/// boundary) equals [`ed25519_dpop_jkt`] of the exact key that produced the
232/// proof, so a compatibility/misrouted response bound to some *other* key
233/// cannot be mistaken for a token this browser can actually use.
234pub fn verify_sender_bound_token(token: &ExchangedToken, dpop_pubkey: &[u8; 32]) -> Result<()> {
235    ensure!(
236        token.token_type == TokenType::Dpop,
237        "sender-bound browser exchange requires token_type: DPoP; got Bearer or an omitted token_type"
238    );
239    let claims = crate::auth::decode_unverified(&token.access_token)
240        .map_err(|e| anyhow!("exchanged access_token is not a decodable JWT: {e}"))?;
241    let actual_jkt = claims
242        .cnf_jkt()
243        .ok_or_else(|| anyhow!("exchanged token carries no cnf.jkt; sender binding is missing"))?;
244    let expected_jkt = ed25519_dpop_jkt(dpop_pubkey);
245    ensure!(
246        actual_jkt == expected_jkt,
247        "exchanged token cnf.jkt does not match the browser DPoP key"
248    );
249    Ok(())
250}
251
252/// Parse the exact session-exchange / whoami JSON response.
253pub fn parse_session_context(body: &str) -> Result<SessionContext> {
254    let context: SessionContext = serde_json::from_str(body)
255        .map_err(|e| anyhow!("session context response is not valid JSON: {e}"))?;
256    let valid = match context.kind {
257        SessionKind::Local => {
258            context.did.as_deref().is_some_and(|did| !did.is_empty())
259                && context
260                    .tenant
261                    .as_deref()
262                    .is_some_and(|tenant| !tenant.is_empty())
263                && context.can_act_locally
264        }
265        SessionKind::Federated => {
266            context.did.as_deref().is_some_and(|did| !did.is_empty())
267                && context.tenant.is_none()
268                && !context.can_act_locally
269        }
270        SessionKind::Unauthenticated => {
271            context.did.is_none() && context.tenant.is_none() && !context.can_act_locally
272        }
273    };
274    ensure!(
275        valid,
276        "session context contains inconsistent viewer authority"
277    );
278    Ok(context)
279}
280
281/// Decode the `sub` claim from an exchanged at+jwt and build a `Subject`.
282///
283/// No signature verification (see the module authority note). Returns an error
284/// if the token is not a decodable JWT or has no `sub`.
285pub fn subject_from_access_token(token: &str) -> Result<crate::Subject> {
286    let claims = crate::auth::decode_unverified(token)
287        .map_err(|e| anyhow!("access_token is not a decodable JWT: {e}"))?;
288    ensure!(!claims.sub.is_empty(), "access_token has no sub claim");
289    Ok(crate::Subject::new(claims.sub))
290}
291
292// ============================================================================
293// DPoP proof helpers (RFC 9449) — pure, native-testable (#1425 r1 P1 #3/#4)
294// ============================================================================
295
296/// Build the RFC 9449 DPoP JWT signing input (`header.payload`) for an
297/// Ed25519 key. The caller signs `signing_input` with the private key and
298/// assembles the proof via [`assemble_dpop_proof`].
299///
300/// Pure / native-testable: the wasm32 glue calls this, invokes the JS sign
301/// callback, and assembles. Keeping the construction here means the htm/htu/
302/// iat/jti/ath/nonce/alg/jwk shape is tested once, natively, rather than
303/// only through wasm32-only glue.
304pub fn ed25519_dpop_signing_input(
305    pubkey: &[u8; 32],
306    htm: &str,
307    htu: &str,
308    iat: i64,
309    jti: &str,
310    ath: Option<&str>,
311    nonce: Option<&str>,
312) -> Result<(String, String)> {
313    let x = URL_SAFE_NO_PAD.encode(pubkey);
314    let header = serde_json::json!({
315        "typ": "dpop+jwt",
316        "alg": "EdDSA",
317        "jwk": {"kty": "OKP", "crv": "Ed25519", "x": x}
318    });
319    let mut payload = serde_json::json!({
320        "jti": jti,
321        "htm": htm,
322        "htu": htu,
323        "iat": iat,
324    });
325    if let Some(ath) = ath {
326        payload["ath"] = serde_json::Value::String(ath.to_owned());
327    }
328    if let Some(nonce) = nonce {
329        payload["nonce"] = serde_json::Value::String(nonce.to_owned());
330    }
331    let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header)?);
332    let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload)?);
333    let signing_input = format!("{header_b64}.{payload_b64}");
334    Ok((signing_input, header_b64))
335}
336
337/// Assemble a complete DPoP proof JWT from the signing input and signature.
338pub fn assemble_dpop_proof(signing_input: &str, signature: &[u8]) -> String {
339    format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(signature))
340}
341
342/// Compute the RFC 7638 JWK thumbprint (`cnf.jkt`) for an Ed25519 public key.
343pub fn ed25519_dpop_jkt(pubkey: &[u8; 32]) -> String {
344    crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Ed25519 { x: pubkey })
345}
346
347/// Check whether an HTTP error response body is a `use_dpop_nonce` error
348/// (RFC 9449 §8). The browser retries with a fresh proof carrying the
349/// `DPoP-Nonce` response header.
350pub fn is_use_dpop_nonce_response(status: u16, body: &str) -> bool {
351    status == 400
352        && serde_json::from_str::<serde_json::Value>(body)
353            .ok()
354            .and_then(|v| {
355                v.get("error")
356                    .and_then(serde_json::Value::as_str)
357                    .map(|s| s == "use_dpop_nonce")
358            })
359            .unwrap_or(false)
360}
361
362/// Compute the DPoP `ath` value: `base64url(SHA-256(access_token))`.
363pub fn dpop_ath(access_token: &str) -> String {
364    use sha2::{Digest, Sha256};
365    URL_SAFE_NO_PAD.encode(Sha256::digest(access_token.as_bytes()))
366}
367
368/// Generate a fresh, random DPoP `jti` (RFC 9449 requires a unique value per
369/// proof so the AS can detect replay). Pure / native-testable so JTI
370/// freshness is a plain unit test rather than something only exercisable
371/// inside the `wasm32`-only fetch glue (#1425 r1 P1#4).
372pub fn generate_dpop_jti() -> String {
373    use rand::RngCore as _;
374    let mut jti_bytes = [0u8; 16];
375    rand::rngs::OsRng.fill_bytes(&mut jti_bytes);
376    URL_SAFE_NO_PAD.encode(jti_bytes)
377}
378
379/// Outcome of one token-exchange fetch attempt, decided from the response's
380/// status/body/headers (RFC 9449 §8 nonce lifecycle). Pure / native-testable:
381/// the `wasm32` glue calls this after every `fetch` to decide whether to
382/// return, retry with a fresh nonce, or fail (#1425 r1 P1#4).
383#[derive(Debug, Clone, PartialEq, Eq)]
384pub enum NonceOutcome {
385    /// The request succeeded; the caller should parse the body.
386    Success,
387    /// The AS requires a server nonce; retry once with this fresh value.
388    RetryWithNonce(String),
389    /// The AS requires a nonce but returned no `DPoP-Nonce` header to retry
390    /// with, or the retry budget (one retry) is exhausted.
391    Failed,
392}
393
394/// Decide the next action for a token-exchange fetch attempt.
395///
396/// `attempt` is 0 for the bootstrap request, 1 for the nonce retry. Only a
397/// bootstrap attempt (`attempt == 0`) may be retried; a failure on attempt 1
398/// is always [`NonceOutcome::Failed`] (RFC 9449 §8 bounds the retry to one
399/// round-trip so a malicious/misbehaving AS cannot force an infinite loop).
400pub fn decide_nonce_outcome(
401    attempt: u8,
402    response_ok: bool,
403    status: u16,
404    body: &str,
405    fresh_nonce_header: Option<&str>,
406) -> NonceOutcome {
407    if response_ok {
408        return NonceOutcome::Success;
409    }
410    if attempt == 0 && is_use_dpop_nonce_response(status, body) {
411        if let Some(fresh) = fresh_nonce_header {
412            return NonceOutcome::RetryWithNonce(fresh.to_owned());
413        }
414    }
415    NonceOutcome::Failed
416}
417
418// ============================================================================
419// Browser fetch glue (wasm32 only)
420// ============================================================================
421
422#[cfg(target_arch = "wasm32")]
423mod fetch {
424    use super::{
425        assemble_dpop_proof, decide_nonce_outcome, ed25519_dpop_signing_input, exchange_form_body,
426        generate_dpop_jti, parse_exchange_response, parse_session_context, percent_encode,
427        verify_sender_bound_token, ExchangedToken, NonceOutcome, SessionContext,
428        BROWSER_PUBLIC_CLIENT_ID, SESSION_EXCHANGE_PATH, WHOAMI_PATH,
429    };
430    use anyhow::{anyhow, ensure, Context, Result};
431    use wasm_bindgen::JsCast as _;
432    use wasm_bindgen_futures::JsFuture;
433
434    /// Cap on a token-exchange response body. An OAuth token response is a few
435    /// hundred bytes; anything larger signals a misconfigured/compromised
436    /// endpoint trying to exhaust the browser tab (mirrors the spirit of
437    /// `browser_provisioning::MAX_PROVISIONING_BYTES`).
438    const MAX_EXCHANGE_RESPONSE_BYTES: usize = 64 * 1024;
439
440    /// Validate `endpoint` is an absolute, credential-free HTTPS origin.
441    fn parse_origin(endpoint: &str) -> Result<url::Url> {
442        let parsed = url::Url::parse(endpoint).context("invalid exchange endpoint")?;
443        ensure!(
444            parsed.scheme() == "https"
445                && parsed.host_str().is_some()
446                && parsed.username().is_empty()
447                && parsed.password().is_none()
448                && parsed.fragment().is_none()
449                && (parsed.path().is_empty() || parsed.path() == "/")
450                && parsed.query().is_none(),
451            "exchange endpoint must be an absolute credential-free HTTPS origin (no path/query)"
452        );
453        Ok(parsed)
454    }
455
456    /// Read a `Response` body fully into a UTF-8 string via its stream reader.
457    ///
458    /// Mirrors `browser_provisioning::fetch_browser_provisioning`'s reader loop
459    /// (no `content-length` dependency).
460    async fn read_body_text(response: &web_sys::Response) -> Result<String> {
461        let body = response
462            .body()
463            .ok_or_else(|| anyhow!("token-exchange response omitted its body"))?;
464        let reader: web_sys::ReadableStreamDefaultReader = body.get_reader().unchecked_into();
465        let mut bytes = Vec::new();
466        loop {
467            let result = JsFuture::from(reader.read())
468                .await
469                .map_err(|e| anyhow!("token-exchange response read failed: {e:?}"))?;
470            let done = js_sys::Reflect::get(&result, &wasm_bindgen::JsValue::from_str("done"))
471                .map_err(|_| anyhow!("token-exchange chunk omitted done"))?
472                .as_bool()
473                .ok_or_else(|| anyhow!("token-exchange chunk had invalid done"))?;
474            if done {
475                break;
476            }
477            let value = js_sys::Reflect::get(&result, &wasm_bindgen::JsValue::from_str("value"))
478                .map_err(|_| anyhow!("token-exchange chunk omitted value"))?;
479            let chunk: js_sys::Uint8Array = value
480                .dyn_into()
481                .map_err(|_| anyhow!("token-exchange chunk was not a Uint8Array"))?;
482            let chunk_bytes = chunk.to_vec();
483            if bytes.len().saturating_add(chunk_bytes.len()) > MAX_EXCHANGE_RESPONSE_BYTES {
484                return Err(anyhow!(
485                    "token-exchange response exceeds {MAX_EXCHANGE_RESPONSE_BYTES} bytes"
486                ));
487            }
488            bytes.extend_from_slice(&chunk_bytes);
489        }
490        String::from_utf8(bytes).context("token-exchange response was not valid UTF-8")
491    }
492
493    /// Build and sign an Ed25519 DPoP proof by calling the browser's sign
494    /// callback (`dpop_sign_fn`). The callback receives the JWT signing input
495    /// bytes and returns a 64-byte Ed25519 signature.
496    async fn build_ed25519_dpop_proof(
497        pubkey: &[u8; 32],
498        sign_fn: &js_sys::Function,
499        htm: &str,
500        htu: &str,
501        ath: Option<&str>,
502        nonce: Option<&str>,
503    ) -> Result<String> {
504        let iat = chrono::Utc::now().timestamp();
505        let jti = generate_dpop_jti();
506        let (signing_input, _) =
507            ed25519_dpop_signing_input(pubkey, htm, htu, iat, &jti, ath, nonce)?;
508        // Call the JS sign callback: sign_fn(Uint8Array) → Promise<Uint8Array(64)>.
509        let input_array = js_sys::Uint8Array::from(signing_input.as_bytes());
510        let result = sign_fn
511            .call1(&wasm_bindgen::JsValue::UNDEFINED, &input_array)
512            .map_err(|e| anyhow!("DPoP sign callback invocation failed: {e:?}"))?;
513        let promise: js_sys::Promise = result
514            .dyn_into()
515            .map_err(|_| anyhow!("DPoP sign callback did not return a Promise"))?;
516        let signature_value = JsFuture::from(promise)
517            .await
518            .map_err(|e| anyhow!("DPoP sign callback failed: {e:?}"))?;
519        let signature_array: js_sys::Uint8Array = signature_value
520            .dyn_into()
521            .map_err(|_| anyhow!("DPoP sign callback returned non-Uint8Array"))?;
522        Ok(assemble_dpop_proof(
523            &signing_input,
524            &signature_array.to_vec(),
525        ))
526    }
527
528    /// POST an RFC 8693 token-exchange grant to `{exchange_endpoint}/oauth/token`
529    /// and return the short-lived at+jwt access token.
530    ///
531    /// #1425 r1 P1#3/#4: the request carries the required public `client_id`
532    /// ([`BROWSER_PUBLIC_CLIENT_ID`]) and a DPoP proof header generated from
533    /// the browser-held Ed25519 key (`dpop_pubkey` + `dpop_sign_fn`). The AS
534    /// mints a **sender-bound** (`token_type: DPoP`, `cnf.jkt`) token bound to
535    /// this key.
536    ///
537    /// **Nonce lifecycle (RFC 9449 §8):** `nonce` is the server-issued nonce
538    /// from a previous successful response (persisted by the caller). On a
539    /// `use_dpop_nonce` error, this function extracts the fresh `DPoP-Nonce`
540    /// response header, generates a new proof carrying it, and retries once.
541    /// On success, the response's `DPoP-Nonce` is returned in
542    /// [`ExchangedToken::nonce`] for the caller to persist.
543    ///
544    /// Every downstream resource request presenting the returned token must
545    /// carry a fresh DPoP proof (with `ath`) from the same key — the resource
546    /// server rejects a `cnf.jkt`-bound token presented as Bearer (RFC 9449 §7).
547    pub async fn fetch_exchange_token(
548        exchange_endpoint: &str,
549        subject_token: &str,
550        subject_token_type: &str,
551        dpop_pubkey: &[u8; 32],
552        dpop_sign_fn: &js_sys::Function,
553        nonce: Option<&str>,
554    ) -> Result<ExchangedToken> {
555        let mut url = parse_origin(exchange_endpoint)?;
556        // #1425 r2 P2: the canonical resource is this exact origin, no
557        // trailing slash — computed from the validated input string (not the
558        // re-serialized `url::Url`, which normalizes an empty path to `/` and
559        // would otherwise silently drift from the server's
560        // `canonical_issuer_origin` no-trailing-slash form).
561        let resource = exchange_endpoint.trim_end_matches('/');
562        url.set_path("/oauth/token");
563        let token_endpoint_htu = url.as_str().to_owned();
564        let body = exchange_form_body(
565            subject_token,
566            subject_token_type,
567            BROWSER_PUBLIC_CLIENT_ID,
568            resource,
569        );
570
571        let mut current_nonce = nonce.map(str::to_owned);
572
573        // Up to two attempts: bootstrap → use_dpop_nonce retry.
574        for attempt in 0..2u8 {
575            let proof = build_ed25519_dpop_proof(
576                dpop_pubkey,
577                dpop_sign_fn,
578                "POST",
579                &token_endpoint_htu,
580                None, // no ath at the token endpoint
581                current_nonce.as_deref(),
582            )
583            .await?;
584
585            let headers = web_sys::Headers::new()
586                .map_err(|e| anyhow!("token-exchange header construction failed: {e:?}"))?;
587            headers
588                .set("content-type", "application/x-www-form-urlencoded")
589                .map_err(|e| anyhow!("token-exchange content-type set failed: {e:?}"))?;
590            headers
591                .set("accept", "application/json")
592                .map_err(|e| anyhow!("token-exchange accept set failed: {e:?}"))?;
593            headers
594                .set("dpop", &proof)
595                .map_err(|e| anyhow!("token-exchange DPoP header set failed: {e:?}"))?;
596
597            let init = web_sys::RequestInit::new();
598            init.set_method("POST");
599            init.set_body(&js_sys::JsString::from(body.as_str()));
600            init.set_headers(headers.as_ref());
601            init.set_cache(web_sys::RequestCache::NoStore);
602            init.set_credentials(web_sys::RequestCredentials::SameOrigin);
603            init.set_redirect(web_sys::RequestRedirect::Error);
604
605            let request = web_sys::Request::new_with_str_and_init(url.as_str(), &init)
606                .map_err(|e| anyhow!("token-exchange request construction failed: {e:?}"))?;
607            let window = web_sys::window().ok_or_else(|| anyhow!("browser window unavailable"))?;
608            let response_value = JsFuture::from(window.fetch_with_request(&request))
609                .await
610                .map_err(|e| anyhow!("token-exchange fetch failed: {e:?}"))?;
611            let response: web_sys::Response = response_value
612                .dyn_into()
613                .map_err(|_| anyhow!("token-exchange fetch returned a non-Response"))?;
614
615            let text = read_body_text(&response).await?;
616            let status = response.status();
617            let response_ok = response.ok();
618            let fresh_nonce_header = response.headers().get("DPoP-Nonce").ok().flatten();
619
620            // RFC 9449 §8 nonce lifecycle, decided by the same pure function
621            // the native tests exercise directly (#1425 r1 P1#4).
622            match decide_nonce_outcome(
623                attempt,
624                response_ok,
625                status,
626                &text,
627                fresh_nonce_header.as_deref(),
628            ) {
629                NonceOutcome::Success => {}
630                NonceOutcome::RetryWithNonce(fresh) => {
631                    current_nonce = Some(fresh);
632                    continue;
633                }
634                NonceOutcome::Failed => {
635                    return Err(anyhow!(
636                        "token-exchange endpoint returned HTTP {status}: {}",
637                        text.trim()
638                    ));
639                }
640            }
641
642            // Success: parse body + carry the response nonce for the caller to persist.
643            let mut token = parse_exchange_response(&text)?;
644            token.nonce = fresh_nonce_header;
645            // #1425 r2 P2: fail closed rather than installing a misrouted or
646            // compatibility (Bearer / foreign-key) response as if it were
647            // this browser's sender-bound credential.
648            verify_sender_bound_token(&token, dpop_pubkey)?;
649            return Ok(token);
650        }
651        Err(anyhow!(
652            "token-exchange: exhausted nonce retries (this should not happen)"
653        ))
654    }
655
656    /// Exchange a one-use ATProto service-auth JWT plus DPoP proof for the
657    /// opaque HttpOnly hyprstream browser session cookie.
658    pub async fn fetch_session_exchange(
659        exchange_endpoint: &str,
660        service_auth_jwt: &str,
661        dpop_proof: &str,
662    ) -> Result<SessionContext> {
663        let mut url = parse_origin(exchange_endpoint)?;
664        url.set_path(SESSION_EXCHANGE_PATH);
665
666        let headers = web_sys::Headers::new()
667            .map_err(|e| anyhow!("session-exchange header construction failed: {e:?}"))?;
668        headers
669            .set("authorization", &format!("Bearer {service_auth_jwt}"))
670            .map_err(|e| anyhow!("session-exchange authorization set failed: {e:?}"))?;
671        headers
672            .set("dpop", dpop_proof)
673            .map_err(|e| anyhow!("session-exchange DPoP set failed: {e:?}"))?;
674        headers
675            .set("accept", "application/json")
676            .map_err(|e| anyhow!("session-exchange accept set failed: {e:?}"))?;
677
678        let init = web_sys::RequestInit::new();
679        init.set_method("POST");
680        init.set_headers(headers.as_ref());
681        init.set_cache(web_sys::RequestCache::NoStore);
682        init.set_credentials(web_sys::RequestCredentials::Include);
683        init.set_redirect(web_sys::RequestRedirect::Error);
684
685        let request = web_sys::Request::new_with_str_and_init(url.as_str(), &init)
686            .map_err(|e| anyhow!("session-exchange request construction failed: {e:?}"))?;
687        session_context_fetch(request, "session-exchange").await
688    }
689
690    /// Fetch the current viewer authority using the opaque session cookie.
691    pub async fn fetch_session_context(exchange_endpoint: &str) -> Result<SessionContext> {
692        let mut url = parse_origin(exchange_endpoint)?;
693        url.set_path(WHOAMI_PATH);
694
695        let headers = web_sys::Headers::new()
696            .map_err(|e| anyhow!("whoami header construction failed: {e:?}"))?;
697        headers
698            .set("accept", "application/json")
699            .map_err(|e| anyhow!("whoami accept set failed: {e:?}"))?;
700        let init = web_sys::RequestInit::new();
701        init.set_method("GET");
702        init.set_headers(headers.as_ref());
703        init.set_cache(web_sys::RequestCache::NoStore);
704        init.set_credentials(web_sys::RequestCredentials::Include);
705        init.set_redirect(web_sys::RequestRedirect::Error);
706
707        let request = web_sys::Request::new_with_str_and_init(url.as_str(), &init)
708            .map_err(|e| anyhow!("whoami request construction failed: {e:?}"))?;
709        session_context_fetch(request, "whoami").await
710    }
711
712    async fn session_context_fetch(
713        request: web_sys::Request,
714        operation: &str,
715    ) -> Result<SessionContext> {
716        let window = web_sys::window().ok_or_else(|| anyhow!("browser window unavailable"))?;
717        let response_value = JsFuture::from(window.fetch_with_request(&request))
718            .await
719            .map_err(|e| anyhow!("{operation} fetch failed: {e:?}"))?;
720        let response: web_sys::Response = response_value
721            .dyn_into()
722            .map_err(|_| anyhow!("{operation} fetch returned a non-Response"))?;
723        let text = read_body_text(&response).await?;
724        if !response.ok() {
725            return Err(anyhow!(
726                "{operation} endpoint returned HTTP {}: {}",
727                response.status(),
728                text.trim()
729            ));
730        }
731        parse_session_context(&text)
732    }
733
734    /// Revoke an access token (RFC 7009, `POST {exchange_endpoint}/oauth/revoke`).
735    ///
736    /// Per RFC 7009 §2.2 the server always responds 200 whether or not the
737    /// token was valid, so the only error this returns is a transport
738    /// failure — the caller cannot distinguish "revoked" from
739    /// "server unreachable" from the response alone. `BrowserSession::revoke`
740    /// treats the session as unusable locally regardless of this outcome: a
741    /// client that cannot confirm revocation must not keep trusting the
742    /// token it just tried to kill.
743    pub async fn revoke_access_token(exchange_endpoint: &str, access_token: &str) -> Result<()> {
744        let mut url = parse_origin(exchange_endpoint)?;
745        url.set_path("/oauth/revoke");
746
747        let body = format!(
748            "token={}&token_type_hint=access_token",
749            percent_encode(access_token)
750        );
751
752        let headers = web_sys::Headers::new()
753            .map_err(|e| anyhow!("revoke header construction failed: {e:?}"))?;
754        headers
755            .set("content-type", "application/x-www-form-urlencoded")
756            .map_err(|e| anyhow!("revoke content-type set failed: {e:?}"))?;
757
758        let init = web_sys::RequestInit::new();
759        init.set_method("POST");
760        init.set_body(&js_sys::JsString::from(body.as_str()));
761        init.set_headers(headers.as_ref());
762        init.set_cache(web_sys::RequestCache::NoStore);
763        init.set_credentials(web_sys::RequestCredentials::SameOrigin);
764        init.set_redirect(web_sys::RequestRedirect::Error);
765
766        let request = web_sys::Request::new_with_str_and_init(url.as_str(), &init)
767            .map_err(|e| anyhow!("revoke request construction failed: {e:?}"))?;
768        let window = web_sys::window().ok_or_else(|| anyhow!("browser window unavailable"))?;
769        let response_value = JsFuture::from(window.fetch_with_request(&request))
770            .await
771            .map_err(|e| anyhow!("revoke fetch failed: {e:?}"))?;
772        let response: web_sys::Response = response_value
773            .dyn_into()
774            .map_err(|_| anyhow!("revoke fetch returned a non-Response"))?;
775        if !response.ok() {
776            return Err(anyhow!(
777                "revoke endpoint returned HTTP {}",
778                response.status()
779            ));
780        }
781        Ok(())
782    }
783}
784
785#[cfg(target_arch = "wasm32")]
786pub use fetch::{
787    fetch_exchange_token, fetch_session_context, fetch_session_exchange, revoke_access_token,
788};
789
790// ============================================================================
791// BrowserSession support — pure, native-testable
792// ============================================================================
793
794/// Classify a `fetch_exchange_token` (or `verify_sender_bound_token`) failure
795/// message into a stable error code for `hyprstream-rpc-std::browser_session`.
796///
797/// Every input reaches this function only because the exchange already
798/// failed (`Err`) — this is a labeling convenience on top of an already
799/// fail-closed exchange, not a gate that could itself fail open. An
800/// unrecognized message shape still classifies (as `"transport_error"`); it
801/// is never treated as success.
802///
803/// Classification is substring matching against the exact message shapes
804/// those functions produce today — covered by unit tests below against
805/// literal message strings so a wording change upstream is caught rather
806/// than silently misclassified.
807pub fn classify_exchange_error_code(message: &str) -> &'static str {
808    if message.contains("\"invalid_dpop_proof\"") {
809        "invalid_dpop_proof"
810    } else if message.contains("already used") {
811        "replay"
812    } else if message.contains("cnf.jkt does not match")
813        || message.contains("sender binding is missing")
814    {
815        "dpop_key_mismatch"
816    } else if message.contains("requires token_type: DPoP") {
817        "sender_binding_missing"
818    } else if message.contains("HTTP 401") {
819        "expired_or_revoked_subject"
820    } else if message.contains("HTTP 400") {
821        "invalid_request"
822    } else {
823        "transport_error"
824    }
825}
826
827/// Compute the absolute expiry (`Date.now()`-domain milliseconds) for a
828/// token whose `expires_in` (seconds, RFC 6749 §5.1) is `expires_in_secs`
829/// relative to `now_ms`. A non-positive `expires_in` clamps to `now_ms`
830/// (already expired) rather than underflowing.
831pub fn expires_at_ms(now_ms: f64, expires_in_secs: i64) -> f64 {
832    now_ms + (expires_in_secs.max(0) as f64) * 1000.0
833}
834
835#[cfg(test)]
836#[allow(clippy::unwrap_used, clippy::expect_used)]
837mod tests {
838    use super::*;
839
840    fn jwt(payload_json: &str) -> String {
841        let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"EdDSA","typ":"at+jwt"}"#);
842        let payload = URL_SAFE_NO_PAD.encode(payload_json);
843        format!("{header}.{payload}.c2ln")
844    }
845
846    #[test]
847    fn form_body_round_trips_safe_constants() {
848        // `:` is not RFC 3986 unreserved, so the caller-supplied URN is encoded;
849        // the server's form parser decodes %3A back to ':'. A valid JWT
850        // (base64url-no-pad + '.') is already unreserved, so it passes through.
851        // #1425: the body also carries the public client_id. #1425 r2 P2: and
852        // the canonical resource the browser is targeting.
853        let body = exchange_form_body(
854            "abc.def.ghi",
855            "urn:ietf:params:oauth:token-type:jwt",
856            BROWSER_PUBLIC_CLIENT_ID,
857            "https://as.example",
858        );
859        assert_eq!(
860            body,
861            "grant_type=urn:ietf:params:oauth:grant-type:token-exchange\
862             &subject_token=abc.def.ghi\
863             &subject_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Ajwt\
864             &client_id=hyprstream-browser-vfs\
865             &resource=https%3A%2F%2Fas.example"
866        );
867    }
868
869    #[test]
870    fn form_body_percent_encodes_non_unreserved() {
871        // base64url-no-pad never produces '+', but a tampered/odd token could carry it.
872        let body = exchange_form_body("a+b c", "t/y", "c w", "r s");
873        assert!(body.contains("subject_token=a%2Bb%20c"), "{body}");
874        assert!(body.contains("subject_token_type=t%2Fy"), "{body}");
875        assert!(body.contains("client_id=c%20w"), "{body}");
876        assert!(body.contains("resource=r%20s"), "{body}");
877    }
878
879    // ── #1425 r2 P2: sender-bound response verification ───────────────────────
880
881    fn dpop_bound_token(pubkey: &[u8; 32], token_type: TokenType) -> ExchangedToken {
882        let jkt = ed25519_dpop_jkt(pubkey);
883        let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"EdDSA","typ":"at+jwt"}"#);
884        let payload = URL_SAFE_NO_PAD.encode(format!(
885            r#"{{"sub":"alice","exp":9999999999,"iat":1,"cnf":{{"jkt":"{jkt}"}}}}"#
886        ));
887        ExchangedToken {
888            access_token: format!("{header}.{payload}.sig"),
889            expires_in: 300,
890            token_type,
891            nonce: None,
892        }
893    }
894
895    #[test]
896    fn verify_sender_bound_token_accepts_matching_dpop_token() {
897        let pubkey = [0x71; 32];
898        let token = dpop_bound_token(&pubkey, TokenType::Dpop);
899        verify_sender_bound_token(&token, &pubkey).expect("matching DPoP token must be accepted");
900    }
901
902    #[test]
903    fn verify_sender_bound_token_rejects_bearer() {
904        let pubkey = [0x72; 32];
905        let token = dpop_bound_token(&pubkey, TokenType::Bearer);
906        let err = verify_sender_bound_token(&token, &pubkey)
907            .expect_err("a Bearer response must be rejected by the sender-bound fetch");
908        assert!(
909            err.to_string().contains("DPoP"),
910            "unexpected error: {err:#}"
911        );
912    }
913
914    #[test]
915    fn verify_sender_bound_token_rejects_foreign_key_binding() {
916        let pubkey = [0x73; 32];
917        let attacker_pubkey = [0x74; 32];
918        // Bound to a DIFFERENT key than the one that produced the proof.
919        let token = dpop_bound_token(&attacker_pubkey, TokenType::Dpop);
920        let err = verify_sender_bound_token(&token, &pubkey)
921            .expect_err("a token bound to a foreign key must be rejected");
922        assert!(
923            err.to_string().contains("cnf.jkt"),
924            "unexpected error: {err:#}"
925        );
926    }
927
928    #[test]
929    fn verify_sender_bound_token_rejects_missing_cnf() {
930        let pubkey = [0x75; 32];
931        let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"EdDSA","typ":"at+jwt"}"#);
932        let payload = URL_SAFE_NO_PAD.encode(r#"{"sub":"alice","exp":9999999999,"iat":1}"#);
933        let token = ExchangedToken {
934            access_token: format!("{header}.{payload}.sig"),
935            expires_in: 300,
936            token_type: TokenType::Dpop,
937            nonce: None,
938        };
939        let err = verify_sender_bound_token(&token, &pubkey)
940            .expect_err("a token with no cnf.jkt at all must be rejected");
941        assert!(
942            err.to_string().contains("cnf.jkt"),
943            "unexpected error: {err:#}"
944        );
945    }
946
947    #[test]
948    fn browser_public_client_id_is_stable() {
949        // The AS matches this literal; a drift here breaks the wire contract.
950        assert_eq!(BROWSER_PUBLIC_CLIENT_ID, "hyprstream-browser-vfs");
951        assert!(!BROWSER_PUBLIC_CLIENT_ID.is_empty());
952    }
953
954    // ── #1425 r1: pure DPoP proof helpers (RFC 9449) ──────────────────────────
955
956    #[test]
957    fn ed25519_dpop_signing_input_has_correct_shape() {
958        let pubkey = [0x42; 32];
959        let (signing_input, _header) = ed25519_dpop_signing_input(
960            &pubkey,
961            "POST",
962            "https://as.example/oauth/token",
963            1700000000,
964            "jti-1",
965            None,
966            None,
967        )
968        .unwrap();
969        // Two dots → three segments (header.payload.???).
970        assert_eq!(signing_input.matches('.').count(), 1);
971        let (h, p) = signing_input.split_once('.').unwrap();
972        let header: serde_json::Value =
973            serde_json::from_slice(&URL_SAFE_NO_PAD.decode(h).unwrap()).unwrap();
974        let payload: serde_json::Value =
975            serde_json::from_slice(&URL_SAFE_NO_PAD.decode(p).unwrap()).unwrap();
976        assert_eq!(header["typ"], "dpop+jwt");
977        assert_eq!(header["alg"], "EdDSA");
978        assert_eq!(header["jwk"]["kty"], "OKP");
979        assert_eq!(header["jwk"]["crv"], "Ed25519");
980        assert_eq!(payload["htm"], "POST");
981        assert_eq!(payload["htu"], "https://as.example/oauth/token");
982        assert_eq!(payload["iat"], 1700000000);
983        assert_eq!(payload["jti"], "jti-1");
984        assert!(
985            payload.get("ath").is_none(),
986            "ath must be absent when not provided"
987        );
988        assert!(
989            payload.get("nonce").is_none(),
990            "nonce must be absent when not provided"
991        );
992    }
993
994    #[test]
995    fn ed25519_dpop_signing_input_includes_ath_and_nonce() {
996        let pubkey = [0x11; 32];
997        let (signing_input, _) = ed25519_dpop_signing_input(
998            &pubkey,
999            "GET",
1000            "https://rpc.example/v1/models",
1001            1,
1002            "j",
1003            Some("ath-hash"),
1004            Some("nonce-val"),
1005        )
1006        .unwrap();
1007        let (_, p) = signing_input.split_once('.').unwrap();
1008        let payload: serde_json::Value =
1009            serde_json::from_slice(&URL_SAFE_NO_PAD.decode(p).unwrap()).unwrap();
1010        assert_eq!(payload["ath"], "ath-hash");
1011        assert_eq!(payload["nonce"], "nonce-val");
1012    }
1013
1014    #[test]
1015    fn assemble_dpop_proof_produces_three_segments() {
1016        let proof = assemble_dpop_proof("aaa.bbb", &[0xCD; 64]);
1017        let parts: Vec<&str> = proof.split('.').collect();
1018        assert_eq!(parts.len(), 3);
1019        assert_eq!(parts[0], "aaa");
1020        assert_eq!(parts[1], "bbb");
1021    }
1022
1023    #[test]
1024    fn is_use_dpop_nonce_response_detects_400_nonce_error() {
1025        assert!(is_use_dpop_nonce_response(
1026            400,
1027            r#"{"error":"use_dpop_nonce","error_description":"nonce required"}"#
1028        ));
1029        // Not 400
1030        assert!(!is_use_dpop_nonce_response(
1031            401,
1032            r#"{"error":"use_dpop_nonce"}"#
1033        ));
1034        // 400 but different error
1035        assert!(!is_use_dpop_nonce_response(
1036            400,
1037            r#"{"error":"invalid_dpop_proof"}"#
1038        ));
1039        // Non-JSON
1040        assert!(!is_use_dpop_nonce_response(400, "not json"));
1041    }
1042
1043    #[test]
1044    fn ed25519_dpop_jkt_matches_server_thumbprint() {
1045        let pubkey = [0x65; 32];
1046        let jkt = ed25519_dpop_jkt(&pubkey);
1047        // The server computes the same RFC 7638 thumbprint for an OKP Ed25519 key.
1048        let expected =
1049            crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Ed25519 { x: &pubkey });
1050        assert_eq!(jkt, expected);
1051    }
1052
1053    #[test]
1054    fn dpop_ath_is_base64url_sha256() {
1055        let ath = dpop_ath("hello.world.token");
1056        use sha2::{Digest, Sha256};
1057        assert_eq!(
1058            ath,
1059            URL_SAFE_NO_PAD.encode(Sha256::digest(b"hello.world.token"))
1060        );
1061    }
1062
1063    // ── #1425 r1 P1#4: JTI freshness + nonce-lifecycle decision (native) ─────
1064
1065    #[test]
1066    fn generate_dpop_jti_is_fresh_every_call() {
1067        let a = generate_dpop_jti();
1068        let b = generate_dpop_jti();
1069        assert_ne!(a, b, "two proofs must never reuse a jti");
1070        // 16 random bytes, base64url-no-pad-encoded.
1071        assert_eq!(URL_SAFE_NO_PAD.decode(&a).unwrap().len(), 16);
1072    }
1073
1074    #[test]
1075    fn nonce_bootstrap_success_needs_no_retry() {
1076        // First-ever request for a key: the AS may accept without a nonce.
1077        let outcome = decide_nonce_outcome(0, true, 200, "{}", None);
1078        assert_eq!(outcome, NonceOutcome::Success);
1079    }
1080
1081    #[test]
1082    fn nonce_required_failure_retries_with_fresh_nonce() {
1083        let body = r#"{"error":"use_dpop_nonce","error_description":"nonce required"}"#;
1084        let outcome = decide_nonce_outcome(0, false, 400, body, Some("fresh-nonce-1"));
1085        assert_eq!(
1086            outcome,
1087            NonceOutcome::RetryWithNonce("fresh-nonce-1".to_owned())
1088        );
1089    }
1090
1091    #[test]
1092    fn nonce_retry_success_completes() {
1093        // Second attempt, now carrying the fresh nonce, succeeds.
1094        let outcome = decide_nonce_outcome(1, true, 200, "{}", None);
1095        assert_eq!(outcome, NonceOutcome::Success);
1096    }
1097
1098    #[test]
1099    fn nonce_required_but_no_header_to_retry_with_fails() {
1100        // Server said use_dpop_nonce but (contrary to RFC 9449 §8) omitted the
1101        // DPoP-Nonce header — nothing to retry with, must fail closed.
1102        let body = r#"{"error":"use_dpop_nonce"}"#;
1103        let outcome = decide_nonce_outcome(0, false, 400, body, None);
1104        assert_eq!(outcome, NonceOutcome::Failed);
1105    }
1106
1107    #[test]
1108    fn nonce_retry_budget_is_exactly_one_exhausted_on_second_failure() {
1109        // Even a legitimate use_dpop_nonce + fresh header on attempt 1 (the
1110        // retry itself) must NOT trigger a third attempt — bounds the loop.
1111        let body = r#"{"error":"use_dpop_nonce"}"#;
1112        let outcome = decide_nonce_outcome(1, false, 400, body, Some("another-nonce"));
1113        assert_eq!(outcome, NonceOutcome::Failed);
1114    }
1115
1116    #[test]
1117    fn dpop_mismatch_error_is_not_a_nonce_retry() {
1118        // A key/proof mismatch (invalid_dpop_proof) must propagate as a hard
1119        // failure, never be mistaken for a retryable nonce error.
1120        let body = r#"{"error":"invalid_dpop_proof","error_description":"proof key mismatch"}"#;
1121        let outcome = decide_nonce_outcome(0, false, 400, body, Some("irrelevant-nonce"));
1122        assert_eq!(outcome, NonceOutcome::Failed);
1123    }
1124
1125    #[test]
1126    fn nonce_expired_status_is_not_retried() {
1127        // A 401 (e.g. expired access/refresh token) is not a use_dpop_nonce
1128        // shape and must not be retried regardless of body content.
1129        let outcome =
1130            decide_nonce_outcome(0, false, 401, "{\"error\":\"use_dpop_nonce\"}", Some("n"));
1131        assert_eq!(outcome, NonceOutcome::Failed);
1132    }
1133
1134    #[test]
1135    fn parse_full_response() {
1136        let body = r#"{"access_token":"aaa.bbb.ccc","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"Bearer","expires_in":300}"#;
1137        let t = parse_exchange_response(body).unwrap();
1138        assert_eq!(t.access_token, "aaa.bbb.ccc");
1139        assert_eq!(t.expires_in, 300);
1140        assert_eq!(t.token_type, TokenType::Bearer);
1141    }
1142
1143    #[test]
1144    fn parse_tolerates_missing_extras() {
1145        let body = r#"{"access_token":"x.y.z"}"#;
1146        let t = parse_exchange_response(body).unwrap();
1147        assert_eq!(t.access_token, "x.y.z");
1148        assert_eq!(t.expires_in, 0);
1149        // Omitted token_type defaults to Bearer (pre-#1424 endpoint shape).
1150        assert_eq!(t.token_type, TokenType::Bearer);
1151    }
1152
1153    #[test]
1154    fn parse_rejects_missing_access_token() {
1155        let body = r#"{"token_type":"Bearer","expires_in":300}"#;
1156        assert!(parse_exchange_response(body).is_err());
1157    }
1158
1159    #[test]
1160    fn parse_rejects_unknown_token_type() {
1161        // #1425: only Bearer and DPoP are accepted; an unexpected token_type
1162        // must not be treated as a usable credential.
1163        let body = r#"{"access_token":"x","token_type":"N_A","expires_in":300}"#;
1164        assert!(parse_exchange_response(body).is_err());
1165    }
1166
1167    #[test]
1168    fn parse_accepts_dpop_token_type() {
1169        // #1425: the sender-bound exchange returns token_type: DPoP. The
1170        // client must accept it (and downstream requests must carry a proof).
1171        let body = r#"{"access_token":"x.y.z","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"DPoP","expires_in":300}"#;
1172        let t = parse_exchange_response(body).unwrap();
1173        assert_eq!(t.access_token, "x.y.z");
1174        assert_eq!(t.token_type, TokenType::Dpop);
1175    }
1176
1177    #[test]
1178    fn parse_rejects_wrong_issued_token_type() {
1179        let body = r#"{"access_token":"x","issued_token_type":"urn:ietf:params:oauth:token-type:id_token","token_type":"Bearer","expires_in":300}"#;
1180        assert!(parse_exchange_response(body).is_err());
1181    }
1182
1183    #[test]
1184    fn parse_rejects_non_json() {
1185        assert!(parse_exchange_response("not json").is_err());
1186    }
1187
1188    #[test]
1189    fn subject_decoded_from_sub_claim() {
1190        let token =
1191            jwt(r#"{"iss":"https://node.example","sub":"did:plc:abc","exp":9999999999,"iat":1}"#);
1192        let sub = subject_from_access_token(&token).unwrap();
1193        assert_eq!(sub.name(), Some("did:plc:abc"));
1194        assert!(!sub.is_anonymous());
1195    }
1196
1197    #[test]
1198    fn subject_rejects_empty_sub() {
1199        let token = jwt(r#"{"iss":"x","sub":"","exp":1,"iat":1}"#);
1200        assert!(subject_from_access_token(&token).is_err());
1201    }
1202
1203    #[test]
1204    fn subject_rejects_non_jwt() {
1205        assert!(subject_from_access_token("not-a-jwt").is_err());
1206    }
1207
1208    #[test]
1209    fn exchanged_token_debug_redacts_access_token() {
1210        let t = ExchangedToken {
1211            access_token: "secret-bearer-value".to_owned(),
1212            expires_in: 300,
1213            token_type: TokenType::Bearer,
1214            nonce: None,
1215        };
1216        let rendered = format!("{t:?}");
1217        assert!(
1218            !rendered.contains("secret-bearer-value"),
1219            "ExchangedToken Debug leaked the access_token: {rendered}"
1220        );
1221        assert!(rendered.contains("<redacted>"));
1222        assert!(rendered.contains("300"));
1223    }
1224
1225    #[test]
1226    fn parses_local_session_context() {
1227        let context = parse_session_context(
1228            r#"{"did":"did:web:alice.example","kind":"local","tenant":"acme","canActLocally":true}"#,
1229        )
1230        .unwrap();
1231        assert_eq!(context.did.as_deref(), Some("did:web:alice.example"));
1232        assert_eq!(context.kind, SessionKind::Local);
1233        assert_eq!(context.tenant.as_deref(), Some("acme"));
1234        assert!(context.can_act_locally);
1235    }
1236
1237    #[test]
1238    fn parses_unauthenticated_floor() {
1239        let context = parse_session_context(
1240            r#"{"did":null,"kind":"unauthenticated","tenant":null,"canActLocally":false}"#,
1241        )
1242        .unwrap();
1243        assert_eq!(context.kind, SessionKind::Unauthenticated);
1244        assert!(context.did.is_none());
1245        assert!(context.tenant.is_none());
1246        assert!(!context.can_act_locally);
1247    }
1248
1249    #[test]
1250    fn rejects_inconsistent_session_authority() {
1251        assert!(parse_session_context(
1252            r#"{"did":"did:web:alice.example","kind":"federated","tenant":"client-asserted","canActLocally":true}"#,
1253        )
1254        .is_err());
1255    }
1256
1257    #[test]
1258    fn classifies_invalid_dpop_proof() {
1259        let code = classify_exchange_error_code(
1260            r#"token-exchange endpoint returned HTTP 400: {"error":"invalid_dpop_proof","error_description":"DPoP proof verification failed"}"#,
1261        );
1262        assert_eq!(code, "invalid_dpop_proof");
1263    }
1264
1265    #[test]
1266    fn classifies_replay() {
1267        let code = classify_exchange_error_code(
1268            r#"token-exchange endpoint returned HTTP 401: {"error":"invalid_token","error_description":"ATProto service-auth JWT already used"}"#,
1269        );
1270        assert_eq!(code, "replay");
1271    }
1272
1273    #[test]
1274    fn classifies_dpop_key_mismatch() {
1275        let code = classify_exchange_error_code(
1276            "exchanged token cnf.jkt does not match the browser DPoP key",
1277        );
1278        assert_eq!(code, "dpop_key_mismatch");
1279    }
1280
1281    #[test]
1282    fn classifies_missing_cnf_jkt_as_dpop_key_mismatch() {
1283        let code = classify_exchange_error_code(
1284            "exchanged token carries no cnf.jkt; sender binding is missing",
1285        );
1286        assert_eq!(code, "dpop_key_mismatch");
1287    }
1288
1289    #[test]
1290    fn classifies_missing_sender_binding() {
1291        let code = classify_exchange_error_code(
1292            "sender-bound browser exchange requires token_type: DPoP; got Bearer or an omitted token_type",
1293        );
1294        assert_eq!(code, "sender_binding_missing");
1295    }
1296
1297    #[test]
1298    fn classifies_expired_or_revoked_subject() {
1299        let code = classify_exchange_error_code(
1300            r#"token-exchange endpoint returned HTTP 401: {"error":"invalid_token","error_description":"subject token expired"}"#,
1301        );
1302        assert_eq!(code, "expired_or_revoked_subject");
1303    }
1304
1305    #[test]
1306    fn classifies_invalid_request() {
1307        let code = classify_exchange_error_code(
1308            r#"token-exchange endpoint returned HTTP 400: {"error":"invalid_request","error_description":"subject_token_type is required"}"#,
1309        );
1310        assert_eq!(code, "invalid_request");
1311    }
1312
1313    #[test]
1314    fn unrecognized_shape_still_classifies_as_transport_error() {
1315        let code = classify_exchange_error_code("network fetch failed: connection reset");
1316        assert_eq!(code, "transport_error");
1317    }
1318
1319    #[test]
1320    fn expires_at_ms_is_in_the_future_for_a_positive_ttl() {
1321        assert_eq!(expires_at_ms(1_000.0, 300), 1_000.0 + 300_000.0);
1322    }
1323
1324    #[test]
1325    fn expires_at_ms_clamps_negative_ttl_to_now() {
1326        assert_eq!(expires_at_ms(1_000.0, -10), 1_000.0);
1327    }
1328
1329    #[test]
1330    fn expires_at_ms_clamps_zero_ttl_to_now() {
1331        assert_eq!(expires_at_ms(1_000.0, 0), 1_000.0);
1332    }
1333}