capsule_sdk/recovery/cadence.rs
1//! The recovery-verification **cadence scheduler** and the **prompt state machine**
2//! the client UX renders (SSoT: [Backup — Recovery Verification
3//! Cadence]).
4//!
5//! This half of the recovery verification is deliberately **pure and network-free**: every method
6//! takes the current wall-clock instant as an argument, so the whole ladder — the 7 d → 90 d → 180
7//! d back-off, the re-arm triggers, the snooze caps, and the repeated-failure escalation to a
8//! guided re-wrap — is driven by a mocked clock in tests with no sleeps and no I/O. The scheduler
9//! is `serde`-serializable so a client persists it across launches.
10//!
11//! **Advisory by construction.** The scheduler exposes exactly one read surface —
12//! [`RecoveryCadence::state`] — returning a [`VerificationState`] the UX renders. There
13//! is no method anywhere that gates sync, unlock, or any critical flow;
14//! [`VerificationState::blocks_critical_flow`] is `const false` for every variant, so the
15//! "never blocks" rule is a compile-time property, not a convention.
16//!
17//! [Backup — Recovery Verification Cadence]: https://docs/design/backup-recovery/#recovery-verification-cadence
18
19use capsule_core::notify::RecoveryFacts;
20use jiff::Timestamp;
21use serde::{Deserialize, Serialize};
22
23/// One day, in seconds — the unit the whole ladder is expressed in.
24const DAY_SECS: i64 = 86_400;
25
26/// First prompt lands **7 days** after setup: catches the lost-napkin case while
27/// re-setup is still cheap.
28pub const INITIAL_INTERVAL_SECS: i64 = 7 * DAY_SECS;
29/// After the first success the interval steps to **90 days**.
30pub const BACKOFF_INTERVAL_SECS: i64 = 90 * DAY_SECS;
31/// After two consecutive successes the interval caps at **180 days** and stays there.
32pub const CAP_INTERVAL_SECS: i64 = 180 * DAY_SECS;
33
34/// At most this many consecutive snoozes before the prompt degrades to a persistent,
35/// non-blocking [`VerificationState::Badge`].
36pub const MAX_CONSECUTIVE_SNOOZES: u8 = 3;
37
38/// Failures required before the guided re-wrap is offered — **and** they must span at
39/// least [`REWRAP_MIN_SESSIONS`] distinct app sessions, so a single fat-fingered
40/// session never triggers a rotation.
41pub const REWRAP_FAILURE_THRESHOLD: u32 = 3;
42/// The re-wrap escalation requires failures across at least this many app sessions.
43pub const REWRAP_MIN_SESSIONS: u32 = 2;
44
45/// How long a user may defer a due prompt. The check is advisory, so a snooze only
46/// moves the next reminder — it never suppresses anything critical.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48pub enum SnoozeDuration {
49 /// Remind again in 24 hours.
50 OneDay,
51 /// Remind again in 7 days.
52 OneWeek,
53}
54
55impl SnoozeDuration {
56 /// The snooze length in seconds.
57 #[must_use]
58 pub const fn secs(self) -> i64 {
59 match self {
60 Self::OneDay => DAY_SECS,
61 Self::OneWeek => 7 * DAY_SECS,
62 }
63 }
64}
65
66/// A reason to reset the ladder back to the 7-day step (SSoT § Schedule and Triggers).
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68pub enum RearmTrigger {
69 /// A new device enrolled — the prompt lands on the *new* device, which has never
70 /// seen the passphrase.
71 DeviceEnrolled,
72 /// The recovery secret rotated: an escrow store that
73 /// [replaced](crate::recovery::EscrowStored::replaced) an earlier one, e.g. a guided
74 /// re-wrap. A store that replaced nothing is a first enrollment, which is
75 /// [`RecoveryCadence::armed_at_setup`], not a re-arm.
76 SecretRotated,
77 /// A restore-from-escrow completed on this device.
78 RestoredFromEscrow,
79}
80
81/// The state the client UX renders. This is the entire consumer contract of the
82/// scheduler — pure data, never a localized string, and never a gate.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
84pub enum VerificationState {
85 /// The secret was last verified and the next prompt is scheduled for `next_due`.
86 /// Nothing to show now.
87 Verified {
88 /// When the next verification prompt becomes due.
89 next_due: Timestamp,
90 },
91 /// A verification prompt is due now.
92 Due,
93 /// The user snoozed; the prompt is suppressed until `until`. `snoozes_used` of the
94 /// [`MAX_CONSECUTIVE_SNOOZES`] budget have been consumed.
95 Snoozed {
96 /// When the snooze expires and the prompt becomes due again.
97 until: Timestamp,
98 /// Consecutive snoozes consumed so far.
99 snoozes_used: u8,
100 },
101 /// The snooze budget is exhausted: a persistent, **non-blocking** badge remains
102 /// until the user verifies. Not a lock — advisory only.
103 Badge,
104 /// Repeated failures (≥ [`REWRAP_FAILURE_THRESHOLD`] across ≥ [`REWRAP_MIN_SESSIONS`]
105 /// app sessions) or an explicit "I lost it": the client should run the guided
106 /// re-wrap flow ([`crate::recovery::RecoveryClient::guided_rewrap`]).
107 RewrapDue,
108}
109
110impl VerificationState {
111 /// The verification cadence is advisory by design. **No** state — not even
112 /// [`Badge`](Self::Badge) or [`RewrapDue`](Self::RewrapDue) — ever blocks sync,
113 /// unlock, or any critical flow. This is `const false` for every variant so the
114 /// "never blocks" invariant is enforced by the type, not by discipline.
115 #[must_use]
116 pub const fn blocks_critical_flow(self) -> bool {
117 false
118 }
119}
120
121/// The persistent recovery-verification scheduler for one account on one device.
122///
123/// Construct it at setup with [`RecoveryCadence::armed_at_setup`]; drive it with
124/// [`record_success`](Self::record_success), [`record_failure`](Self::record_failure),
125/// [`snooze`](Self::snooze), [`rearm`](Self::rearm), and [`declare_lost`](Self::declare_lost);
126/// render [`state`](Self::state) at `now`. All time arguments are explicit, so the whole
127/// machine is deterministic under a mocked clock.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
129pub struct RecoveryCadence {
130 /// When the next verification prompt is due.
131 next_due: Timestamp,
132 /// Consecutive successful verifications (drives the ladder; capped in effect at 2).
133 consecutive_successes: u32,
134 /// Consecutive snoozes since the last verification.
135 snoozes_used: u8,
136 /// When the active snooze expires, if any.
137 snoozed_until: Option<Timestamp>,
138 /// Total failures since the last success.
139 failures: u32,
140 /// Distinct app sessions in which a failure was recorded since the last success.
141 distinct_failure_sessions: u32,
142 /// The app-session id of the most recent failure, to count *distinct* sessions.
143 last_failure_session: Option<u64>,
144 /// The user explicitly declared the secret lost — jump straight to re-wrap.
145 declared_lost: bool,
146}
147
148impl RecoveryCadence {
149 /// Arm the ladder at account setup: the first prompt lands 7 days out.
150 #[must_use]
151 pub fn armed_at_setup(now: Timestamp) -> Self {
152 Self {
153 next_due: add_secs(now, INITIAL_INTERVAL_SECS),
154 consecutive_successes: 0,
155 snoozes_used: 0,
156 snoozed_until: None,
157 failures: 0,
158 distinct_failure_sessions: 0,
159 last_failure_session: None,
160 declared_lost: false,
161 }
162 }
163
164 /// The interval to the next prompt given the number of consecutive successes so
165 /// far: 7 d for the initial check, 90 d after one success, 180 d (capped) after two.
166 #[must_use]
167 pub const fn interval_for(consecutive_successes: u32) -> i64 {
168 match consecutive_successes {
169 0 => INITIAL_INTERVAL_SECS,
170 1 => BACKOFF_INTERVAL_SECS,
171 _ => CAP_INTERVAL_SECS,
172 }
173 }
174
175 /// When the next prompt is currently scheduled.
176 #[must_use]
177 pub const fn next_due(&self) -> Timestamp {
178 self.next_due
179 }
180
181 /// Whether the repeated-failure (or explicit-loss) re-wrap threshold has tripped.
182 #[must_use]
183 pub const fn rewrap_due(&self) -> bool {
184 self.declared_lost
185 || (self.failures >= REWRAP_FAILURE_THRESHOLD
186 && self.distinct_failure_sessions >= REWRAP_MIN_SESSIONS)
187 }
188
189 /// The state the UX should render at `now`.
190 #[must_use]
191 pub fn state(&self, now: Timestamp) -> VerificationState {
192 // Repeated failure / explicit loss dominates: the user needs a new secret.
193 if self.rewrap_due() {
194 return VerificationState::RewrapDue;
195 }
196 // An active snooze suppresses the prompt until it expires.
197 if let Some(until) = self.snoozed_until
198 && now < until
199 {
200 return VerificationState::Snoozed {
201 until,
202 snoozes_used: self.snoozes_used,
203 };
204 }
205 // Due yet?
206 if now >= self.next_due {
207 if self.snoozes_used >= MAX_CONSECUTIVE_SNOOZES {
208 // Snooze budget spent → persistent, non-blocking badge.
209 return VerificationState::Badge;
210 }
211 return VerificationState::Due;
212 }
213 VerificationState::Verified {
214 next_due: self.next_due,
215 }
216 }
217
218 /// Record a successful verification: advance the ladder, and clear the snooze and
219 /// failure counters (a success re-arms the "consecutive" accounting).
220 pub fn record_success(&mut self, now: Timestamp) {
221 self.consecutive_successes = self.consecutive_successes.saturating_add(1);
222 self.snoozes_used = 0;
223 self.snoozed_until = None;
224 self.failures = 0;
225 self.distinct_failure_sessions = 0;
226 self.last_failure_session = None;
227 self.declared_lost = false;
228 self.next_due = add_secs(now, Self::interval_for(self.consecutive_successes));
229 }
230
231 /// Record a failed verification during app session `session`. A failure keeps the
232 /// prompt due (it does not reschedule), but once
233 /// [`REWRAP_FAILURE_THRESHOLD`] failures span [`REWRAP_MIN_SESSIONS`] distinct
234 /// sessions the state escalates to [`VerificationState::RewrapDue`]. Returns the
235 /// state at `now` for the caller's convenience.
236 pub fn record_failure(&mut self, now: Timestamp, session: u64) -> VerificationState {
237 self.failures = self.failures.saturating_add(1);
238 if self.last_failure_session != Some(session) {
239 self.distinct_failure_sessions = self.distinct_failure_sessions.saturating_add(1);
240 self.last_failure_session = Some(session);
241 }
242 self.state(now)
243 }
244
245 /// Snooze a due prompt. Permitted up to [`MAX_CONSECUTIVE_SNOOZES`] times; the
246 /// `N+1`-th request is a no-op that leaves the prompt in the persistent
247 /// [`VerificationState::Badge`] state. Returns the resulting state.
248 pub fn snooze(&mut self, now: Timestamp, dur: SnoozeDuration) -> VerificationState {
249 if self.snoozes_used >= MAX_CONSECUTIVE_SNOOZES {
250 // Budget exhausted: no further deferral — the badge stands.
251 self.snoozed_until = None;
252 return self.state(now);
253 }
254 self.snoozes_used = self.snoozes_used.saturating_add(1);
255 self.snoozed_until = Some(add_secs(now, dur.secs()));
256 self.state(now)
257 }
258
259 /// Re-arm the ladder back to the 7-day step (new device, secret rotation, or a
260 /// completed restore-from-escrow), clearing snoozes and failures.
261 pub fn rearm(&mut self, now: Timestamp, _trigger: RearmTrigger) {
262 self.consecutive_successes = 0;
263 self.snoozes_used = 0;
264 self.snoozed_until = None;
265 self.failures = 0;
266 self.distinct_failure_sessions = 0;
267 self.last_failure_session = None;
268 self.declared_lost = false;
269 self.next_due = add_secs(now, INITIAL_INTERVAL_SECS);
270 }
271
272 /// The user explicitly said "I lost it": escalate straight to the guided re-wrap.
273 pub fn declare_lost(&mut self) {
274 self.declared_lost = true;
275 }
276
277 /// Project the scheduler into the flat facts the shared alert predicate consumes
278 /// ([`capsule_core::notify`]).
279 ///
280 /// The direction matters: `capsule-sdk` depends on `capsule-core` and never the reverse, so
281 /// the predicate cannot read this scheduler. It is handed a projection instead, and this is
282 /// the only place that mapping exists — the ladder, the re-arm triggers, and the snooze
283 /// accounting stay owned here, and `capsule_core::notify` never recomputes them.
284 ///
285 /// It is derived from [`state`](Self::state) rather than from the fields, so the alert and
286 /// the prompt the UX renders can never disagree about whether a check is due. Two mappings
287 /// are worth stating:
288 ///
289 /// - [`VerificationState::Badge`] reports `snooze_budget_spent`, which is what stops the
290 /// alert being pre-armed as a notification while leaving the condition reported — the
291 /// badge is persistent and non-blocking, and never escalates back into an alert.
292 /// - [`VerificationState::RewrapDue`] is due **now**, whatever the ladder says: repeated
293 /// failure or an explicit "I lost it" is not a scheduled check. The alert class set is
294 /// closed, so `recovery_check_due` is the only class that can carry it — which is why the
295 /// escalation also rides [`RecoveryFacts::rewrap_due`], surfacing as the alert's
296 /// `recovery` parameter. Without it the alert would be byte-identical to the routine
297 /// ninety-day check, and the client could not know to route into
298 /// [`RecoveryClient::guided_rewrap`](crate::recovery::RecoveryClient::guided_rewrap)
299 /// rather than a plain verification prompt.
300 #[must_use]
301 pub fn notify_facts(&self, now: Timestamp) -> RecoveryFacts {
302 match self.state(now) {
303 VerificationState::Verified { next_due } => RecoveryFacts {
304 next_due,
305 snoozed_until: None,
306 snooze_budget_spent: false,
307 rewrap_due: false,
308 },
309 VerificationState::Due => RecoveryFacts {
310 next_due: self.next_due,
311 snoozed_until: None,
312 snooze_budget_spent: false,
313 rewrap_due: false,
314 },
315 VerificationState::Snoozed {
316 until,
317 snoozes_used,
318 } => RecoveryFacts {
319 next_due: self.next_due,
320 snoozed_until: Some(until),
321 snooze_budget_spent: snoozes_used >= MAX_CONSECUTIVE_SNOOZES,
322 rewrap_due: false,
323 },
324 VerificationState::Badge => RecoveryFacts {
325 next_due: self.next_due,
326 snoozed_until: None,
327 snooze_budget_spent: true,
328 rewrap_due: false,
329 },
330 VerificationState::RewrapDue => RecoveryFacts {
331 next_due: now,
332 snoozed_until: None,
333 snooze_budget_spent: false,
334 rewrap_due: true,
335 },
336 }
337 }
338}
339
340/// Add a signed second offset to a timestamp, saturating at the representable bounds
341/// (the scheduler never operates near them; saturation just keeps the API total).
342fn add_secs(base: Timestamp, secs: i64) -> Timestamp {
343 let target = base.as_second().saturating_add(secs);
344 Timestamp::from_second(target).unwrap_or(if target < 0 {
345 Timestamp::MIN
346 } else {
347 Timestamp::MAX
348 })
349}
350
351#[cfg(test)]
352mod tests;