Skip to main content

capsule_sdk/recovery/
mod.rs

1//! Recovery-secret verification cadence and the guided re-wrap flow (
2//! SSoT: [Backup — Recovery Verification Cadence] and [§ On Repeated Failure: Guided
3//! Re-Wrap]).
4//!
5//! This module owns the **client half** of the master-key recovery story that the
6//! server escrow surface (`PUT`/`GET /v1/auth/escrow`) and the core
7//! crypto ([`capsule_core::backup`]) make possible. It has two cohesive halves:
8//!
9//! - **[`cadence`]** — the pure, network-free scheduler and prompt state machine
10//!   ([`RecoveryCadence`] → [`VerificationState`]): the 7 d → 90 d → 180 d ladder,
11//!   re-arm triggers, snooze caps, and the escalation to a guided re-wrap. It is driven
12//!   by a mocked clock and never blocks any flow.
13//! - **[`RecoveryClient`]** — the networked side: the cached copy of the escrow blob
14//!   ([`EscrowCache`]), the stale-cache-aware [`verify`](RecoveryClient::verify), and the
15//!   [`guided_rewrap`](RecoveryClient::guided_rewrap) that mints a fresh secret, re-wraps
16//!   the **same** master key, and replaces the server escrow through the server's
17//!   escrow endpoint. It also stores and fetches the **sealed identity** beside the escrow
18//!   ([`store_sealed_identity`](RecoveryClient::store_sealed_identity),
19//!   [`fetch_sealed_identity`](RecoveryClient::fetch_sealed_identity),
20//!   `/v1/auth/escrow/identity`, #544): the user identity key sealed under the master key,
21//!   which a recovered device opens beside the recovered master key to come up as the same
22//!   account. And it stores and lists the account's **album key escrows**
23//!   ([`store_album_keys`](RecoveryClient::store_album_keys),
24//!   [`list_album_keys`](RecoveryClient::list_album_keys), `/v1/auth/escrow/albums`, #741):
25//!   each album's keys sealed under the master key, which a recovered device adopts so it can
26//!   open the account's assets.
27//!
28//! The escrow blob on the wire is the opaque canonical-CBOR encoding of a
29//! [`WrappedSecret`] — byte-identical to what the server stores verbatim and to what the
30//! core restore path unwraps.
31//!
32//! # The wire is the generated client, not a path this module builds
33//!
34//! Both escrow operations are `application/octet-stream` in each direction, which is a media
35//! type `spargen` lowers, so both are **generated** and neither is narrowed out in
36//! `build.rs`. [`RecoveryClient`] therefore orchestrates
37//! [`AuthenticatedClient::fetch_escrow`](crate::rest::Client::fetch_escrow) and
38//! [`store_escrow`](crate::rest::Client::store_escrow) and hand-writes no request. That is
39//! not a preference: `.claude/rules/capsule-sdk.md` requires that everything which parses or
40//! serializes is generated, *including* the byte-serving endpoints, and the reason is this
41//! module's own history. It used to build `{api_root}/backup/escrow` from a `const` — the
42//! Salvo document's path — and when the contract was re-sourced from Kynos to `/v1/auth/escrow` nothing
43//! noticed, because a route in a string constant is checked by no gate and this module's own
44//! mock answered whichever path it was handed.
45//!
46//! [Backup — Recovery Verification Cadence]: https://docs/design/backup-recovery/#recovery-verification-cadence
47//! [§ On Repeated Failure: Guided Re-Wrap]: https://docs/design/backup-recovery/#on-repeated-failure-guided-re-wrap
48
49pub mod cadence;
50
51use std::sync::Arc;
52
53use base64::Engine as _;
54use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
55pub use cadence::{
56    BACKOFF_INTERVAL_SECS, CAP_INTERVAL_SECS, INITIAL_INTERVAL_SECS, MAX_CONSECUTIVE_SNOOZES,
57    REWRAP_FAILURE_THRESHOLD, REWRAP_MIN_SESSIONS, RearmTrigger, RecoveryCadence, SnoozeDuration,
58    VerificationState,
59};
60use capsule_core::backup::{VerifyOutcome, split_seed_2of3, verify_recovery_secret};
61use capsule_core::crypto::primitives::{Argon2Params, DeviceTier};
62use capsule_core::crypto::pwkdf::{self, WrappedSecret};
63use capsule_core::crypto::rng;
64use capsule_i18n::error_codes;
65use jiff::Timestamp;
66use tracing::instrument;
67use uuid::Uuid;
68
69use crate::auth::Session;
70use crate::client::{
71    AuthenticatedClient, ClientError, describe_error, is_token_failure, upgrade_required_of,
72};
73use crate::rest;
74
75/// Everything the networked recovery flows can fail with. Callers switch on the typed
76/// variant (or its stable `error.*` code), never a bare HTTP status.
77#[derive(Debug, thiserror::Error)]
78pub enum RecoveryError {
79    // There is deliberately no `Auth(AuthError)` variant any more. The session used to build
80    // these requests itself, so a dead session surfaced as its own typed `AuthError`; the
81    // generated client attaches the bearer through a token-provider seam that flattens our
82    // `AuthError` to a string, so the same event now arrives as `Unauthorized` — which is
83    // where the FFI's `Auth` mapping reads it from. An unconstructible variant would be a
84    // promise no code path can keep.
85    /// The API root is not a URL the generated client can hang operation paths off.
86    #[error("invalid base URL {url:?}: {reason}")]
87    InvalidBaseUrl {
88        /// The offending URL.
89        url: String,
90        /// Why the generated client rejected it.
91        reason: String,
92    },
93    /// The call never reached a server answer: DNS, connection refused, a TLS handshake, a
94    /// timeout, a reset mid-body, or a refusal this client could not parse. Transient — the
95    /// cadence's next tick tries again.
96    ///
97    /// The generated taxonomy files a connection failure under `Transport` and a genuine
98    /// pre-flight one under `RequestConstruction`; both land here, except a session that could
99    /// not mint a bearer, which is [`RecoveryError::Unauthorized`].
100    #[error("the escrow endpoint could not be reached: {0}")]
101    Transport(String),
102    /// The credential was refused (`401`/`403`) and a refresh did not recover it — the user
103    /// must re-authenticate.
104    ///
105    /// `code` is whatever the server stamped on the problem body. Today Capsule stamps one
106    /// code (`error.request.unauthenticated`) on every `401` it renders, so this does not yet
107    /// separate an expired token from an unreadable revocation ledger; the field carries the
108    /// code so that it will the moment the server distinguishes them.
109    #[error("the escrow endpoint refused the credential: {detail}")]
110    Unauthorized {
111        /// The stable `error.*` catalog code from the problem body, when the failure came
112        /// with one. `None` when the credential could not be produced at all — there was no
113        /// server answer to carry a code.
114        code: Option<String>,
115        /// English detail from the problem body.
116        detail: String,
117    },
118    /// The caller has no escrow stored yet (server returned a coded `404`). Enroll one first.
119    #[error("no escrow stored for this account")]
120    NotEnrolled,
121    /// The caller has stored no sealed identity (`GET /v1/auth/escrow/identity` answered a coded
122    /// `404`). The escrow alone cannot open the account as itself: a device that still holds the
123    /// identity has to store it ([`RecoveryClient::store_sealed_identity`]) first.
124    #[error("no sealed identity stored for this account")]
125    IdentityNotStored,
126    /// The server refused the blob as one that cannot be an escrow at any version — empty or
127    /// past the coarse ceiling (`400`), not the declared media type (`415`), or past the
128    /// transport's body limit (`413`). Retrying the same bytes changes nothing.
129    #[error("the server rejected the escrow blob: {detail}")]
130    Malformed {
131        /// The stable `error.*` catalog code the refusal carried.
132        code: Option<String>,
133        /// English detail from the problem body.
134        detail: String,
135    },
136    /// The account's album key escrows are at the server's per-account bound (`409`, coded
137    /// `error.escrow.album_keys_full`): nothing was stored, and resending will not fit either.
138    #[error("the account's album key escrows are full: {detail}")]
139    AlbumKeysFull {
140        /// The stable `error.*` catalog code the refusal carried.
141        code: Option<String>,
142        /// English detail from the problem body.
143        detail: String,
144    },
145    /// The escrow store could not answer (`500`). Transient, and coded
146    /// `error.escrow.unavailable` — which is why it is not folded into
147    /// [`Transport`](RecoveryError::Transport): a caller that localizes codes has one to show.
148    #[error("the escrow store could not answer: {detail}")]
149    Unavailable {
150        /// The stable `error.*` catalog code the refusal carried.
151        code: Option<String>,
152        /// English detail from the problem body.
153        detail: String,
154    },
155    /// The escrow bytes could not be (de)serialized as the canonical `WrappedSecret`.
156    #[error("escrow blob codec error: {0}")]
157    Codec(String),
158    /// A success answer this client could not read — a `stored_at` that is not an RFC 3339
159    /// instant. The server *did* answer `200`, so the escrow may well be stored; this is the
160    /// answer being unreadable, not the write being refused.
161    #[error("the escrow endpoint's answer could not be read: {0}")]
162    InvalidResponse(String),
163    /// The (re-)wrap of the master key under the fresh secret failed in core.
164    #[error("re-wrapping the master key failed: {0}")]
165    Wrap(String),
166    /// The server returned a status this client does not model as an escrow outcome — an
167    /// unmodeled status, or the body-size backstop's `413` on a read.
168    #[error("unexpected {status} response from the escrow endpoint")]
169    Unexpected {
170        /// The HTTP status code the server returned.
171        status: u16,
172        /// The stable `error.*` catalog code the response carried, when it came with a coded
173        /// problem body. `None` when there was no body to read a code from.
174        code: Option<String>,
175    },
176    /// The server will not take this client's writes: the protocol gate's `426`, or a window
177    /// it advertised that already refuses this build, so the write never left (issue #674).
178    /// Nothing about the escrow is wrong — update the client.
179    #[error(transparent)]
180    UpgradeRequired(Box<crate::net::negotiation::UpgradeRequired>),
181}
182
183impl RecoveryError {
184    /// The stable `error.*` catalog code a client localizes, when one applies. The English
185    /// [`Display`](std::fmt::Display) form stays the developer/log detail.
186    #[must_use]
187    pub fn error_code(&self) -> Option<&str> {
188        match self {
189            Self::Unauthorized { code, .. }
190            | Self::Malformed { code, .. }
191            | Self::AlbumKeysFull { code, .. }
192            | Self::Unavailable { code, .. }
193            | Self::Unexpected { code, .. } => code.as_deref(),
194            Self::UpgradeRequired(refusal) => Some(refusal.error_code()),
195            // The one code this module states rather than reads. `NotEnrolled` is a *state*
196            // ("this account has escrowed nothing"), not a message, and the server's own code
197            // for that state is this constant — see `capsule-server/src/routes/escrow.rs`.
198            Self::NotEnrolled => Some(error_codes::ESCROW_NOT_STORED),
199            // The same reasoning, for the sealed identity's own `404` state.
200            Self::IdentityNotStored => Some(error_codes::ESCROW_IDENTITY_NOT_STORED),
201            _ => None,
202        }
203    }
204}
205
206/// What storing an escrow did: the server's `StoreEscrowResponse`, read.
207///
208/// Both members are for a client. [`stored_at`](Self::stored_at) is what lets it tell
209/// whether a cached copy is current (the [stale-cache rule](RecoveryClient::verify));
210/// [`replaced`](Self::replaced) separates a first escrow, which completes account setup,
211/// from a replacement, which means the *previous* recovery secret has stopped working.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub struct EscrowStored {
214    /// When the server accepted the blob, on the server's clock.
215    pub stored_at: Timestamp,
216    /// Whether this displaced an earlier escrow.
217    pub replaced: bool,
218}
219
220impl EscrowStored {
221    /// The guidance about backup artifacts under the old secret that this store calls for:
222    /// [`ReexportOrDestroy`](OldArtifactGuidance::ReexportOrDestroy) when it displaced an
223    /// earlier escrow, and none for a first enrollment — there was no earlier secret for an
224    /// artifact to be bound to.
225    #[must_use]
226    pub fn old_artifact_guidance(&self) -> Option<OldArtifactGuidance> {
227        self.replaced
228            .then_some(OldArtifactGuidance::ReexportOrDestroy)
229    }
230}
231
232/// What storing a sealed identity did: the server's `StoreSealedIdentityResponse`, read.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub struct SealedIdentityStored {
235    /// When the server accepted the blob, on the server's clock.
236    pub stored_at: Timestamp,
237    /// Whether this displaced an earlier sealed identity. Unlike an escrow replacement it retires
238    /// no secret: the identity key is the same one, sealed again.
239    pub replaced: bool,
240}
241
242/// What storing an album key escrow did: the server's `StoreAlbumKeysResponse`, read.
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244pub struct AlbumKeysStored {
245    /// When the server accepted the blob, on the server's clock.
246    pub stored_at: Timestamp,
247    /// Whether this displaced an earlier escrow of the same album's keys.
248    pub replaced: bool,
249}
250
251/// One album's key escrow as the server holds it: the album's whole key state, sealed under the
252/// master key by `Workspace::album_key_escrow`, and opened by
253/// `Workspace::adopt_album_key_escrows`.
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub struct EscrowedAlbumKeys {
256    /// The album the keys are of.
257    pub album_id: Uuid,
258    /// The sealed keys, exactly as stored.
259    pub blob: Vec<u8>,
260    /// When the server accepted them.
261    pub stored_at: Timestamp,
262}
263
264/// A client-side cached copy of the server escrow blob.
265///
266/// Fetched at enrollment and refreshed opportunistically (SSoT § Local Verification);
267/// the [stale-cache rule](RecoveryClient::verify) refreshes it before ever recording a
268/// verification failure, so a rotation on another device can never manufacture a false
269/// failure here.
270///
271/// It carries the blob's [`stored_at`](Self::stored_at) when this client knows it — from
272/// its own [`store_escrow`](RecoveryClient::store_escrow), or from a
273/// [`verify`](RecoveryClient::verify) that refreshed against a known instant. A blob
274/// fetched with `GET /v1/auth/escrow` alone has none: that operation serves the bytes and
275/// nothing else.
276#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct EscrowCache {
278    blob: WrappedSecret,
279    stored_at: Option<Timestamp>,
280}
281
282impl EscrowCache {
283    /// Wrap an already-decoded escrow blob as the local cache, with no known `stored_at`.
284    #[must_use]
285    pub fn new(blob: WrappedSecret) -> Self {
286        Self {
287            blob,
288            stored_at: None,
289        }
290    }
291
292    /// Wrap an escrow blob whose server `stored_at` is known — the blob this client just
293    /// stored, paired with the [`EscrowStored::stored_at`] the server answered.
294    #[must_use]
295    pub fn with_stored_at(blob: WrappedSecret, stored_at: Timestamp) -> Self {
296        Self {
297            blob,
298            stored_at: Some(stored_at),
299        }
300    }
301
302    /// The cached wrapped-master-key escrow blob.
303    #[must_use]
304    pub fn blob(&self) -> &WrappedSecret {
305        &self.blob
306    }
307
308    /// When the server stored the cached blob, when this client knows it.
309    #[must_use]
310    pub fn stored_at(&self) -> Option<Timestamp> {
311        self.stored_at
312    }
313
314    /// Whether an escrow stored at `latest` is newer than this copy. A copy with no known
315    /// `stored_at` cannot prove it is current, so it counts as older.
316    #[must_use]
317    pub fn is_older_than(&self, latest: Timestamp) -> bool {
318        self.stored_at.is_none_or(|stored_at| stored_at < latest)
319    }
320
321    /// Decode an escrow cache from the opaque canonical-CBOR wire bytes.
322    fn from_wire(bytes: &[u8]) -> Result<Self, RecoveryError> {
323        let blob: WrappedSecret = capsule_core::cbor::from_slice(bytes)
324            .map_err(|e| RecoveryError::Codec(e.to_string()))?;
325        Ok(Self::new(blob))
326    }
327}
328
329/// A freshly minted recovery secret, presented to the user exactly once. It doubles as
330/// the escrow wrap passphrase and (when enrolled) the Shamir-split seed — the single
331/// root of the [single-root invariant](https://docs/design/backup-recovery/#single-root-invariant).
332///
333/// The bytes are zeroized on drop; surface them to the user (as a BIP39-style phrase or
334/// hex) and then let this drop.
335pub struct MintedSecret {
336    seed: [u8; 32],
337}
338
339impl MintedSecret {
340    /// Draw a fresh 32-byte (256-bit — well over the ≥128-bit floor) recovery secret.
341    #[must_use]
342    pub fn generate() -> Self {
343        Self {
344            seed: rng::random_array::<32>(),
345        }
346    }
347
348    /// The raw secret bytes (the escrow wrap passphrase and Shamir seed).
349    #[must_use]
350    pub fn as_bytes(&self) -> &[u8; 32] {
351        &self.seed
352    }
353
354    /// Lowercase-hex rendering, for surfacing the secret to the user.
355    #[must_use]
356    pub fn to_hex(&self) -> String {
357        hex::encode(self.seed)
358    }
359
360    /// The setup-style **type-back gate**: confirm the user re-entered the secret they
361    /// were just shown. A constant-time compare over the decoded bytes.
362    #[must_use]
363    pub fn matches(&self, typed: &[u8]) -> bool {
364        typed.len() == self.seed.len()
365            && typed
366                .iter()
367                .zip(self.seed.iter())
368                .fold(0u8, |acc, (a, b)| acc | (a ^ b))
369                == 0
370    }
371}
372
373impl Drop for MintedSecret {
374    fn drop(&mut self) {
375        // Best-effort zeroization of the recovery secret.
376        for byte in &mut self.seed {
377            *byte = 0;
378        }
379    }
380}
381
382impl std::fmt::Debug for MintedSecret {
383    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384        // Never print the secret material.
385        f.debug_struct("MintedSecret").finish_non_exhaustive()
386    }
387}
388
389/// Guidance the client surfaces after a rotation about backup **artifacts** exported
390/// under the *old* secret — pure data (a stable variant), never a localized string, so
391/// the client maps it to a catalog key.
392///
393/// Per the [single-root invariant] versioning seam: an already-exported backup artifact
394/// stays bound to the passphrase in force at export, so rotating the recovery secret
395/// ends with "re-export or destroy old artifacts" guidance.
396///
397/// [single-root invariant]: https://docs/design/backup-recovery/#single-root-invariant
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub enum OldArtifactGuidance {
400    /// Backup artifacts exported before this rotation still open only with the *old*
401    /// secret. Re-export them under the new secret, or destroy them.
402    ReexportOrDestroy,
403}
404
405/// The Shamir shares re-issued during a guided re-wrap when the account had social
406/// recovery enrolled. The old shares are explicitly invalidated (they split the *old*
407/// seed) and surfaced as such.
408#[derive(Debug, Clone, PartialEq, Eq)]
409pub struct ShamirReissue {
410    /// The fresh 2-of-3 shares splitting the **new** seed.
411    pub shares: Vec<Vec<u8>>,
412    /// Always `true`: the previously issued shares split the old seed and no longer
413    /// reconstruct anything useful — the client must tell the user to discard them.
414    pub old_shares_invalidated: bool,
415}
416
417/// The outcome of a guided re-wrap: everything the UX needs, surfaced as data.
418///
419/// The master key is **unchanged** — this is wrap rotation, not key rotation (SSoT
420/// § On Repeated Failure). [`new_escrow`](Self::new_escrow) wraps the same master key
421/// under [`secret`](Self::secret); no asset blob is touched or re-encrypted.
422#[derive(Debug)]
423pub struct GuidedRewrap {
424    /// The freshly minted recovery secret — present once, confirm via the type-back
425    /// gate ([`MintedSecret::matches`]), then let it drop.
426    pub secret: MintedSecret,
427    /// The new escrow blob (already stored on the server), cached locally with the
428    /// server's `stored_at`.
429    pub new_escrow: EscrowCache,
430    /// What the store did — in particular whether it displaced an earlier escrow.
431    pub stored: EscrowStored,
432    /// Re-issued Shamir shares, when the account had social recovery enrolled.
433    pub shamir: Option<ShamirReissue>,
434    /// Whether the client must run the setup-style type-back gate (always `true`).
435    pub type_back_required: bool,
436    /// Guidance about backup artifacts exported under the old secret: present only when the
437    /// store [replaced](EscrowStored::replaced) an earlier escrow. A re-wrap on an account
438    /// that had none retired no secret, so there is no old artifact to warn about.
439    pub old_artifact_guidance: Option<OldArtifactGuidance>,
440}
441
442/// The networked recovery client: escrow cache/refresh, stale-cache-aware local
443/// verification, and the guided re-wrap.
444///
445/// It holds one [`AuthenticatedClient`], so every call rides the generated operation paths
446/// and the SDK's bearer/refresh machinery, and this module states no route of its own. The
447/// client is behind an [`Arc`] only so [`RecoveryClient`] stays [`Clone`] — the cadence hands
448/// one client to several prompts. There is deliberately no repoint/session-swap accessor:
449/// `AuthenticatedClient`'s own take `&mut self` and are unreachable through the `Arc`, and an
450/// escrow client that changed origin mid-cadence would be a way to pull one account's escrow
451/// into another's cache. Build a new one instead.
452#[derive(Clone)]
453pub struct RecoveryClient {
454    client: Arc<AuthenticatedClient>,
455}
456
457impl RecoveryClient {
458    /// Build a recovery client against the **API root** — the origin the generated operation
459    /// paths hang off (e.g. `https://api.example.com`), which is the same base
460    /// [`AuthenticatedClient`] and [`crate::sync::SyncConsumer`] take.
461    ///
462    /// # Errors
463    ///
464    /// [`RecoveryError::InvalidBaseUrl`] when `api_base_url` is not a URL operation paths can
465    /// hang off. Fallible where the old hand-written `format!` was not, because the generated
466    /// client parses the base once at construction rather than per call.
467    pub fn new(session: Session, api_base_url: &str) -> Result<Self, RecoveryError> {
468        let client =
469            AuthenticatedClient::new(api_base_url, session).map_err(|error| match error {
470                ClientError::InvalidBaseUrl { url, reason } => {
471                    RecoveryError::InvalidBaseUrl { url, reason }
472                }
473            })?;
474        Ok(Self {
475            client: Arc::new(client),
476        })
477    }
478
479    /// Fetch the current escrow blob from the server (`GET /v1/auth/escrow`) into a fresh
480    /// [`EscrowCache`]. `404` maps to [`RecoveryError::NotEnrolled`].
481    #[instrument(skip_all)]
482    pub async fn fetch_escrow(&self) -> Result<EscrowCache, RecoveryError> {
483        // The protocol date is a required parameter of every gated operation in the document,
484        // so the generated signature asks for it; the value is the build's own, the same one the
485        // transport's default header carries. The suite and sidecar schema ride the transport.
486        let bytes = self
487            .client
488            .fetch_escrow(rest::FetchEscrowParamsRequired {
489                x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
490            })
491            .await
492            .map_err(fetch_escrow_error)?
493            .into_inner();
494        tracing::debug!(len = bytes.len(), "fetched escrow blob");
495        EscrowCache::from_wire(&bytes)
496    }
497
498    /// Store or replace the caller's escrow blob (`PUT /v1/auth/escrow`). Single active
499    /// escrow: the server overwrites any prior blob in the same transaction.
500    ///
501    /// The canonical CBOR goes on the wire verbatim. The answer comes back as
502    /// [`EscrowStored`]: `stored_at` for the stale-cache rule, `replaced` to tell a first
503    /// enrollment from a rotation.
504    ///
505    /// # Errors
506    ///
507    /// The refusals `store_escrow_error` maps, and [`RecoveryError::InvalidResponse`] when
508    /// the server's `stored_at` is not an RFC 3339 instant.
509    #[instrument(skip_all)]
510    pub async fn store_escrow(&self, blob: &WrappedSecret) -> Result<EscrowStored, RecoveryError> {
511        let body = capsule_core::cbor::to_canonical_vec(blob)
512            .map_err(|e| RecoveryError::Codec(e.to_string()))?;
513        let stored = self
514            .client
515            .store_escrow(
516                rest::StoreEscrowParamsRequired {
517                    x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
518                },
519                rest::types::StoreEscrowBody::from(body),
520            )
521            .await
522            .map_err(store_escrow_error)?
523            .into_inner();
524        let stored_at = stored_instant(&stored.stored_at, "escrow")?;
525        tracing::info!(
526            %stored_at,
527            replaced = stored.replaced,
528            "escrow blob stored (single active escrow: any prior blob replaced)"
529        );
530        Ok(EscrowStored {
531            stored_at,
532            replaced: stored.replaced,
533        })
534    }
535
536    /// Store or replace the caller's **sealed identity** (`PUT /v1/auth/escrow/identity`): the
537    /// user identity key sealed under the master key, as `Workspace::sealed_identity` returns
538    /// it. The other half of what a recovered device needs beside the escrow — the identity is
539    /// random rather than master-derived, and the server pins it on first directory publish, so
540    /// a recovered device must carry this one rather than mint its own.
541    ///
542    /// Opaque on the wire and stored independently of the escrow: a
543    /// [`guided_rewrap`](Self::guided_rewrap) replaces the escrow and leaves this alone, because
544    /// re-wrapping the master key under a new recovery secret does not change the master key
545    /// the identity is sealed under.
546    ///
547    /// # Errors
548    ///
549    /// The same refusals [`store_escrow`](Self::store_escrow) maps, under this operation's
550    /// statuses, and [`RecoveryError::InvalidResponse`] for an unreadable `stored_at`.
551    #[instrument(skip_all, fields(len = sealed.len()))]
552    pub async fn store_sealed_identity(
553        &self,
554        sealed: &[u8],
555    ) -> Result<SealedIdentityStored, RecoveryError> {
556        let stored = self
557            .client
558            .store_sealed_identity(
559                rest::StoreSealedIdentityParamsRequired {
560                    x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
561                },
562                rest::types::StoreSealedIdentityBody::from(sealed.to_vec()),
563            )
564            .await
565            .map_err(store_sealed_identity_error)?
566            .into_inner();
567        let stored_at = stored_instant(&stored.stored_at, "sealed identity")?;
568        tracing::info!(
569            %stored_at,
570            replaced = stored.replaced,
571            "sealed identity stored (one per account: any prior one replaced)"
572        );
573        Ok(SealedIdentityStored {
574            stored_at,
575            replaced: stored.replaced,
576        })
577    }
578
579    /// Fetch the caller's sealed identity (`GET /v1/auth/escrow/identity`), verbatim — the
580    /// bytes `Workspace::create_from_master` opens under the recovered master key.
581    ///
582    /// # Errors
583    ///
584    /// [`RecoveryError::IdentityNotStored`] on the coded `404`; otherwise the refusals
585    /// [`fetch_escrow`](Self::fetch_escrow) maps.
586    #[instrument(skip_all)]
587    pub async fn fetch_sealed_identity(&self) -> Result<Vec<u8>, RecoveryError> {
588        let bytes = self
589            .client
590            .fetch_sealed_identity(rest::FetchSealedIdentityParamsRequired {
591                x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
592            })
593            .await
594            .map_err(fetch_sealed_identity_error)?
595            .into_inner();
596        tracing::debug!(len = bytes.len(), "fetched the sealed identity");
597        Ok(bytes.to_vec())
598    }
599
600    /// Store or replace one album's **key escrow** (`PUT /v1/auth/escrow/albums/{album_id}`,
601    /// #741): the album's whole key state sealed under the master key, as
602    /// `Workspace::album_key_escrow` returns it. One slot per album; storing it never touches
603    /// another album's, the escrow or the sealed identity.
604    ///
605    /// # Errors
606    ///
607    /// [`RecoveryError::Malformed`] for a blob the server refuses (empty, past the album keys'
608    /// ceiling, or an album id that is not canonical), the credential and store refusals
609    /// [`store_escrow`](Self::store_escrow) maps, and [`RecoveryError::InvalidResponse`] for an
610    /// unreadable `stored_at`.
611    #[instrument(skip(self, sealed), fields(len = sealed.len()))]
612    pub async fn store_album_keys(
613        &self,
614        album_id: Uuid,
615        sealed: &[u8],
616    ) -> Result<AlbumKeysStored, RecoveryError> {
617        let stored = self
618            .client
619            .store_album_keys(
620                album_id.to_string(),
621                rest::StoreAlbumKeysParamsRequired {
622                    x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
623                },
624                rest::types::StoreAlbumKeysBody::from(sealed.to_vec()),
625            )
626            .await
627            .map_err(store_album_keys_error)?
628            .into_inner();
629        let stored_at = stored_instant(&stored.stored_at, "album key escrow")?;
630        tracing::info!(
631            %album_id,
632            %stored_at,
633            replaced = stored.replaced,
634            "album key escrow stored (one per album: any prior one replaced)"
635        );
636        Ok(AlbumKeysStored {
637            stored_at,
638            replaced: stored.replaced,
639        })
640    }
641
642    /// Every album key escrow the account holds (`GET /v1/auth/escrow/albums`), each blob
643    /// verbatim, in album order. Empty for an account that has escrowed no album.
644    ///
645    /// # Errors
646    ///
647    /// The credential and store refusals [`fetch_escrow`](Self::fetch_escrow) maps, and
648    /// [`RecoveryError::InvalidResponse`] when an entry's album id, blob or `stored_at` cannot
649    /// be read.
650    #[instrument(skip_all)]
651    pub async fn list_album_keys(&self) -> Result<Vec<EscrowedAlbumKeys>, RecoveryError> {
652        let listing = self
653            .client
654            .list_album_keys(rest::ListAlbumKeysParamsRequired {
655                x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
656            })
657            .await
658            .map_err(list_album_keys_error)?
659            .into_inner();
660        let albums = listing
661            .albums
662            .into_iter()
663            .map(read_escrowed_album_keys)
664            .collect::<Result<Vec<_>, RecoveryError>>()?;
665        tracing::debug!(albums = albums.len(), "fetched the album key escrows");
666        Ok(albums)
667    }
668
669    /// Local recovery-secret verification with the **stale-cache rule** (SSoT § Local
670    /// Verification): run the offline derived-tag compare against the cached blob; if it
671    /// does not verify, refresh the blob from the server **once** and retry before
672    /// returning a failure — so a rotation on another device cannot manufacture a false
673    /// failure here.
674    ///
675    /// `latest_stored_at` is the newest escrow `stored_at` the caller has seen — an
676    /// [`EscrowStored`] from any device, however it reached this one. When the cache is
677    /// [older](EscrowCache::is_older_than) than it, the cache is known stale: it is refreshed
678    /// **before** the compare and stamped with `latest_stored_at`, and the compare against
679    /// the fresh blob is the answer, with no second fetch on a failure. `None`, or a cache at
680    /// least that new, keeps the refresh-on-failure rule above.
681    ///
682    /// Purely local crypto (`capsule_core::backup::verify_recovery_secret`); the only
683    /// network I/O is the single conditional refresh. Never blocks anything.
684    #[instrument(skip_all, fields(cache_stored_at = ?cache.stored_at(), ?latest_stored_at))]
685    pub async fn verify(
686        &self,
687        cache: &mut EscrowCache,
688        passphrase: &[u8],
689        device_master: &[u8; 32],
690        latest_stored_at: Option<Timestamp>,
691    ) -> Result<VerifyOutcome, RecoveryError> {
692        if let Some(latest) = latest_stored_at.filter(|latest| cache.is_older_than(*latest)) {
693            // Known stale: refresh before comparing, so the compare is against the current
694            // blob and a failure is genuine on the first try.
695            tracing::info!(%latest, "cached escrow predates the latest stored_at; refreshing first");
696            let refreshed = self.fetch_escrow().await?;
697            *cache = EscrowCache::with_stored_at(refreshed.blob, latest);
698            let outcome = verify_recovery_secret(cache.blob(), passphrase, device_master);
699            tracing::debug!(
700                ?outcome,
701                "verified against the proactively refreshed escrow"
702            );
703            return Ok(outcome);
704        }
705
706        if verify_recovery_secret(cache.blob(), passphrase, device_master)
707            == VerifyOutcome::Verified
708        {
709            tracing::debug!("recovery secret verified against the cached escrow");
710            return Ok(VerifyOutcome::Verified);
711        }
712
713        // Stale-cache rule: the cached blob may be stale after a rotation elsewhere.
714        // Refresh once and retry before recording a failure.
715        tracing::info!("cached-escrow verify failed; refreshing escrow and retrying once");
716        let refreshed = self.fetch_escrow().await?;
717        let changed = refreshed.blob != cache.blob;
718        if changed {
719            // A different blob: the cached `stored_at` described the old one, and `GET` does
720            // not say when this one was stored, so the refreshed copy carries none.
721            *cache = refreshed;
722            let outcome = verify_recovery_secret(cache.blob(), passphrase, device_master);
723            tracing::debug!(?outcome, "retried verify against refreshed escrow");
724            Ok(outcome)
725        } else {
726            // The blob is genuinely current — this is a real failure.
727            tracing::debug!("escrow unchanged on refresh; recording a genuine failure");
728            Ok(VerifyOutcome::NotVerified)
729        }
730    }
731
732    /// Run the guided re-wrap (SSoT § On Repeated Failure): mint a fresh ≥128-bit
733    /// recovery secret, **re-wrap the same master key** under it, replace the server
734    /// escrow (single active — the old blob is deleted, so the lost secret unwraps
735    /// nothing), re-issue Shamir shares when enrolled, and surface the old-artifact
736    /// guidance when the store displaced an earlier escrow. Wrap rotation, not key
737    /// rotation: no data re-encryption, no blob-hash changes.
738    ///
739    /// After this succeeds, the caller should
740    /// [`rearm`](RecoveryCadence::rearm)`(now, RearmTrigger::SecretRotated)` its cadence
741    /// when [`GuidedRewrap::stored`] says it [replaced](EscrowStored::replaced) an escrow; a
742    /// store that replaced nothing is a first enrollment, which arms a fresh ladder with
743    /// [`RecoveryCadence::armed_at_setup`].
744    #[instrument(skip_all)]
745    pub async fn guided_rewrap(
746        &self,
747        device_master: &[u8; 32],
748        tier: DeviceTier,
749        shamir_enrolled: bool,
750    ) -> Result<GuidedRewrap, RecoveryError> {
751        self.guided_rewrap_with_params(device_master, tier.params(), shamir_enrolled)
752            .await
753    }
754
755    /// The [`guided_rewrap`](Self::guided_rewrap) body with explicit Argon2id parameters
756    /// — the seam tests drive with fast params so the crypto does not dominate a smoke.
757    #[instrument(skip_all)]
758    async fn guided_rewrap_with_params(
759        &self,
760        device_master: &[u8; 32],
761        params: Argon2Params,
762        shamir_enrolled: bool,
763    ) -> Result<GuidedRewrap, RecoveryError> {
764        let secret = MintedSecret::generate();
765
766        // Re-wrap the SAME master key under the fresh secret. `device_master` is an
767        // input, never rotated — the escrow is the only thing that changes.
768        let new_blob = pwkdf::wrap_with(device_master, secret.as_bytes(), params)
769            .map_err(|e| RecoveryError::Wrap(e.to_string()))?;
770
771        // Replace the server escrow (single active escrow — the old ciphertext is gone).
772        let stored = self.store_escrow(&new_blob).await?;
773        tracing::info!(
774            stored_at = %stored.stored_at,
775            replaced = stored.replaced,
776            "guided re-wrap: server escrow set to the new-secret wrap"
777        );
778
779        // Re-issue Shamir shares of the NEW seed when the account had them enrolled.
780        let shamir = shamir_enrolled.then(|| ShamirReissue {
781            shares: split_seed_2of3(secret.as_bytes()),
782            old_shares_invalidated: true,
783        });
784
785        Ok(GuidedRewrap {
786            secret,
787            new_escrow: EscrowCache::with_stored_at(new_blob, stored.stored_at),
788            stored,
789            shamir,
790            type_back_required: true,
791            old_artifact_guidance: stored.old_artifact_guidance(),
792        })
793    }
794}
795
796/// Map a `GET /v1/auth/escrow` refusal onto its typed variant.
797///
798/// One readable status table rather than a match buried in the request path. The *inner*
799/// match is exhaustive over the generated enum, so a status the document adds to this
800/// operation stops the build here; a new `rest::Error` **class** still falls through to
801/// [`wire_error`]'s catch-all.
802fn fetch_escrow_error(error: rest::Error<rest::FetchEscrowError>) -> RecoveryError {
803    if let Some(refusal) = upgrade_required_of(&error) {
804        return RecoveryError::UpgradeRequired(Box::new(refusal));
805    }
806    match error {
807        rest::Error::Api(response) => match response.into_inner() {
808            rest::FetchEscrowError::Status404(_) => RecoveryError::NotEnrolled,
809            // The protocol gate's malformed-handshake answer (issue #404): a read is admitted at
810            // any grammatical protocol date, so the only `400` this operation renders is a
811            // request whose handshake headers did not parse. Unreachable from this client — the
812            // transport always sends the build's own — and carried with its code rather than
813            // swallowed, so a caller that localizes codes still has the server's.
814            rest::FetchEscrowError::Status400(problem) => RecoveryError::Malformed {
815                code: Some(problem.code.clone()),
816                detail: detail(&problem),
817            },
818            rest::FetchEscrowError::Status401(problem)
819            | rest::FetchEscrowError::Status403(problem) => refused(&problem),
820            rest::FetchEscrowError::Status500(problem) => unavailable(&problem),
821            // Declared by the transport backstop and unreachable on a body-less `GET`; kept
822            // honest rather than folded into a class it does not belong to.
823            rest::FetchEscrowError::Status413(problem) => RecoveryError::Unexpected {
824                status: 413,
825                code: Some(problem.code.clone()),
826            },
827        },
828        other => wire_error(&other),
829    }
830}
831
832/// Map a `PUT /v1/auth/escrow` refusal onto its typed variant.
833fn store_escrow_error(error: rest::Error<rest::StoreEscrowError>) -> RecoveryError {
834    if let Some(refusal) = upgrade_required_of(&error) {
835        return RecoveryError::UpgradeRequired(Box::new(refusal));
836    }
837    match error {
838        rest::Error::Api(response) => match response.into_inner() {
839            // `400` and `415` are the same answer to the caller: these bytes are not an
840            // escrow, and sending them again will not help.
841            rest::StoreEscrowError::Status400(problem)
842            | rest::StoreEscrowError::Status415(problem) => RecoveryError::Malformed {
843                code: Some(problem.code.clone()),
844                detail: detail(&problem),
845            },
846            // Unreachable: every `426` is taken as `UpgradeRequired` above. Kept because the
847            // generated enum is matched exhaustively.
848            rest::StoreEscrowError::Status426(problem) => RecoveryError::Unexpected {
849                status: 426,
850                code: Some(problem.code.clone()),
851            },
852            rest::StoreEscrowError::Status401(problem)
853            | rest::StoreEscrowError::Status403(problem) => refused(&problem),
854            // A write that reached the server as TLS early data: re-sent later, it lands.
855            rest::StoreEscrowError::Status425(problem)
856            | rest::StoreEscrowError::Status500(problem) => unavailable(&problem),
857            // The body-size backstop carries no problem body at all, so there is no code to
858            // carry and this client does not invent one. Every other code in this module is
859            // the server's own, and a code minted here would assert that the server said
860            // something it did not — a client localizing it would be reading the SDK's guess
861            // as the server's judgement. The English detail says what happened instead; the
862            // variant already says "these bytes will not do, do not resend them".
863            rest::StoreEscrowError::Status413(problem) => RecoveryError::Malformed {
864                code: Some(problem.code.clone()),
865                detail: "the escrow blob exceeds the server's request-body limit".to_owned(),
866            },
867        },
868        other => wire_error(&other),
869    }
870}
871
872/// Map a `GET /v1/auth/escrow/identity` refusal onto its typed variant: the escrow fetch's
873/// table, except that the coded `404` is the sealed identity's own state.
874fn fetch_sealed_identity_error(
875    error: rest::Error<rest::FetchSealedIdentityError>,
876) -> RecoveryError {
877    if let Some(refusal) = upgrade_required_of(&error) {
878        return RecoveryError::UpgradeRequired(Box::new(refusal));
879    }
880    match error {
881        rest::Error::Api(response) => match response.into_inner() {
882            rest::FetchSealedIdentityError::Status404(_) => RecoveryError::IdentityNotStored,
883            rest::FetchSealedIdentityError::Status400(problem) => RecoveryError::Malformed {
884                code: Some(problem.code.clone()),
885                detail: detail(&problem),
886            },
887            rest::FetchSealedIdentityError::Status401(problem)
888            | rest::FetchSealedIdentityError::Status403(problem) => refused(&problem),
889            rest::FetchSealedIdentityError::Status500(problem) => unavailable(&problem),
890            rest::FetchSealedIdentityError::Status413(problem) => RecoveryError::Unexpected {
891                status: 413,
892                code: Some(problem.code.clone()),
893            },
894        },
895        other => wire_error(&other),
896    }
897}
898
899/// Map a `PUT /v1/auth/escrow/identity` refusal onto its typed variant — the escrow store's
900/// table, status for status.
901fn store_sealed_identity_error(
902    error: rest::Error<rest::StoreSealedIdentityError>,
903) -> RecoveryError {
904    if let Some(refusal) = upgrade_required_of(&error) {
905        return RecoveryError::UpgradeRequired(Box::new(refusal));
906    }
907    match error {
908        rest::Error::Api(response) => match response.into_inner() {
909            rest::StoreSealedIdentityError::Status400(problem)
910            | rest::StoreSealedIdentityError::Status415(problem) => RecoveryError::Malformed {
911                code: Some(problem.code.clone()),
912                detail: detail(&problem),
913            },
914            // Unreachable: every `426` is taken as `UpgradeRequired` above.
915            rest::StoreSealedIdentityError::Status426(problem) => RecoveryError::Unexpected {
916                status: 426,
917                code: Some(problem.code.clone()),
918            },
919            rest::StoreSealedIdentityError::Status401(problem)
920            | rest::StoreSealedIdentityError::Status403(problem) => refused(&problem),
921            rest::StoreSealedIdentityError::Status425(problem)
922            | rest::StoreSealedIdentityError::Status500(problem) => unavailable(&problem),
923            rest::StoreSealedIdentityError::Status413(problem) => RecoveryError::Malformed {
924                code: Some(problem.code.clone()),
925                detail: "the sealed identity exceeds the server's request-body limit".to_owned(),
926            },
927        },
928        other => wire_error(&other),
929    }
930}
931
932/// Read one entry of the album key listing: a UUID album id, a standard-base64 blob and an
933/// RFC 3339 `stored_at`, or [`RecoveryError::InvalidResponse`] naming the one that is not.
934fn read_escrowed_album_keys(
935    entry: rest::types::EscrowedAlbumKeys,
936) -> Result<EscrowedAlbumKeys, RecoveryError> {
937    let album_id = Uuid::parse_str(&entry.album_id).map_err(|error| {
938        RecoveryError::InvalidResponse(format!(
939            "album id {:?} is not a UUID: {error}",
940            entry.album_id
941        ))
942    })?;
943    let blob = BASE64_STANDARD.decode(&entry.blob).map_err(|error| {
944        RecoveryError::InvalidResponse(format!(
945            "album {album_id}'s key escrow is not standard base64: {error}"
946        ))
947    })?;
948    let stored_at = stored_instant(&entry.stored_at, "album key escrow")?;
949    Ok(EscrowedAlbumKeys {
950        album_id,
951        blob,
952        stored_at,
953    })
954}
955
956/// Map a `PUT /v1/auth/escrow/albums/{album_id}` refusal onto its typed variant — the escrow
957/// store's table, status for status.
958fn store_album_keys_error(error: rest::Error<rest::StoreAlbumKeysError>) -> RecoveryError {
959    if let Some(refusal) = upgrade_required_of(&error) {
960        return RecoveryError::UpgradeRequired(Box::new(refusal));
961    }
962    match error {
963        rest::Error::Api(response) => match response.into_inner() {
964            rest::StoreAlbumKeysError::Status400(problem)
965            | rest::StoreAlbumKeysError::Status415(problem) => RecoveryError::Malformed {
966                code: Some(problem.code.clone()),
967                detail: detail(&problem),
968            },
969            // Unreachable: every `426` is taken as `UpgradeRequired` above.
970            rest::StoreAlbumKeysError::Status426(problem) => RecoveryError::Unexpected {
971                status: 426,
972                code: Some(problem.code.clone()),
973            },
974            rest::StoreAlbumKeysError::Status409(problem) => RecoveryError::AlbumKeysFull {
975                code: Some(problem.code.clone()),
976                detail: detail(&problem),
977            },
978            rest::StoreAlbumKeysError::Status401(problem)
979            | rest::StoreAlbumKeysError::Status403(problem) => refused(&problem),
980            rest::StoreAlbumKeysError::Status425(problem)
981            | rest::StoreAlbumKeysError::Status500(problem) => unavailable(&problem),
982            rest::StoreAlbumKeysError::Status413(problem) => RecoveryError::Malformed {
983                code: Some(problem.code.clone()),
984                detail: "the album key escrow exceeds the server's request-body limit".to_owned(),
985            },
986        },
987        other => wire_error(&other),
988    }
989}
990
991/// Map a `GET /v1/auth/escrow/albums` refusal onto its typed variant: the escrow fetch's table,
992/// with no `404` — an account with no album escrowed lists none.
993fn list_album_keys_error(error: rest::Error<rest::ListAlbumKeysError>) -> RecoveryError {
994    if let Some(refusal) = upgrade_required_of(&error) {
995        return RecoveryError::UpgradeRequired(Box::new(refusal));
996    }
997    match error {
998        rest::Error::Api(response) => match response.into_inner() {
999            rest::ListAlbumKeysError::Status400(problem) => RecoveryError::Malformed {
1000                code: Some(problem.code.clone()),
1001                detail: detail(&problem),
1002            },
1003            rest::ListAlbumKeysError::Status401(problem)
1004            | rest::ListAlbumKeysError::Status403(problem) => refused(&problem),
1005            rest::ListAlbumKeysError::Status500(problem) => unavailable(&problem),
1006            rest::ListAlbumKeysError::Status413(problem) => RecoveryError::Unexpected {
1007                status: 413,
1008                code: Some(problem.code.clone()),
1009            },
1010        },
1011        other => wire_error(&other),
1012    }
1013}
1014
1015/// Read a success answer's `stored_at`, which the server renders as RFC 3339.
1016///
1017/// The server *did* answer `200`, so the blob may well be stored; an unreadable instant is the
1018/// answer being unreadable, which is [`RecoveryError::InvalidResponse`] rather than a refusal.
1019fn stored_instant(stored_at: &str, what: &str) -> Result<Timestamp, RecoveryError> {
1020    stored_at.parse::<Timestamp>().map_err(|error| {
1021        tracing::warn!(
1022            %stored_at,
1023            %error,
1024            what,
1025            "stored, but the server's stored_at is not an RFC 3339 instant"
1026        );
1027        RecoveryError::InvalidResponse(format!(
1028            "stored_at {stored_at:?} is not an RFC 3339 instant: {error}"
1029        ))
1030    })
1031}
1032
1033/// A refused credential, carrying the problem body's stable code. `CodedProblem.code` is a
1034/// required member, so a refusal that parsed always has one.
1035fn refused(problem: &rest::types::CodedProblem) -> RecoveryError {
1036    RecoveryError::Unauthorized {
1037        code: Some(problem.code.clone()),
1038        detail: detail(problem),
1039    }
1040}
1041
1042/// The store could not answer — transient, and the caller's cadence retries.
1043fn unavailable(problem: &rest::types::CodedProblem) -> RecoveryError {
1044    RecoveryError::Unavailable {
1045        code: Some(problem.code.clone()),
1046        detail: detail(problem),
1047    }
1048}
1049
1050/// The problem body's English detail, or its code when the server sent no detail.
1051fn detail(problem: &rest::types::CodedProblem) -> String {
1052    problem
1053        .detail
1054        .clone()
1055        .unwrap_or_else(|| problem.code.clone())
1056}
1057
1058/// Map the generated client's non-`Api` taxonomy classes: an undocumented status keeps its
1059/// number, and everything else is a wire failure with its source chain preserved.
1060fn wire_error<E>(error: &rest::Error<E>) -> RecoveryError
1061where
1062    E: std::error::Error + 'static,
1063{
1064    match error {
1065        rest::Error::UnexpectedStatus { status, .. } => RecoveryError::Unexpected {
1066            status: status.as_u16(),
1067            code: None,
1068        },
1069        // Reading `RequestConstruction` as an auth failure by class alone would report every
1070        // request the runtime could not assemble as "sign in again"; the shared classifier
1071        // reads the source instead, so only a dead session is one.
1072        rest::Error::RequestConstruction(_) if is_token_failure(error) => {
1073            RecoveryError::Unauthorized {
1074                code: None,
1075                detail: describe_error(error),
1076            }
1077        }
1078        // A *declared* refusal whose body was not the coded problem the document promises.
1079        // Deliberately a wire failure and not [`RecoveryError::NotEnrolled`], even though an
1080        // uncoded `404` is its commonest shape: reading any `404` as "this account has
1081        // escrowed nothing" is exactly what let a wrong route look like an empty escrow for a
1082        // whole slice. An intermediary answering `404 text/html` is a broken path, not an
1083        // enrollment state.
1084        rest::Error::Decode { path, .. } => RecoveryError::Transport(format!(
1085            "the escrow endpoint answered a refusal this client could not parse ({path})"
1086        )),
1087        other => RecoveryError::Transport(describe_error(other)),
1088    }
1089}
1090
1091#[cfg(test)]
1092mod tests;