Skip to main content

vault_core/
totp.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! RFC 6238 time-based one-time passwords.
4//!
5//! # Two callers, one generator
6//!
7//! Phase 19 added this module for **sub-user login**: UnENVerse checking a code
8//! its own user typed. Phase 22 added the mirror image — a TOTP seed the vault
9//! *stores on behalf of a third party*, the way Bitwarden and 1Password hold an
10//! authenticator entry, where UnENVerse produces the code and a website checks
11//! it.
12//!
13//! They share every line of arithmetic and deliberately nothing else. The login
14//! path is fixed at SHA-1/6 digits/30 seconds because that is what this product
15//! mints and there is no interoperability question; the stored-seed path is
16//! parameterised ([`Params`]) because the issuer chose those numbers years ago
17//! and a generator that cannot follow is a generator that produces confidently
18//! wrong codes. Only the login path has an anti-replay mark — see [`verify`] —
19//! because only the login path is a verifier.
20//!
21//! # Why this exists twice
22//!
23//! Phase 5.1 shipped a TOTP implementation and Phase 7 removed it, because
24//! nothing in the product ever reached it: there was no enrollment surface, no
25//! CLI verb and no UI, so the only thing the code did was carry a schema column.
26//! It comes back here with all three, and with the anti-replay rule that the
27//! original had — see [`verify`].
28//!
29//! # Sub-users only, deliberately
30//!
31//! The vault owner authenticates by deriving the SQLCipher key from the master
32//! password. There is no stored hash to check and therefore nothing for a second
33//! factor to gate: an attacker who can derive the key does not go through a login
34//! form, they open the file. Offering the owner a TOTP toggle would be a control
35//! that protects nothing while looking as though it protects everything.
36//!
37//! # No new crates
38//!
39//! `hmac` is already a dependency (`entropy.rs` builds HKDF on it), `sha1` is
40//! added for the one algorithm RFC 6238 pins for interoperability, and `sha2`
41//! was already here for the KDF — which is the whole cost of supporting the
42//! SHA-256 and SHA-512 variants a stored third-party seed may name. Base32 is
43//! forty lines and lives here rather than behind a crate, for the same reason
44//! HKDF does: the encoding is part of what a reader has to check.
45
46use hmac::{Hmac, KeyInit, Mac};
47use serde::{Deserialize, Serialize};
48use sha1::Sha1;
49use sha2::{Sha256, Sha512};
50use zeroize::Zeroizing;
51
52/// Digits in a generated code. Six is what every authenticator app assumes when
53/// the `otpauth://` URI omits the parameter, and omitting it is what keeps the
54/// QR-less manual-entry path working.
55pub const DIGITS: u32 = 6;
56
57/// Seconds per counter step. RFC 6238's recommended default.
58pub const STEP_SECS: u64 = 30;
59
60/// How many steps either side of the current one are accepted.
61///
62/// One step is 30 seconds, so a window of 1 tolerates a phone clock up to 30
63/// seconds out in either direction. Anything larger widens the replay window
64/// that [`verify`]'s `last_step` argument exists to close.
65pub const SKEW_STEPS: i64 = 1;
66
67/// Bytes of secret material. RFC 4226 requires at least 128 bits and recommends
68/// 160 — which is also the SHA-1 block output, so nothing is truncated.
69pub const SECRET_BYTES: usize = 20;
70
71type HmacSha1 = Hmac<Sha1>;
72type HmacSha256 = Hmac<Sha256>;
73type HmacSha512 = Hmac<Sha512>;
74
75/// Fewest digits a code may carry. RFC 4226 sets six as the floor.
76pub const MIN_DIGITS: u32 = 6;
77
78/// Most digits a code may carry.
79///
80/// Ten is where `u32` runs out: dynamic truncation yields a 31-bit number, so
81/// `10^10` already exceeds it and an eleventh digit would be a constant zero
82/// that looks like part of the code.
83pub const MAX_DIGITS: u32 = 10;
84
85/// Longest step a stored seed may name, in seconds.
86///
87/// An hour. Nothing real uses more, and the cap is what stops a pasted URI with
88/// `period=0` or `period=4294967295` from producing a division by zero or a
89/// code that never changes.
90pub const MAX_PERIOD_SECS: u64 = 3600;
91
92// ── Base32 (RFC 4648, no padding) ─────────────────────────────────────────────
93
94const B32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
95
96/// Encodes bytes as unpadded RFC 4648 base32.
97///
98/// Unpadded because `otpauth://` secrets are conventionally written without `=`,
99/// and several authenticators reject the padding rather than ignoring it.
100pub fn base32_encode(data: &[u8]) -> String {
101    let mut out = String::with_capacity(data.len().div_ceil(5) * 8);
102    let mut buffer: u32 = 0;
103    let mut bits: u32 = 0;
104    for &byte in data {
105        buffer = (buffer << 8) | u32::from(byte);
106        bits += 8;
107        while bits >= 5 {
108            bits -= 5;
109            out.push(char::from(B32_ALPHABET[((buffer >> bits) & 0x1f) as usize]));
110        }
111    }
112    if bits > 0 {
113        // Left-align the remaining bits in the final group, as RFC 4648 requires.
114        out.push(char::from(
115            B32_ALPHABET[((buffer << (5 - bits)) & 0x1f) as usize],
116        ));
117    }
118    out
119}
120
121/// Decodes unpadded (or padded) RFC 4648 base32, case-insensitively.
122///
123/// Spaces are stripped because this is what a human types back out of the
124/// grouped display the UI shows, and `=` is accepted because a user pasting a
125/// secret exported from somewhere else should not have to know the difference.
126pub fn base32_decode(s: &str) -> Result<Vec<u8>, String> {
127    let mut out = Vec::with_capacity(s.len() * 5 / 8);
128    let mut buffer: u32 = 0;
129    let mut bits: u32 = 0;
130    for ch in s.chars() {
131        if ch == '=' || ch.is_whitespace() || ch == '-' {
132            continue;
133        }
134        let up = ch.to_ascii_uppercase();
135        let val = B32_ALPHABET
136            .iter()
137            .position(|&c| c == up as u8)
138            .ok_or_else(|| format!("not base32: {ch:?}"))? as u32;
139        buffer = (buffer << 5) | val;
140        bits += 5;
141        if bits >= 8 {
142            bits -= 8;
143            out.push(((buffer >> bits) & 0xff) as u8);
144        }
145    }
146    Ok(out)
147}
148
149// ── Code generation ───────────────────────────────────────────────────────────
150
151/// HOTP (RFC 4226) for one counter value, SHA-1 and six digits.
152///
153/// The login path's shape. A stored third-party seed goes through
154/// [`hotp_with`], which is the same function with the two constants unpinned;
155/// this one stays because every caller in `users.rs` means exactly these
156/// numbers and spelling them out at each call site invites one of them to
157/// drift.
158pub fn hotp(secret: &[u8], counter: u64) -> String {
159    hotp_with(secret, counter, Algorithm::Sha1, DIGITS)
160}
161
162/// HOTP (RFC 4226) for one counter value, with the algorithm and digit count
163/// the issuer chose.
164///
165/// `digits` is clamped to [`MIN_DIGITS`]..=[`MAX_DIGITS`] rather than rejected:
166/// this is the innermost function and it is reached only through validated
167/// constructors, so a panic here would be a crash in a card renderer for a
168/// number a user typed. [`Params::validate`] is where a bad value is refused.
169pub fn hotp_with(secret: &[u8], counter: u64, algorithm: Algorithm, digits: u32) -> String {
170    // Dynamic truncation, RFC 4226 §5.3, over whichever digest the issuer picked.
171    // `new_from_slice` only fails for key lengths HMAC cannot take, and HMAC
172    // accepts any length, so none of these can fail in practice.
173    let digest: Vec<u8> = match algorithm {
174        Algorithm::Sha1 => {
175            let mut mac = HmacSha1::new_from_slice(secret).expect("HMAC accepts any key length");
176            mac.update(&counter.to_be_bytes());
177            mac.finalize().into_bytes().to_vec()
178        }
179        Algorithm::Sha256 => {
180            let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC accepts any key length");
181            mac.update(&counter.to_be_bytes());
182            mac.finalize().into_bytes().to_vec()
183        }
184        Algorithm::Sha512 => {
185            let mut mac = HmacSha512::new_from_slice(secret).expect("HMAC accepts any key length");
186            mac.update(&counter.to_be_bytes());
187            mac.finalize().into_bytes().to_vec()
188        }
189    };
190
191    let offset = (digest[digest.len() - 1] & 0x0f) as usize;
192    let binary = (u32::from(digest[offset]) & 0x7f) << 24
193        | u32::from(digest[offset + 1]) << 16
194        | u32::from(digest[offset + 2]) << 8
195        | u32::from(digest[offset + 3]);
196
197    let digits = digits.clamp(MIN_DIGITS, MAX_DIGITS);
198    let modulus = 10u32.pow(digits);
199    format!("{:0width$}", binary % modulus, width = digits as usize)
200}
201
202/// Steam Guard's five characters for one counter value.
203///
204/// The HMAC and the dynamic truncation are RFC 4226's, unchanged — see
205/// [`hotp_with`], whose first half this repeats. Only the rendering differs: the
206/// 31-bit value is written in base 26 over [`STEAM_ALPHABET`] instead of base 10.
207///
208/// Written out rather than folded into `hotp_with` because the two produce
209/// different *types* of answer from the same number, and a `digits`-shaped
210/// parameter that silently switched alphabets would be the kind of flag that
211/// gets passed wrongly once and then produces codes that look plausible.
212fn steam_with(secret: &[u8], counter: u64) -> String {
213    let mut mac = HmacSha1::new_from_slice(secret).expect("HMAC accepts any key length");
214    mac.update(&counter.to_be_bytes());
215    let digest = mac.finalize().into_bytes();
216
217    let offset = (digest[digest.len() - 1] & 0x0f) as usize;
218    let mut value = (u32::from(digest[offset]) & 0x7f) << 24
219        | u32::from(digest[offset + 1]) << 16
220        | u32::from(digest[offset + 2]) << 8
221        | u32::from(digest[offset + 3]);
222
223    let n = STEAM_ALPHABET.len() as u32;
224    let mut out = String::with_capacity(STEAM_DIGITS as usize);
225    for _ in 0..STEAM_DIGITS {
226        out.push(STEAM_ALPHABET[(value % n) as usize] as char);
227        value /= n;
228    }
229    out
230}
231
232/// The counter step for a Unix timestamp.
233pub fn step_at(unix_secs: u64) -> u64 {
234    unix_secs / STEP_SECS
235}
236
237/// Current Unix time in seconds.
238pub fn now_unix() -> u64 {
239    std::time::SystemTime::now()
240        .duration_since(std::time::UNIX_EPOCH)
241        .map(|d| d.as_secs())
242        .unwrap_or(0)
243}
244
245/// TOTP for a base32 secret at a given time. Exposed so a caller can show the
246/// user the code their authenticator should be showing — used by nothing that
247/// authenticates, only by diagnostics.
248pub fn totp_at(secret_b32: &str, unix_secs: u64) -> Result<String, String> {
249    let secret = base32_decode(secret_b32)?;
250    if secret.is_empty() {
251        return Err("empty TOTP secret".into());
252    }
253    Ok(hotp(&secret, step_at(unix_secs)))
254}
255
256// ── Verification ──────────────────────────────────────────────────────────────
257
258/// The outcome of checking a code, carrying the step that was accepted.
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub struct Accepted {
261    /// The counter step the code matched. The caller **must** persist this and
262    /// pass it back as `last_step` next time.
263    pub step: u64,
264}
265
266/// Verifies a code against a secret, refusing anything at or before `last_step`.
267///
268/// # The anti-replay rule is the whole point
269///
270/// A ±1-step skew window means any given code is valid for ninety seconds. Over
271/// a network that is ninety seconds in which an observed code can be replayed by
272/// whoever saw it — which for a second factor is the exact attack it exists to
273/// stop. Refusing a step that has already been accepted reduces that to a single
274/// use, and it is why every caller has to store what [`Accepted::step`] returns.
275///
276/// `last_step` of `None` means the factor has never been used.
277pub fn verify(secret_b32: &str, code: &str, last_step: Option<u64>, now: u64) -> Option<Accepted> {
278    let secret = base32_decode(secret_b32).ok()?;
279    if secret.is_empty() {
280        return None;
281    }
282    // Users type codes with a space in the middle because that is how phones
283    // display them.
284    let code: String = code.chars().filter(|c| c.is_ascii_digit()).collect();
285    if code.len() != DIGITS as usize {
286        return None;
287    }
288
289    let current = step_at(now) as i64;
290    for delta in -SKEW_STEPS..=SKEW_STEPS {
291        let step = current + delta;
292        if step < 0 {
293            continue;
294        }
295        let step = step as u64;
296        if let Some(last) = last_step {
297            if step <= last {
298                continue;
299            }
300        }
301        if constant_time_eq(hotp(&secret, step).as_bytes(), code.as_bytes()) {
302            return Some(Accepted { step });
303        }
304    }
305    None
306}
307
308/// Length-aware, branch-free byte comparison.
309///
310/// Codes are six digits, so a timing oracle here leaks very little — but the
311/// same reasoning retired the legacy SHA-256 password comparison in Phase 5.1,
312/// and writing the fast version in a file about authentication invites the next
313/// reader to copy it somewhere it matters.
314fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
315    if a.len() != b.len() {
316        return false;
317    }
318    let mut diff = 0u8;
319    for (x, y) in a.iter().zip(b.iter()) {
320        diff |= x ^ y;
321    }
322    diff == 0
323}
324
325// ── Enrollment ────────────────────────────────────────────────────────────────
326
327/// Generates a fresh base32 secret from the OS CSPRNG.
328pub fn generate_secret() -> String {
329    use rand::Rng;
330    let mut buf = [0u8; SECRET_BYTES];
331    rand::rng().fill_bytes(&mut buf);
332    base32_encode(&buf)
333}
334
335/// Builds the `otpauth://` URI an authenticator scans or imports.
336///
337/// The label is `issuer:account` and the `issuer` parameter repeats it, which is
338/// redundant by the spec and required in practice — several apps read only one
339/// of the two, and which one differs between them.
340pub fn otpauth_uri(issuer: &str, account: &str, secret_b32: &str) -> String {
341    format!(
342        "otpauth://totp/{}:{}?secret={}&issuer={}&algorithm=SHA1&digits={}&period={}",
343        pct(issuer),
344        pct(account),
345        secret_b32,
346        pct(issuer),
347        DIGITS,
348        STEP_SECS
349    )
350}
351
352/// Percent-encodes everything outside the unreserved set.
353///
354/// A username is user-supplied, so it reaches this function containing anything
355/// at all: a `?`, `&` or `#` in it would otherwise terminate the path and turn
356/// the rest of the username into query parameters of the caller's choosing.
357fn pct(s: &str) -> String {
358    let mut out = String::with_capacity(s.len());
359    for b in s.as_bytes() {
360        match b {
361            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
362                out.push(*b as char)
363            }
364            _ => out.push_str(&format!("%{b:02X}")),
365        }
366    }
367    out
368}
369
370/// Splits a secret into space-separated groups of four for manual entry.
371///
372/// The UI cannot render a QR code — the CSP does not allow the library that
373/// would draw one, and relaxing it to display a secret would be an odd trade —
374/// so the secret is typed by hand, and a 32-character unbroken string is typed
375/// wrong.
376pub fn grouped(secret_b32: &str) -> String {
377    secret_b32
378        .as_bytes()
379        .chunks(4)
380        .map(|c| String::from_utf8_lossy(c).to_string())
381        .collect::<Vec<_>>()
382        .join(" ")
383}
384
385// ── Stored third-party seeds (Phase 22) ───────────────────────────────────────
386//
387// Everything below serves the *other* caller: a seed the vault holds on behalf
388// of a website, from which UnENVerse produces a code the user types into that
389// website. Nothing here verifies anything, so nothing here has — or wants — the
390// anti-replay mark that `verify` above carries.
391
392/// The alphabet Steam Guard draws its five characters from.
393///
394/// Steam runs ordinary RFC 6238 arithmetic — SHA-1, a 30-second step — and then
395/// encodes the truncated value in base 26 instead of base 10. Nothing else about
396/// it differs, which is why it is a [`Kind`] rather than an [`Algorithm`]: the
397/// HMAC is the same, the rendering is not.
398pub const STEAM_ALPHABET: &[u8; 26] = b"23456789BCDFGHJKMNPQRTVWXY";
399
400/// How many characters a Steam code carries. Not configurable; Steam fixes it.
401pub const STEAM_DIGITS: u32 = 5;
402
403/// What a stored seed *is*, which decides what "the current code" means for it.
404///
405/// The three differ in where the counter comes from, not in the arithmetic:
406/// `Totp` divides the clock by the period, `Steam` does the same and renders the
407/// result in base 26, and `Hotp` has no clock at all and uses a number the vault
408/// stores and the user advances.
409///
410/// Phase 22 refused the last two by name. That refusal was right while nothing
411/// could store a counter — an `Hotp` entry with nowhere to keep its position
412/// shows a code that never changes and never works. Phase 22.2 gives it
413/// somewhere, so the refusal became a limitation instead of a safeguard.
414#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
415#[serde(rename_all = "lowercase")]
416pub enum Kind {
417    /// Time-based, RFC 6238. What an entry with no stored kind means.
418    #[default]
419    Totp,
420    /// Counter-based, RFC 4226. The counter lives on the entry.
421    Hotp,
422    /// Time-based like `Totp`, rendered in Steam's five-character alphabet.
423    Steam,
424}
425
426impl Kind {
427    /// The spelling stored on the entry and used in an `otpauth://` path.
428    pub fn as_str(self) -> &'static str {
429        match self {
430            Kind::Totp => "totp",
431            Kind::Hotp => "hotp",
432            Kind::Steam => "steam",
433        }
434    }
435
436    /// Reads that spelling, case-insensitively. `None` for anything else.
437    pub fn parse(raw: &str) -> Option<Self> {
438        match raw.trim().to_ascii_lowercase().as_str() {
439            "totp" => Some(Kind::Totp),
440            "hotp" => Some(Kind::Hotp),
441            "steam" => Some(Kind::Steam),
442            _ => None,
443        }
444    }
445
446    /// True when the code advances on its own, so a countdown means something.
447    ///
448    /// The UI asks this rather than comparing against `Kind::Hotp`: a card with
449    /// no clock must draw no countdown ring, and a card that draws one whose
450    /// number never moves is worse than one that draws none.
451    pub fn is_time_based(self) -> bool {
452        !matches!(self, Kind::Hotp)
453    }
454}
455
456/// The HMAC a stored seed names.
457///
458/// SHA-1 is the only value a login seed ever takes and the overwhelming
459/// majority of what issuers hand out. The other two exist because `otpauth://`
460/// can name them and a handful of issuers do: reading `algorithm=SHA256` and
461/// then generating SHA-1 codes produces six digits that are correct-looking,
462/// wrong, and give the user no way to tell which of the two ends is at fault.
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
464#[serde(rename_all = "UPPERCASE")]
465pub enum Algorithm {
466    #[default]
467    Sha1,
468    Sha256,
469    Sha512,
470}
471
472impl Algorithm {
473    /// The spelling `otpauth://` uses.
474    pub fn as_str(self) -> &'static str {
475        match self {
476            Algorithm::Sha1 => "SHA1",
477            Algorithm::Sha256 => "SHA256",
478            Algorithm::Sha512 => "SHA512",
479        }
480    }
481
482    /// Reads the spelling `otpauth://` uses, case- and dash-insensitively.
483    ///
484    /// `SHA-256` appears in real URIs even though the spec does not allow it.
485    /// Rejecting it would mean refusing a seed that every phone accepts.
486    pub fn parse(raw: &str) -> Option<Self> {
487        match raw.trim().to_ascii_uppercase().replace('-', "").as_str() {
488            "SHA1" => Some(Algorithm::Sha1),
489            "SHA256" => Some(Algorithm::Sha256),
490            "SHA512" => Some(Algorithm::Sha512),
491            _ => None,
492        }
493    }
494}
495
496/// The three numbers a stored seed is generated under.
497///
498/// Defaults are what an `otpauth://` URI means when it omits the parameter, and
499/// therefore what an entry that stores only a bare base32 seed means too.
500#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
501pub struct Params {
502    /// Time-based, counter-based or Steam. `#[serde(default)]` because every
503    /// entry written before Phase 22.2 has no such field and means `Totp`.
504    #[serde(default)]
505    pub kind: Kind,
506    pub algorithm: Algorithm,
507    pub digits: u32,
508    pub period: u64,
509    /// The next counter value an `Hotp` seed will use. Meaningless for the other
510    /// two kinds, and zero for them.
511    ///
512    /// It is *state*, not configuration — the only number in this struct that a
513    /// correct implementation writes back — which is why advancing it is an
514    /// explicit action rather than a side effect of reading a code. See
515    /// `advance` in `unv-app/src/totp_cmd.rs`.
516    #[serde(default)]
517    pub counter: u64,
518}
519
520impl Default for Params {
521    fn default() -> Self {
522        Params {
523            kind: Kind::Totp,
524            algorithm: Algorithm::Sha1,
525            digits: DIGITS,
526            period: STEP_SECS,
527            counter: 0,
528        }
529    }
530}
531
532impl Params {
533    /// The parameters an entry's four stored fields mean, with anything
534    /// unusable falling back to the `otpauth://` default.
535    ///
536    /// **This is the only place a vault's TOTP fields become `Params`.** They
537    /// were read three separate ways before — `unv totp code` clamped, `unv
538    /// totp ls` did not, and the IPC command did neither — so one entry
539    /// carrying `totp_digits: 99` listed as a 99-digit credential, produced six
540    /// digits when asked for a code, and returned an error rather than a code to
541    /// any caller of `entry_totp_code` that had not clamped first. Three
542    /// readings of one field is three answers.
543    ///
544    /// A vault is untrusted input (invariant 4): these fields arrive from an
545    /// imported backup or a remote server as readily as from this CLI, and the
546    /// unions are not enforced at rest. Falling back rather than refusing is
547    /// what an omitted `otpauth://` parameter already means, and it keeps a
548    /// single mistyped number from making the whole entry unreadable.
549    ///
550    /// The twin is `totpParamsOf` in `src/ts/totp.ts` — the form needs these
551    /// before anything is saved — and the two are pinned by the `params`
552    /// section of `tests/fixtures/parity/totp-seeds.json`.
553    pub fn from_fields(
554        kind: Option<&str>,
555        algorithm: Option<&str>,
556        digits: Option<u64>,
557        period: Option<u64>,
558        counter: Option<u64>,
559    ) -> Self {
560        let d = Params::default();
561        let kind = kind.and_then(Kind::parse).unwrap_or(d.kind);
562        Params {
563            kind,
564            algorithm: algorithm.and_then(Algorithm::parse).unwrap_or(d.algorithm),
565            digits: digits
566                .filter(|n| (u64::from(MIN_DIGITS)..=u64::from(MAX_DIGITS)).contains(n))
567                .map(|n| n as u32)
568                .unwrap_or(d.digits),
569            period: period
570                .filter(|p| *p > 0 && *p <= MAX_PERIOD_SECS)
571                .unwrap_or(d.period),
572            // A counter is only ever read for an `Hotp` seed. Carrying one on a
573            // time-based entry would be a number that looks like state and is
574            // never used, which is the kind of field a later reader trusts.
575            counter: if kind == Kind::Hotp {
576                counter.unwrap_or(0)
577            } else {
578                0
579            },
580        }
581        .steam_normalised()
582    }
583
584    /// Forces the values Steam fixes, so nothing downstream has to special-case
585    /// them.
586    ///
587    /// Steam issues one shape — SHA-1, five characters, a 30-second step — and an
588    /// import that carried `digits: 6` from a generic exporter would otherwise
589    /// produce six characters no Steam login accepts.
590    fn steam_normalised(mut self) -> Self {
591        if self.kind == Kind::Steam {
592            self.algorithm = Algorithm::Sha1;
593            self.digits = STEAM_DIGITS;
594            self.period = STEP_SECS;
595            self.counter = 0;
596        }
597        self
598    }
599
600    /// Refuses a combination that cannot produce a code, naming the field.
601    ///
602    /// Called at every boundary a number can enter through — the URI parser, the
603    /// CLI flags, the IPC command — rather than at the generator, so that a
604    /// `period` of zero is a message about the value the user typed instead of a
605    /// division by zero three frames deeper.
606    pub fn validate(&self) -> Result<(), String> {
607        // Steam fixes its own shape, so there is nothing here for a user to get
608        // wrong — and its five characters are below `MIN_DIGITS`, which the
609        // check below would otherwise refuse.
610        if self.kind == Kind::Steam {
611            return if self.digits == STEAM_DIGITS {
612                Ok(())
613            } else {
614                Err(format!(
615                    "a Steam code is always {STEAM_DIGITS} characters, got {}",
616                    self.digits
617                ))
618            };
619        }
620        if !(MIN_DIGITS..=MAX_DIGITS).contains(&self.digits) {
621            return Err(format!(
622                "digits must be between {MIN_DIGITS} and {MAX_DIGITS}, got {}",
623                self.digits
624            ));
625        }
626        // An `Hotp` seed has no clock, so its period is meaningless rather than
627        // wrong. It is still range-checked, because a stored zero would divide
628        // by zero the moment somebody converted the entry to time-based.
629        if self.period == 0 || self.period > MAX_PERIOD_SECS {
630            return Err(format!(
631                "period must be between 1 and {MAX_PERIOD_SECS} seconds, got {}",
632                self.period
633            ));
634        }
635        Ok(())
636    }
637
638    /// True when these are the values an `otpauth://` URI may omit.
639    ///
640    /// Used to keep the stored entry honest: writing `algorithm: "SHA1"` onto
641    /// every entry would make the field look chosen when it was defaulted, and
642    /// the UI would then have to distinguish "the issuer said SHA-1" from "we
643    /// wrote SHA-1 because nobody said anything". They are the same thing, so
644    /// the field is simply absent.
645    pub fn is_default(&self) -> bool {
646        *self == Params::default()
647    }
648}
649
650/// A parsed seed: the base32 secret plus everything the URI said about it.
651#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
652pub struct Stored {
653    /// Base32, uppercased, with the grouping spaces and any padding removed.
654    pub secret: String,
655    #[serde(flatten)]
656    pub params: Params,
657    /// The service, when the URI named one. Never overwrites an entry's
658    /// provider — see `unv-cli`'s `--totp` handling; it is offered, not applied.
659    pub issuer: Option<String>,
660    /// The account at that service, when the URI named one.
661    pub account: Option<String>,
662}
663
664impl Stored {
665    /// Rebuilds an `otpauth://` URI, for exporting the seed back to a phone.
666    ///
667    /// The URI **contains the secret**, so every caller of this is a
668    /// materialising path: it is refused to stdout without `--reveal`, exactly
669    /// as the seed itself is.
670    pub fn to_uri(&self, issuer_fallback: &str, account_fallback: &str) -> String {
671        let issuer = self.issuer.as_deref().unwrap_or(issuer_fallback);
672        let account = self.account.as_deref().unwrap_or(account_fallback);
673        let label = if issuer.is_empty() {
674            pct(account)
675        } else {
676            format!("{}:{}", pct(issuer), pct(account))
677        };
678        // Steam is written as `otpauth://totp/…&encoder=steam` rather than as
679        // `otpauth://steam/`: both spellings exist, Aegis reads either, and the
680        // `totp` path is the one every *other* authenticator will at least
681        // import as a working — if wrongly rendered — seed instead of rejecting
682        // the line outright.
683        let path = match self.params.kind {
684            Kind::Hotp => "hotp",
685            Kind::Totp | Kind::Steam => "totp",
686        };
687        let mut uri = format!("otpauth://{path}/{label}?secret={}", self.secret);
688        if !issuer.is_empty() {
689            uri.push_str(&format!("&issuer={}", pct(issuer)));
690        }
691        uri.push_str(&format!(
692            "&algorithm={}&digits={}",
693            self.params.algorithm.as_str(),
694            self.params.digits,
695        ));
696        match self.params.kind {
697            // A counter-based URI carries its position instead of a period. An
698            // exporter that dropped it would hand the next phone a seed starting
699            // from zero, which is a second factor that fails until it is resynced.
700            Kind::Hotp => uri.push_str(&format!("&counter={}", self.params.counter)),
701            Kind::Totp => uri.push_str(&format!("&period={}", self.params.period)),
702            Kind::Steam => uri.push_str(&format!("&period={}&encoder=steam", self.params.period)),
703        }
704        uri
705    }
706}
707
708/// Percent-decodes, leaving anything malformed alone.
709///
710/// A label that ends in a bare `%` is a typo in someone's export, not an attack,
711/// and dropping the whole seed over it helps nobody.
712fn pct_decode(s: &str) -> String {
713    let bytes = s.as_bytes();
714    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
715    let mut i = 0;
716    while i < bytes.len() {
717        if bytes[i] == b'%' && i + 2 < bytes.len() {
718            let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
719            if let Some(b) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
720                out.push(b);
721                i += 3;
722                continue;
723            }
724        }
725        // `+` is a form-encoding convention, not a URI one, but exports written
726        // by web tooling use it in the label and a literal plus in an account
727        // name is vanishingly rare next to a space that reads as one.
728        out.push(if bytes[i] == b'+' { b' ' } else { bytes[i] });
729        i += 1;
730    }
731    String::from_utf8_lossy(&out).into_owned()
732}
733
734/// Normalises a base32 secret: uppercase, no spaces, dashes or padding.
735///
736/// The value that reaches the vault, so that two entries holding the same seed
737/// typed differently are byte-identical and their fingerprints match.
738pub fn normalize_b32(raw: &str) -> String {
739    raw.chars()
740        .filter(|c| !c.is_whitespace() && *c != '-' && *c != '=')
741        .flat_map(|c| c.to_uppercase())
742        .collect()
743}
744
745/// Reads either a bare base32 seed or a full `otpauth://` URI.
746///
747/// One entry point because the form field, the CLI flag and the paste handler
748/// all accept whichever the user has to hand, and a user who pastes a URI into a
749/// box labelled "secret" is doing the reasonable thing.
750pub fn parse_seed(input: &str) -> Result<Stored, String> {
751    let trimmed = input.trim();
752    if trimmed.is_empty() {
753        return Err("empty TOTP secret".into());
754    }
755    if trimmed.len() >= 8 && trimmed[..8].eq_ignore_ascii_case("otpauth:") {
756        return parse_otpauth(trimmed);
757    }
758    let secret = normalize_b32(trimmed);
759    validate_secret(&secret)?;
760    Ok(Stored {
761        secret,
762        params: Params::default(),
763        issuer: None,
764        account: None,
765    })
766}
767
768/// Rejects a secret that cannot produce a code, before it is stored.
769///
770/// Storing an unusable seed is worse than refusing it: the entry then shows a
771/// code field that is permanently blank, and the user has no way to tell a
772/// mistyped secret from a bug.
773fn validate_secret(secret: &str) -> Result<(), String> {
774    if secret.is_empty() {
775        return Err("empty TOTP secret".into());
776    }
777    let bytes = Zeroizing::new(base32_decode(secret)?);
778    if bytes.is_empty() {
779        return Err("TOTP secret decodes to no bytes".into());
780    }
781    Ok(())
782}
783
784/// Parses an `otpauth://totp/...` URI.
785///
786/// Deliberately strict about the scheme and the type, and forgiving about
787/// everything else: an unknown query parameter is ignored, an unreadable
788/// `digits` falls back to the default rather than failing, and only a missing or
789/// unusable `secret` is fatal. A URI is pasted from a third party's export and
790/// half of them are slightly wrong.
791pub fn parse_otpauth(uri: &str) -> Result<Stored, String> {
792    let rest = uri
793        .get(..10)
794        .filter(|p| p.eq_ignore_ascii_case("otpauth://"))
795        .and_then(|_| uri.get(10..))
796        .ok_or("not an otpauth:// URI")?;
797
798    let (path, query) = match rest.split_once('?') {
799        Some((p, q)) => (p, q),
800        None => (rest, ""),
801    };
802    let (kind, label) = match path.split_once('/') {
803        Some((k, l)) => (k, l),
804        None => (path, ""),
805    };
806    // Phase 22 refused everything but `totp` here, because an `hotp` seed with
807    // nowhere to keep its counter shows a code that never changes. The entry can
808    // hold a counter now, so the three kinds are read and anything else is still
809    // refused by name.
810    let kind = Kind::parse(kind).ok_or_else(|| {
811        format!("only otpauth://totp/, //hotp/ and //steam/ are supported, got 'otpauth://{kind}/'")
812    })?;
813
814    let mut secret = String::new();
815    let mut issuer_param: Option<String> = None;
816    let mut params = Params {
817        kind,
818        ..Params::default()
819    };
820    for pair in query.split('&').filter(|p| !p.is_empty()) {
821        let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
822        match k.to_ascii_lowercase().as_str() {
823            "secret" => secret = normalize_b32(&pct_decode(v)),
824            "issuer" => {
825                let decoded = pct_decode(v);
826                if !decoded.trim().is_empty() {
827                    issuer_param = Some(decoded.trim().to_string());
828                }
829            }
830            "algorithm" => {
831                if let Some(a) = Algorithm::parse(&pct_decode(v)) {
832                    params.algorithm = a;
833                }
834            }
835            "digits" => {
836                if let Ok(d) = pct_decode(v).trim().parse::<u32>() {
837                    if (MIN_DIGITS..=MAX_DIGITS).contains(&d) {
838                        params.digits = d;
839                    }
840                }
841            }
842            // RFC 4226 calls this the "initial counter value"; every exporter
843            // writes the *next* value to use, which is what the entry stores.
844            "counter" => {
845                if let Ok(c) = pct_decode(v).trim().parse::<u64>() {
846                    params.counter = c;
847                }
848            }
849            // Aegis writes `encoder=steam` on an `otpauth://totp/` URI rather
850            // than using the `steam` path, so a seed exported from it would
851            // otherwise import as an ordinary six-digit TOTP and produce codes
852            // Steam rejects. Recognised by this parameter and by the path — never
853            // by the issuer *name*, which is text a user can edit into anything.
854            "encoder" if pct_decode(v).trim().eq_ignore_ascii_case("steam") => {
855                params.kind = Kind::Steam;
856            }
857            "period" => {
858                if let Ok(p) = pct_decode(v).trim().parse::<u64>() {
859                    if p > 0 && p <= MAX_PERIOD_SECS {
860                        params.period = p;
861                    }
862                }
863            }
864            _ => {}
865        }
866    }
867
868    validate_secret(&secret)?;
869    // `encoder=steam` can arrive after `digits=6`, and the `steam` path arrives
870    // before any parameter at all, so the shape Steam fixes is forced once the
871    // whole query has been read rather than in whichever arm saw it first.
872    params = params.steam_normalised();
873    params.validate()?;
874
875    // The label is `issuer:account`, and the `issuer` query parameter repeats
876    // it. Where the two disagree the parameter wins — it is the one an exporter
877    // writes deliberately, while the label half is often whatever the user typed
878    // into their phone years ago.
879    let label = pct_decode(label);
880    let (label_issuer, account) = match label.split_once(':') {
881        Some((i, a)) => (
882            Some(i.trim().to_string()).filter(|s| !s.is_empty()),
883            a.trim().to_string(),
884        ),
885        None => (None, label.trim().to_string()),
886    };
887
888    Ok(Stored {
889        secret,
890        params,
891        issuer: issuer_param.or(label_issuer),
892        account: Some(account).filter(|a| !a.is_empty()),
893    })
894}
895
896/// The counter a seed uses at a given moment.
897///
898/// The one place the three kinds differ before the arithmetic starts: two divide
899/// the clock, one ignores it entirely and reads the number the vault stored.
900fn counter_at(params: &Params, unix_secs: u64) -> u64 {
901    match params.kind {
902        Kind::Hotp => params.counter,
903        Kind::Totp | Kind::Steam => unix_secs / params.period.max(1),
904    }
905}
906
907/// The code a stored seed produces at a given time.
908///
909/// For an `Hotp` seed the time is ignored and `params.counter` is used, so this
910/// is still the single entry point for every kind and no caller has to know
911/// which it holds.
912pub fn code_at(secret_b32: &str, params: &Params, unix_secs: u64) -> Result<String, String> {
913    code_for_counter(secret_b32, params, counter_at(params, unix_secs))
914}
915
916/// The code for one explicit counter value.
917///
918/// Exposed because "the next code" is this function at `counter + 1`, and
919/// deriving it that way keeps one arithmetic path rather than two that must
920/// agree.
921pub fn code_for_counter(secret_b32: &str, params: &Params, counter: u64) -> Result<String, String> {
922    params.validate()?;
923    // Zeroized on drop: this is the decoded seed, and it is the one value in
924    // this function that would still be readable in a heap dump afterwards.
925    let secret = Zeroizing::new(base32_decode(secret_b32)?);
926    if secret.is_empty() {
927        return Err("empty TOTP secret".into());
928    }
929    Ok(match params.kind {
930        Kind::Steam => steam_with(&secret, counter),
931        Kind::Totp | Kind::Hotp => hotp_with(&secret, counter, params.algorithm, params.digits),
932    })
933}
934
935/// The code that replaces the current one.
936///
937/// For a time-based seed that is the next step; for an `Hotp` seed it is the
938/// next counter, which is the value the *service* will expect after this one is
939/// spent. Both are the same operation, which is the point.
940pub fn next_code_at(secret_b32: &str, params: &Params, unix_secs: u64) -> Result<String, String> {
941    code_for_counter(secret_b32, params, counter_at(params, unix_secs) + 1)
942}
943
944/// Seconds until the current code is replaced.
945///
946/// Zero is never returned: at the instant of a step boundary the *new* code has
947/// a full period ahead of it, and a countdown that reads 0 for one second in
948/// every period is a countdown users report as a bug.
949pub fn remaining_secs(period: u64, unix_secs: u64) -> u64 {
950    let period = period.clamp(1, MAX_PERIOD_SECS);
951    period - (unix_secs % period)
952}
953
954/// A code and how long it has left — the shape the desktop app and the CLI both
955/// render.
956#[derive(Debug, Clone, Serialize, Deserialize)]
957pub struct LiveCode {
958    pub code: String,
959    /// The code that replaces `code`, when the caller asked for it.
960    ///
961    /// Absent unless requested: it is a second live credential, and a panel that
962    /// always painted one would put two working codes in every screenshot.
963    #[serde(skip_serializing_if = "Option::is_none")]
964    pub next_code: Option<String>,
965    /// What produced it, so a renderer knows whether a countdown means anything.
966    pub kind: Kind,
967    /// The counter this code was generated at. For an `Hotp` seed it is the
968    /// entry's stored position, which is what the user is deciding whether to
969    /// advance.
970    pub counter: u64,
971    /// Seconds until `code` is replaced, or **0 for an `Hotp` seed**, which has
972    /// no clock and whose code is replaced only when somebody advances it.
973    pub remaining_secs: u64,
974    /// Echoed back so a caller can draw a countdown without re-deriving it from
975    /// the entry, and so a stale response is recognisable as stale.
976    pub period: u64,
977    pub digits: u32,
978    pub algorithm: Algorithm,
979}
980
981/// The code a stored seed produces right now, with its countdown.
982pub fn live_code(secret_b32: &str, params: &Params) -> Result<LiveCode, String> {
983    live_code_with(secret_b32, params, false)
984}
985
986/// The same, optionally carrying the code that comes next.
987///
988/// `with_next` is a parameter rather than always-on because the next code is a
989/// second working credential with a longer life than the one on screen: a
990/// screenshot of a panel showing both is good for up to two periods rather than
991/// one. The authenticator screen puts it behind a toggle and the CLI behind
992/// `--next`.
993pub fn live_code_with(
994    secret_b32: &str,
995    params: &Params,
996    with_next: bool,
997) -> Result<LiveCode, String> {
998    let now = now_unix();
999    Ok(LiveCode {
1000        code: code_at(secret_b32, params, now)?,
1001        next_code: if with_next {
1002            Some(next_code_at(secret_b32, params, now)?)
1003        } else {
1004            None
1005        },
1006        kind: params.kind,
1007        counter: counter_at(params, now),
1008        // An `Hotp` code is not replaced by the passage of time, and a countdown
1009        // that never moves reads as a frozen UI. Zero says "no clock" and the
1010        // renderer draws no ring.
1011        remaining_secs: if params.kind.is_time_based() {
1012            remaining_secs(params.period, now)
1013        } else {
1014            0
1015        },
1016        period: params.period,
1017        digits: params.digits,
1018        algorithm: params.algorithm,
1019    })
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024    use super::*;
1025
1026    #[test]
1027    fn base32_round_trips_every_remainder_length() {
1028        // The tail handling has a different shape for each input length mod 5,
1029        // and the left-align in the final group is the part that is easy to get
1030        // wrong — it is silent, and produces a secret an authenticator accepts
1031        // and then disagrees with.
1032        for n in 0..=16usize {
1033            let data: Vec<u8> = (0..n).map(|i| (i as u8).wrapping_mul(37)).collect();
1034            let enc = base32_encode(&data);
1035            assert!(
1036                enc.chars().all(|c| B32_ALPHABET.contains(&(c as u8))),
1037                "non-alphabet char in {enc}"
1038            );
1039            assert_eq!(
1040                base32_decode(&enc).unwrap(),
1041                data,
1042                "round trip failed at {n}"
1043            );
1044        }
1045    }
1046
1047    #[test]
1048    fn base32_matches_rfc_4648_vectors() {
1049        // Without a published vector this file could be self-consistently wrong,
1050        // and every authenticator on earth would disagree with it.
1051        for (input, expect) in [
1052            ("", ""),
1053            ("f", "MY"),
1054            ("fo", "MZXQ"),
1055            ("foo", "MZXW6"),
1056            ("foob", "MZXW6YQ"),
1057            ("fooba", "MZXW6YTB"),
1058            ("foobar", "MZXW6YTBOI"),
1059        ] {
1060            assert_eq!(
1061                base32_encode(input.as_bytes()),
1062                expect,
1063                "encoding {input:?}"
1064            );
1065        }
1066    }
1067
1068    #[test]
1069    fn hotp_matches_rfc_4226_vectors() {
1070        // RFC 4226 Appendix D, the ASCII secret "12345678901234567890".
1071        let secret = b"12345678901234567890";
1072        for (counter, expect) in [
1073            (0u64, "755224"),
1074            (1, "287082"),
1075            (2, "359152"),
1076            (3, "969429"),
1077            (4, "338314"),
1078            (5, "254676"),
1079            (6, "287922"),
1080            (7, "162583"),
1081            (8, "399871"),
1082            (9, "520489"),
1083        ] {
1084            assert_eq!(hotp(secret, counter), expect, "counter {counter}");
1085        }
1086    }
1087
1088    #[test]
1089    fn totp_matches_rfc_6238_sha1_vectors() {
1090        let secret = base32_encode(b"12345678901234567890");
1091        // RFC 6238 Appendix B, SHA-1 rows, truncated to our six digits.
1092        for (t, expect) in [
1093            (59u64, "287082"),
1094            (1111111109, "081804"),
1095            (1111111111, "050471"),
1096            (1234567890, "005924"),
1097            (2000000000, "279037"),
1098        ] {
1099            assert_eq!(totp_at(&secret, t).unwrap(), expect, "t={t}");
1100        }
1101    }
1102
1103    #[test]
1104    fn accepts_the_current_code_and_one_step_of_skew_either_way() {
1105        let secret = generate_secret();
1106        let now = 1_700_000_000u64;
1107        for offset in [-(STEP_SECS as i64), 0, STEP_SECS as i64] {
1108            let at = (now as i64 + offset) as u64;
1109            let code = totp_at(&secret, at).unwrap();
1110            assert!(
1111                verify(&secret, &code, None, now).is_some(),
1112                "offset {offset} should be inside the skew window"
1113            );
1114        }
1115        // Two steps out is outside the window.
1116        let far = totp_at(&secret, now + 2 * STEP_SECS).unwrap();
1117        assert!(verify(&secret, &far, None, now).is_none());
1118    }
1119
1120    #[test]
1121    fn refuses_a_code_whose_step_was_already_used() {
1122        // The replay this whole module exists to prevent: without the last_step
1123        // check, an observed code stays valid for the rest of its ninety-second
1124        // window and anyone who saw it can use it.
1125        let secret = generate_secret();
1126        let now = 1_700_000_000u64;
1127        let code = totp_at(&secret, now).unwrap();
1128
1129        let first = verify(&secret, &code, None, now).expect("first use accepted");
1130        assert_eq!(first.step, step_at(now));
1131        assert!(
1132            verify(&secret, &code, Some(first.step), now).is_none(),
1133            "the same code must not be accepted twice"
1134        );
1135        // And nor may the *earlier* code from the skew window, which is still
1136        // arithmetically valid but is a step the user has already moved past.
1137        let earlier = totp_at(&secret, now - STEP_SECS).unwrap();
1138        assert!(verify(&secret, &earlier, Some(first.step), now).is_none());
1139    }
1140
1141    #[test]
1142    fn tolerates_the_spacing_a_phone_displays() {
1143        let secret = generate_secret();
1144        let now = now_unix();
1145        let code = totp_at(&secret, now).unwrap();
1146        let spaced = format!("{} {}", &code[..3], &code[3..]);
1147        assert!(verify(&secret, &spaced, None, now).is_some());
1148    }
1149
1150    #[test]
1151    fn refuses_malformed_input_rather_than_panicking() {
1152        let secret = generate_secret();
1153        let now = now_unix();
1154        for bad in ["", "12345", "1234567", "abcdef", "!!!!!!"] {
1155            assert!(
1156                verify(&secret, bad, None, now).is_none(),
1157                "accepted {bad:?}"
1158            );
1159        }
1160        assert!(verify("not base32 ∅", "123456", None, now).is_none());
1161        assert!(verify("", "123456", None, now).is_none());
1162    }
1163
1164    #[test]
1165    fn otpauth_uri_escapes_a_username_that_would_break_the_query() {
1166        // A username is user-supplied. Unescaped, `a&issuer=Evil` would append a
1167        // parameter of the attacker's choosing to the URI a user is about to
1168        // paste into their authenticator.
1169        let uri = otpauth_uri("UnENVerse", "a&issuer=Evil?x=1", "ABCD");
1170        assert!(uri.contains("a%26issuer%3DEvil%3Fx%3D1"), "{uri}");
1171        assert_eq!(uri.matches("issuer=").count(), 1, "{uri}");
1172    }
1173
1174    #[test]
1175    fn grouped_secret_decodes_to_the_same_bytes_as_the_ungrouped_one() {
1176        // The UI shows the grouped form and users type it back with the spaces.
1177        let secret = generate_secret();
1178        assert_eq!(
1179            base32_decode(&grouped(&secret)).unwrap(),
1180            base32_decode(&secret).unwrap()
1181        );
1182    }
1183
1184    // ── Stored third-party seeds (Phase 22) ──────────────────────────────────
1185
1186    /// RFC 6238 Appendix B seeds. The three are different lengths on purpose:
1187    /// the spec's SHA-256 and SHA-512 vectors use 32- and 64-byte keys, and a
1188    /// generator that quietly truncated or padded would still match the SHA-1
1189    /// row and fail only for the users who have a SHA-512 seed.
1190    fn rfc6238_seed(algorithm: Algorithm) -> String {
1191        let ascii: &[u8] = match algorithm {
1192            Algorithm::Sha1 => b"12345678901234567890",
1193            Algorithm::Sha256 => b"12345678901234567890123456789012",
1194            Algorithm::Sha512 => {
1195                b"1234567890123456789012345678901234567890123456789012345678901234"
1196            }
1197        };
1198        base32_encode(ascii)
1199    }
1200
1201    #[test]
1202    fn code_at_matches_rfc_6238_for_all_three_algorithms() {
1203        // Without these the SHA-256 and SHA-512 arms could be self-consistently
1204        // wrong: they would produce six plausible digits that the issuer
1205        // rejects, and nothing in the app could tell the user which end was at
1206        // fault. Eight digits because that is the width the RFC tabulates —
1207        // which also exercises the non-default `digits`.
1208        let rows: [(u64, &str, &str, &str); 6] = [
1209            (59, "94287082", "46119246", "90693936"),
1210            (1111111109, "07081804", "68084774", "25091201"),
1211            (1111111111, "14050471", "67062674", "99943326"),
1212            (1234567890, "89005924", "91819424", "93441116"),
1213            (2000000000, "69279037", "90698825", "38618901"),
1214            (20000000000, "65353130", "77737706", "47863826"),
1215        ];
1216        for (t, sha1, sha256, sha512) in rows {
1217            for (algorithm, want) in [
1218                (Algorithm::Sha1, sha1),
1219                (Algorithm::Sha256, sha256),
1220                (Algorithm::Sha512, sha512),
1221            ] {
1222                let params = Params {
1223                    kind: Kind::Totp,
1224                    counter: 0,
1225                    algorithm,
1226                    digits: 8,
1227                    period: 30,
1228                };
1229                assert_eq!(
1230                    code_at(&rfc6238_seed(algorithm), &params, t).unwrap(),
1231                    want,
1232                    "{} at t={t}",
1233                    algorithm.as_str()
1234                );
1235            }
1236        }
1237    }
1238
1239    #[test]
1240    fn the_default_params_reproduce_the_login_paths_answer() {
1241        // `hotp` delegates to `hotp_with`, so the two must agree for every
1242        // secret or Phase 19's login would start failing the moment Phase 21
1243        // touched the generator.
1244        let secret = generate_secret();
1245        let now = 1_700_000_000u64;
1246        assert_eq!(
1247            code_at(&secret, &Params::default(), now).unwrap(),
1248            totp_at(&secret, now).unwrap()
1249        );
1250    }
1251
1252    #[test]
1253    fn a_bare_base32_seed_parses_with_the_omitted_defaults() {
1254        let stored = parse_seed("jbsw y3dp ehpk 3pxp").unwrap();
1255        // Normalised: the vault holds one spelling, so two entries carrying the
1256        // same seed typed differently fingerprint the same.
1257        assert_eq!(stored.secret, "JBSWY3DPEHPK3PXP");
1258        assert!(stored.params.is_default());
1259        assert_eq!(stored.issuer, None);
1260        assert_eq!(stored.account, None);
1261    }
1262
1263    #[test]
1264    fn an_otpauth_uri_parses_label_issuer_and_every_parameter() {
1265        let stored = parse_seed(
1266            "otpauth://totp/GitHub:darth%40example.com?secret=JBSWY3DPEHPK3PXP\
1267             &issuer=GitHub&algorithm=SHA256&digits=8&period=60",
1268        )
1269        .unwrap();
1270        assert_eq!(stored.secret, "JBSWY3DPEHPK3PXP");
1271        assert_eq!(stored.params.algorithm, Algorithm::Sha256);
1272        assert_eq!(stored.params.digits, 8);
1273        assert_eq!(stored.params.period, 60);
1274        assert_eq!(stored.issuer.as_deref(), Some("GitHub"));
1275        assert_eq!(stored.account.as_deref(), Some("darth@example.com"));
1276    }
1277
1278    #[test]
1279    fn the_issuer_parameter_beats_the_label_when_they_disagree() {
1280        // The label half is often years-old text a user typed into a phone; the
1281        // parameter is what an exporter wrote deliberately.
1282        let stored =
1283            parse_seed("otpauth://totp/Stale:me?secret=JBSWY3DPEHPK3PXP&issuer=Current").unwrap();
1284        assert_eq!(stored.issuer.as_deref(), Some("Current"));
1285        assert_eq!(stored.account.as_deref(), Some("me"));
1286    }
1287
1288    #[test]
1289    fn a_uri_with_no_secret_is_refused_rather_than_stored_unusable() {
1290        // Storing it would give the entry a code field that is permanently
1291        // blank, with nothing on screen distinguishing that from a bug.
1292        assert!(parse_seed("otpauth://totp/Acme:me?issuer=Acme").is_err());
1293        assert!(parse_seed("otpauth://totp/Acme:me?secret=").is_err());
1294        assert!(parse_seed("otpauth://totp/Acme:me?secret=!!!!").is_err());
1295    }
1296
1297    #[test]
1298    fn a_counter_based_uri_keeps_its_counter() {
1299        // Phase 22 refused this by name, because an `hotp` seed with nowhere to
1300        // keep its position produces a card whose code never changes. The entry
1301        // holds a counter now (Phase 22.2), so the URI is read — and the counter
1302        // is the half that must survive: an `hotp` seed imported at zero is a
1303        // second factor that fails until the account is resynced.
1304        let stored = parse_seed("otpauth://hotp/Acme:me?secret=JBSWY3DPEHPK3PXP&counter=7")
1305            .expect("hotp is read");
1306        assert_eq!(stored.params.kind, Kind::Hotp);
1307        assert_eq!(stored.params.counter, 7);
1308        assert!(!stored.params.kind.is_time_based());
1309
1310        // A scheme nothing here implements is still refused, and still by name.
1311        let err = parse_seed("otpauth://yubico/Acme:me?secret=JBSWY3DPEHPK3PXP")
1312            .expect_err("an unknown type must be refused");
1313        assert!(err.contains("yubico"), "{err}");
1314    }
1315
1316    #[test]
1317    fn a_counter_based_code_ignores_the_clock_and_advances_only_with_its_counter() {
1318        // The whole difference between the two kinds, asserted directly: time
1319        // moves and the code does not; the counter moves and it does.
1320        let p = Params {
1321            kind: Kind::Hotp,
1322            counter: 3,
1323            ..Params::default()
1324        };
1325        let at_zero = code_at("JBSWY3DPEHPK3PXP", &p, 0).unwrap();
1326        let much_later = code_at("JBSWY3DPEHPK3PXP", &p, 5_000_000).unwrap();
1327        assert_eq!(at_zero, much_later, "an hotp code must not move with time");
1328
1329        let next = Params { counter: 4, ..p };
1330        assert_ne!(at_zero, code_at("JBSWY3DPEHPK3PXP", &next, 0).unwrap());
1331        // And "the next code" is exactly the next counter, not the next step.
1332        assert_eq!(
1333            next_code_at("JBSWY3DPEHPK3PXP", &p, 0).unwrap(),
1334            code_at("JBSWY3DPEHPK3PXP", &next, 0).unwrap()
1335        );
1336        // No clock means no countdown; a ring that never moves reads as a
1337        // frozen UI, so the renderer is told there is nothing to draw.
1338        assert_eq!(live_code("JBSWY3DPEHPK3PXP", &p).unwrap().remaining_secs, 0);
1339    }
1340
1341    #[test]
1342    fn steam_matches_an_independent_implementation() {
1343        // Steam publishes no test vectors, so these were computed by a separate
1344        // implementation written from the algorithm description and checked
1345        // against this one at a pinned step — not by running this code twice.
1346        // Without fixed vectors the only check available is "the two agree
1347        // right now", which passes for two identical mistakes.
1348        let p = Params {
1349            kind: Kind::Steam,
1350            ..Params::default()
1351        }
1352        .steam_normalised();
1353        for (counter, want) in [(0u64, "VH8YJ"), (1, "2YXGV"), (59_636_971, "5TC5V")] {
1354            assert_eq!(
1355                code_for_counter("JBSWY3DPEHPK3PXP", &p, counter).unwrap(),
1356                want,
1357                "steam code at counter {counter}"
1358            );
1359        }
1360        // The same seed at the same counter under the ordinary renderer is a
1361        // different answer, which is the whole reason `Kind` exists.
1362        assert_ne!(
1363            code_for_counter("JBSWY3DPEHPK3PXP", &Params::default(), 0).unwrap(),
1364            "VH8YJ"
1365        );
1366    }
1367
1368    #[test]
1369    fn a_steam_seed_produces_five_characters_from_steams_alphabet() {
1370        let p = Params {
1371            kind: Kind::Steam,
1372            ..Params::default()
1373        }
1374        .steam_normalised();
1375        let code = code_at("JBSWY3DPEHPK3PXP", &p, 0).unwrap();
1376        assert_eq!(code.len(), STEAM_DIGITS as usize, "{code}");
1377        for c in code.chars() {
1378            assert!(
1379                STEAM_ALPHABET.contains(&(c as u8)),
1380                "{c} is not in Steam's alphabet"
1381            );
1382        }
1383        // Same HMAC underneath: it is the rendering that differs, which is why
1384        // this is a `Kind` and not an `Algorithm`.
1385        assert_ne!(code, hotp(&base32_decode("JBSWY3DPEHPK3PXP").unwrap(), 0));
1386        // It moves with the clock like any time-based seed.
1387        assert_ne!(code, code_at("JBSWY3DPEHPK3PXP", &p, 30).unwrap());
1388    }
1389
1390    #[test]
1391    fn steam_forces_its_own_shape_whatever_the_file_said() {
1392        // A generic exporter writes `digits: 6` beside a Steam seed. Six
1393        // characters is not something Steam accepts, and `MIN_DIGITS` would
1394        // otherwise refuse the five it does.
1395        let p = Params::from_fields(Some("steam"), Some("SHA512"), Some(8), Some(60), Some(9));
1396        assert_eq!(p.digits, STEAM_DIGITS);
1397        assert_eq!(p.algorithm, Algorithm::Sha1);
1398        assert_eq!(p.period, STEP_SECS);
1399        assert_eq!(p.counter, 0, "a time-based seed carries no counter");
1400        p.validate().expect("steam's own shape must validate");
1401
1402        // Aegis writes the encoder as a parameter on a `totp` URI rather than
1403        // using the `steam` path, and the parameter can arrive after `digits`.
1404        let stored =
1405            parse_seed("otpauth://totp/Steam:me?secret=JBSWY3DPEHPK3PXP&digits=6&encoder=steam")
1406                .expect("aegis's spelling is read");
1407        assert_eq!(stored.params.kind, Kind::Steam);
1408        assert_eq!(stored.params.digits, STEAM_DIGITS);
1409    }
1410
1411    #[test]
1412    fn every_kind_round_trips_through_its_uri() {
1413        for (kind, counter) in [(Kind::Totp, 0), (Kind::Hotp, 42), (Kind::Steam, 0)] {
1414            let stored = Stored {
1415                secret: "JBSWY3DPEHPK3PXP".into(),
1416                params: Params {
1417                    kind,
1418                    counter,
1419                    ..Params::default()
1420                }
1421                .steam_normalised(),
1422                issuer: Some("Acme".into()),
1423                account: Some("me".into()),
1424            };
1425            let back = parse_seed(&stored.to_uri("", "")).expect("its own URI parses");
1426            assert_eq!(back.params.kind, kind, "kind for {kind:?}");
1427            assert_eq!(back.params.counter, counter, "counter for {kind:?}");
1428            assert_eq!(back.secret, stored.secret);
1429        }
1430    }
1431
1432    #[test]
1433    fn nonsense_parameters_fall_back_to_the_defaults_instead_of_failing() {
1434        // Half of the URIs people paste come out of someone else's export and
1435        // are slightly wrong. Losing the seed over an unreadable `digits` is a
1436        // worse outcome than generating six digits.
1437        let stored = parse_seed(
1438            "otpauth://totp/Acme:me?secret=JBSWY3DPEHPK3PXP&digits=nine&period=0\
1439             &algorithm=WHIRLPOOL&unknown=1",
1440        )
1441        .unwrap();
1442        assert!(stored.params.is_default());
1443    }
1444
1445    #[test]
1446    fn a_lowercase_scheme_and_a_sha_dash_256_still_parse() {
1447        let stored =
1448            parse_seed("OTPAUTH://TOTP/Acme:me?secret=jbswy3dpehpk3pxp&algorithm=sha-256").unwrap();
1449        assert_eq!(stored.secret, "JBSWY3DPEHPK3PXP");
1450        assert_eq!(stored.params.algorithm, Algorithm::Sha256);
1451    }
1452
1453    #[test]
1454    fn to_uri_round_trips_through_the_parser() {
1455        // The exported URI is what a user scans into a replacement phone. One
1456        // that does not read back is a lockout discovered at the worst moment.
1457        let original = parse_seed(
1458            "otpauth://totp/Acme%20Corp:d%40e.com?secret=JBSWY3DPEHPK3PXP\
1459             &issuer=Acme%20Corp&algorithm=SHA512&digits=7&period=45",
1460        )
1461        .unwrap();
1462        let round = parse_seed(&original.to_uri("", "")).unwrap();
1463        assert_eq!(round, original);
1464    }
1465
1466    #[test]
1467    fn to_uri_falls_back_to_the_entrys_own_names_and_escapes_them() {
1468        // The fallbacks are the entry's provider and account, which are vault
1469        // data and therefore untrusted (CLAUDE.md invariant 4). Unescaped,
1470        // `a&issuer=Evil` would append a parameter of the writer's choosing.
1471        let stored = parse_seed("JBSWY3DPEHPK3PXP").unwrap();
1472        let uri = stored.to_uri("Acme", "a&issuer=Evil");
1473        assert!(uri.contains("a%26issuer%3DEvil"), "{uri}");
1474        assert_eq!(uri.matches("issuer=").count(), 1, "{uri}");
1475        assert_eq!(parse_seed(&uri).unwrap().secret, stored.secret);
1476    }
1477
1478    #[test]
1479    fn remaining_secs_counts_down_a_full_period_and_never_reaches_zero() {
1480        // A countdown that reads 0 for one second in every period gets reported
1481        // as a bug; at a step boundary the *new* code has a full period ahead.
1482        assert_eq!(remaining_secs(30, 0), 30);
1483        assert_eq!(remaining_secs(30, 1), 29);
1484        assert_eq!(remaining_secs(30, 29), 1);
1485        assert_eq!(remaining_secs(30, 30), 30);
1486        assert_eq!(remaining_secs(60, 119), 1);
1487        // A period of zero cannot divide; the clamp is what stops a malformed
1488        // stored entry from panicking a card renderer.
1489        assert_eq!(remaining_secs(0, 12345), 1);
1490    }
1491
1492    #[test]
1493    fn params_refuse_the_values_that_cannot_produce_a_code() {
1494        for bad in [
1495            Params {
1496                digits: 5,
1497                ..Default::default()
1498            },
1499            Params {
1500                digits: 11,
1501                ..Default::default()
1502            },
1503            Params {
1504                period: 0,
1505                ..Default::default()
1506            },
1507            Params {
1508                period: MAX_PERIOD_SECS + 1,
1509                ..Default::default()
1510            },
1511        ] {
1512            assert!(bad.validate().is_err(), "{bad:?} should be refused");
1513            assert!(code_at("JBSWY3DPEHPK3PXP", &bad, 0).is_err());
1514        }
1515        assert!(Params::default().validate().is_ok());
1516    }
1517
1518    #[test]
1519    fn live_code_agrees_with_code_at_and_its_own_countdown() {
1520        let stored = parse_seed("JBSWY3DPEHPK3PXP").unwrap();
1521        let live = live_code(&stored.secret, &stored.params).unwrap();
1522        assert_eq!(live.code.len(), stored.params.digits as usize);
1523        assert!(live.remaining_secs >= 1 && live.remaining_secs <= live.period);
1524        // The code is the one for the step the countdown belongs to. Deriving
1525        // them from two different `now` readings is how a card shows a code that
1526        // expires a second later.
1527        let step_start = now_unix() + live.remaining_secs - live.period;
1528        assert_eq!(
1529            code_at(&stored.secret, &stored.params, step_start).unwrap(),
1530            live.code
1531        );
1532    }
1533}