# auth.recovery-codes Recovery (backup) codes for two-factor sign-in: the codes a user prints or saves when they turn on an authenticator app, and types in when the phone is lost. Four functions, all pure: - `generateRecoveryCodes(entropy, count)` turns the caller's random bytes into codes like `7h3k-q9mz-2bxa-v0pd`. Show them to the user once. - `hashRecoveryCode(code)` is what you store instead of each code. - `consumeRecoveryCode(code, hashes)` takes what the user typed and the stored hashes still unused, and answers whether it matched and the hashes to store from now on (the matched one removed). - `normaliseRecoveryCode(code)` is the one form a typed code is read in. ## Randomness comes from you The function never reads a random source, so it can be pinned by test vectors. Pass bytes from a cryptographically secure generator, 10 per code: `crypto.getRandomValues(new Uint8Array(100))` in TypeScript, `list(secrets.token_bytes(100))` in Python, `getrandom` in Rust. Never `Math.random` or Python's `random`. Bytes past `count * 10` are ignored. ## The codes Each code is 10 random bytes (80 bits) written as 16 characters of Crockford's base32 alphabet (`0-9` and `a-z` without `i`, `l`, `o` and `u`), in four groups of four. When a code is typed back, case, spaces and hyphens do not matter, and `i`/`l` are read as `1` and `o` as `0`, so a code copied by hand still works. Only ASCII is accepted: a full-width or other-script letter makes the code invalid in every language. ## Why a fast, unsalted hash is enough Passwords need a slow, salted hash (see `auth.password-hash`) because people choose guessable ones. These codes are not chosen: each is 80 bits from a CSPRNG, so even with the stored hashes in hand an attacker faces 2^80 SHA-256 guesses per code, which is out of reach. A salt would add nothing against that. The hash is SHA-256 of `fune.recovery-code:` followed by the normalised code, in lowercase hex; the prefix keeps these hashes apart from any other SHA-256 values the app stores. This holds only because the codes are random: do not use these functions for codes a person makes up. ## Consuming a code `consumeRecoveryCode` compares the attempt with every stored hash in constant time, with no early exit, so the time taken does not reveal which one matched. On a match, `remaining` is the stored list without that hash, in the same order; write it back in the same transaction that signs the user in, so a code works once even under two concurrent requests (use a row lock or a compare-and-set on the old list). A malformed code is `valid: false` with the list unchanged, not an error, since it is ordinary user input. A stored entry that is not 64 lowercase hex characters is an error: it means the stored data is corrupt. Rate-limit attempts as you would logins (`auth.login-throttle`). Ten codes is the usual set; let the user regenerate the whole set, which replaces the stored hashes.