auth.recovery-codes
Two-factor recovery codes: generate from caller entropy, hash for storage, and verify-and-consume as a pure step.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 39 tests, run in TypeScript, Python and Rust.generateRecoveryCodes 11 · normaliseRecoveryCode 9 · hashRecoveryCode 8 · consumeRecoveryCode 11
What it does
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.
The functions
A group: 4 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.
- generate_recovery_codes (entropy: int[], count: int) -> string[]
- normalise_recovery_code (code: string) -> string?
- hash_recovery_code (code: string) -> string
- consume_recovery_code (code: string, hashes: string[]) -> RecoveryCheck
The type it declares, generated into your project
@dataclass(frozen=True)
class RecoveryCheck:
"""The answer to one recovery-code attempt, with the new stored set."""
#: the code matched one of the stored hashes
valid: bool
#: which stored hash it matched, when valid
index: Optional[int]
#: the hashes to store now: the matched one removed, order kept
remaining: List[str]
Once installed, your code imports each one from the group's module.
generate_recovery_codes throws on bad input 11 tests
def generate_recovery_codes(entropy: Sequence[int], count: int) -> List[str]
| entropy | int[] | random bytes from a CSPRNG, at least 10 per code; extra bytes are ignored |
| count | int | how many codes, 1 to 50 (10 is usual) |
| returns | string[] | codes like 7h3k-q9mz-2bxa-v0pd, to show the user once and never store |
For example
generate_recovery_codes(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1)→ 000g-40r4-0m30-e209 one code from bytes 0..9: 80 bits as 16 Crockford charactersgenerate_recovery_codes(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)→ 0000-0000-0000-0000 all zero bytes are all zerosgenerate_recovery_codes(255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1)→ zzzz-zzzz-zzzz-zzzz all 0xff bytes are the last letter throughout
from fune.auth.recovery_codes import generate_recovery_codes # auth.recovery-codes@^1
from typing import List, Sequence
# Crockford's base32 alphabet, lower case: no i, l, o or u to misread.
RECOVERY_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"
_BYTES_PER_CODE = 10
def generate_recovery_codes(entropy: Sequence[int], count: int) -> List[str]:
"""Recovery codes from the caller's random bytes, 10 bytes (80 bits) each,
as 16 Crockford base32 characters in four groups. Pass bytes from a CSPRNG
(secrets.token_bytes), never the random module."""
if isinstance(entropy, (str, dict)) or not hasattr(entropy, "__len__"):
raise TypeError("entropy must be a list of integers from 0 to 255")
for b in entropy:
if type(b) is not int or b < 0 or b > 255:
raise ValueError("entropy must be a list of integers from 0 to 255")
if type(count) is not int or count < 1 or count > 50:
raise ValueError("count must be a whole number from 1 to 50")
needed = count * _BYTES_PER_CODE
if len(entropy) < needed:
raise ValueError(
"entropy must hold at least 10 bytes per code: %d needed, %d given" % (needed, len(entropy))
)
codes = []
for c in range(count):
chars = []
buffer = 0
bits = 0
for i in range(_BYTES_PER_CODE):
buffer = ((buffer << 8) | entropy[c * _BYTES_PER_CODE + i]) & 0xFFFF
bits += 8
while bits >= 5:
bits -= 5
chars.append(RECOVERY_ALPHABET[(buffer >> bits) & 31])
s = "".join(chars)
codes.append("%s-%s-%s-%s" % (s[0:4], s[4:8], s[8:12], s[12:16]))
return codesnormalise_recovery_code 9 tests
def normalise_recovery_code(code: str) -> Optional[str]
| code | string | a code as the user typed it: any case, with or without hyphens and spaces |
| returns | string? | the 16 characters with i and l read as 1 and o as 0; null if it cannot be a code |
For example
normalise_recovery_code(vtpv-xvr1-4d2p-f2db)→ vtpvxvr14d2pf2db a generated code loses its hyphensnormalise_recovery_code( VTPV XVR1 4D2P F2DB )→ vtpvxvr14d2pf2db upper case and spaces as typednormalise_recovery_code(IL0O-abcd-efgh-jkmn)→ 1100abcdefghjkmn i and l read as 1, o read as 0
from fune.auth.recovery_codes import normalise_recovery_code # auth.recovery-codes@^1
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from typing import Optional
from .auth_recovery_codes_generate_recovery_codes import RECOVERY_ALPHABET ← generateRecoveryCodes, another function of this group · built into the same file, even by a slim install
def normalise_recovery_code(code: str) -> Optional[str]:
"""A typed code in its one stored form: ASCII lower case, spaces and
hyphens dropped, i/l read as 1 and o as 0 (Crockford). None when what is
left is not exactly 16 characters of the alphabet."""
if not isinstance(code, str):
raise TypeError("code must be a string")
out = []
for ch in code:
if ch == " " or ch == "-":
continue
# ASCII only: str.lower() would also fold letters from other scripts.
if "A" <= ch <= "Z":
ch = chr(ord(ch) + 32)
if ch == "i" or ch == "l":
ch = "1"
elif ch == "o":
ch = "0"
if ch not in RECOVERY_ALPHABET:
return None
out.append(ch)
return "".join(out) if len(out) == 16 else Nonehash_recovery_code throws on bad input 8 tests
def hash_recovery_code(code: str) -> str
| code | string | a code as generated or as typed |
| returns | string | the lowercase hex SHA-256 to store in place of the code |
For example
hash_recovery_code(vtpv-xvr1-4d2p-f2db)→ ea9c4071abd35fa50aa34307961d4a3f2fb25f307daa10c1f78ce462ca3bb6e1 the stored hash of a generated codehash_recovery_code(VTPV XVR1 4D2P F2DB)→ ea9c4071abd35fa50aa34307961d4a3f2fb25f307daa10c1f78ce462ca3bb6e1 typed differently, the same hashhash_recovery_code(0000-0000-0000-0000)→ 90a768aff01cf5e1d699927179a2c82455a9428eca6669681709a10660672071 all zeros
from fune.auth.recovery_codes import hash_recovery_code # auth.recovery-codes@^1
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from .auth_recovery_codes_normalise_recovery_code import normalise_recovery_code ← normaliseRecoveryCode, another function of this group · built into the same file, even by a slim install
from .crypto_sha256 import sha256 ← from crypto.sha256 ^1.0.0 · built alongside by fune
from .encoding_hex_hex_encode import hex_encode
from .encoding_utf8_utf8_encode import utf8_encode
def hash_recovery_code(code: str) -> str:
"""The hex SHA-256 of "fune.recovery-code:" and the normalised code: what
to store. A fast unsalted hash is enough because each code carries 80
random bits."""
normal = normalise_recovery_code(code)
if normal is None:
raise ValueError("not a recovery code")
return hex_encode(sha256(utf8_encode("fune.recovery-code:" + normal)))consume_recovery_code throws on bad input 11 tests
def consume_recovery_code(code: str, hashes: Sequence[str]) -> RecoveryCheck
| code | string | what the user typed |
| hashes | string[] | the user's stored hashes still unused |
| returns | RecoveryCheck | whether it matched, and the hashes to store from now on |
For example
consume_recovery_code(000g-40r4-0m30-e209, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c38…)→ valid true, index 0, remaining d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c3877d2d3dccdade4ecc8bf1581eadc97ded65bd0 the first code matches and is removedconsume_recovery_code(185G R38E 1W81 24GK, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c38…)→ valid true, index 1, remaining 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, b80588adecc76b1a8269a92c3877d2d3dccdade4ecc8bf1581eadc97ded65bd0 the middle code, typed in capitals with spacesconsume_recovery_code(2gah-c5rr-34d1-p70x, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c38…)→ valid true, index 2, remaining 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605 the last code leaves the first two
from fune.auth.recovery_codes import consume_recovery_code # auth.recovery-codes@^1
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import re
from typing import Sequence
from .auth_recovery_codes_hash_recovery_code import hash_recovery_code ← hashRecoveryCode, another function of this group · built into the same file, even by a slim install
from .auth_recovery_codes_normalise_recovery_code import normalise_recovery_code ← normaliseRecoveryCode, another function of this group · built into the same file, even by a slim install
from .auth_recovery_codes_types import RecoveryCheck
from .crypto_constant_time_equal import constant_time_equal ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
from .encoding_hex_hex_decode import hex_decode
_HASH = re.compile(r"[0-9a-f]{64}")
def consume_recovery_code(code: str, hashes: Sequence[str]) -> RecoveryCheck:
"""One recovery-code attempt as a pure state change: the stored hashes in,
whether the code matched and the hashes to store from now on out. Every
stored hash is compared in constant time, with no early exit."""
if isinstance(hashes, (str, dict)) or not hasattr(hashes, "__len__"):
raise TypeError("hashes must be a list of 64 lowercase hex characters each")
for h in hashes:
if not isinstance(h, str) or not _HASH.fullmatch(h):
raise ValueError("hashes must be a list of 64 lowercase hex characters each")
if normalise_recovery_code(code) is None:
return RecoveryCheck(valid=False, index=None, remaining=list(hashes))
attempt = hex_decode(hash_recovery_code(code))
index = -1
for i, h in enumerate(hashes):
same = constant_time_equal(attempt, hex_decode(h))
if same and index < 0:
index = i
if index < 0:
return RecoveryCheck(valid=False, index=None, remaining=list(hashes))
return RecoveryCheck(valid=True, index=index, remaining=[h for i, h in enumerate(hashes) if i != index])Install
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add auth.recovery-codes
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add auth.recovery-codes --only generateRecoveryCodes
The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./auth.recovery-codes-1.0.0-python.fune, or fetch it from a terminal with fune pull auth.recovery-codes@1.0.0:python.
The whole function, every language, is one file too: auth.recovery-codes-1.0.0.fune, 38,449 bytes, sha256 6ef8fcb7816b0dd00c753cfcdb1a93ee97b78be5f3118ec3641e47f3a77f011b. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
# fune: before auth.recovery-codes.generateRecoveryCodes
# fune: before auth.recovery-codes.normaliseRecoveryCode
# fune: before auth.recovery-codes.hashRecoveryCode
# fune: before auth.recovery-codes.consumeRecoveryCode
after — your function gets the result and the arguments, and returns the final result.
# fune: after auth.recovery-codes.generateRecoveryCodes
# fune: after auth.recovery-codes.normaliseRecoveryCode
# fune: after auth.recovery-codes.hashRecoveryCode
# fune: after auth.recovery-codes.consumeRecoveryCode
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
# fune: replace crypto.constant-time-equal in auth.recovery-codes
# fune: replace crypto.sha256 in auth.recovery-codes
# fune: replace encoding.hex in auth.recovery-codes
# fune: replace encoding.utf8 in auth.recovery-codes
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.recovery-codes --steps.
# fune: step auth.recovery-codes.<fn> after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
generateRecoveryCodes 11 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| one code from bytes 0..9: 80 bits as 16 Crockford characters | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 | → | 000g-40r4-0m30-e209 |
| all zero bytes are all zeros | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 | → | 0000-0000-0000-0000 |
| all 0xff bytes are the last letter throughout | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1 | → | zzzz-zzzz-zzzz-zzzz |
| three codes take consecutive 10-byte slices in order | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3 | → | 000g-40r4-0m30-e209, 185g-r38e-1w81-24gk, 2gah-c5rr-34d1-p70x |
| extra entropy past count*10 bytes is ignored | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2 | → | 000g-40r4-0m30-e209, 185g-r38e-1w81-24gk |
| a mixed byte pattern | 222, 173, 190, 239, 1, 35, 69, 103, 137, 171, 1 | → | vtpv-xvr1-4d2p-f2db |
| too few bytes for the count | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2 | → | error: entropy must hold at least 10 bytes per code: 20 needed, 19 given |
| a count of 0 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 | → | error: count must be a whole number from 1 to 50 |
| a count over 50 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 4… | → | error: count must be a whole number from 1 to 50 |
| a byte over 255 | 256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 | → | error: entropy must be a list of integers from 0 to 255 |
Show the other 1 test
| Case | Arguments | Expected | |
|---|---|---|---|
| a negative byte | -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 | → | error: entropy must be a list of integers from 0 to 255 |
normaliseRecoveryCode 9 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a generated code loses its hyphens | vtpv-xvr1-4d2p-f2db | → | vtpvxvr14d2pf2db |
| upper case and spaces as typed | VTPV XVR1 4D2P F2DB | → | vtpvxvr14d2pf2db |
| i and l read as 1, o read as 0 | IL0O-abcd-efgh-jkmn | → | 1100abcdefghjkmn |
| u is not in the alphabet | uuuu-abcd-efgh-jkmn | → | — |
| 15 characters is too short | abcd-efgh-jkmn-pqr | → | — |
| 17 characters is too long | abcd-efgh-jkmn-pqrst | → | — |
| the empty string | → | — | |
| a full-width letter is not ASCII and is refused | abcd-efgh-jkmn-pqrs | → | — |
| a trailing newline is not whitespace we drop | abcd-efgh-jkmn-pqrs | → | — |
hashRecoveryCode 8 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the stored hash of a generated code | vtpv-xvr1-4d2p-f2db | → | ea9c4071abd35fa50aa34307961d4a3f2fb25f307daa10c1f78ce462ca3bb6e1 |
| typed differently, the same hash | VTPV XVR1 4D2P F2DB | → | ea9c4071abd35fa50aa34307961d4a3f2fb25f307daa10c1f78ce462ca3bb6e1 |
| all zeros | 0000-0000-0000-0000 | → | 90a768aff01cf5e1d699927179a2c82455a9428eca6669681709a10660672071 |
| o and l typed for 0 and 1 hash as the digits | oooo-llll-0000-1111 | → | 84e30ba19fdce78656ac4fcaffe366f58a528c5739becb836ea1745575477ff4 |
| the code from bytes 0..9 | 000g-40r4-0m30-e209 | → | 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497 |
| a code of the wrong length | abcd-efgh | → | error: not a recovery code |
| a code with u in it | uuuu-abcd-efgh-jkmn | → | error: not a recovery code |
| the empty string | → | error: not a recovery code |
consumeRecoveryCode 11 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the first code matches and is removed | 000g-40r4-0m30-e209, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c38… | → | valid true, index 0, remaining d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c3877d2d3dccdade4ecc8bf1581eadc97ded65bd0 |
| the middle code, typed in capitals with spaces | 185G R38E 1W81 24GK, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c38… | → | valid true, index 1, remaining 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, b80588adecc76b1a8269a92c3877d2d3dccdade4ecc8bf1581eadc97ded65bd0 |
| the last code leaves the first two | 2gah-c5rr-34d1-p70x, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c38… | → | valid true, index 2, remaining 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605 |
| a code already used is not in the set | 000g-40r4-0m30-e209, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c3877d2d3dccdade4ecc8bf1581eadc97ded65bd0 | → | valid false, index —, remaining d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c3877d2d3dccdade4ecc8bf1581eadc97ded65bd0 |
| the last remaining code empties the set | 2gah-c5rr-34d1-p70x, b80588adecc76b1a8269a92c3877d2d3dccdade4ecc8bf1581eadc97ded65bd0 | → | valid true, index 0, remaining |
| no codes left | 000g-40r4-0m30-e209, | → | valid false, index —, remaining |
| a malformed code is refused, not thrown | not-a-code, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1a8269a92c3877d2d3dcc… | → | valid false, index —, remaining 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, b80588adecc76b1… |
| a duplicate stored hash: only the first is consumed | 185g-r38e-1w81-24gk, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605, d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605 | → | valid true, index 0, remaining d6f24e147c01ca863e9fdc7b35bef9398eadd1bafd254fd933fc8dcb6d4ba605 |
| a stored hash in upper case is refused | 000g-40r4-0m30-e209, 02734A8CB7D9E671C0E80B3EEE14DC9AD421B0BB87D15A6FEF52F8F121AAB497 | → | error: hashes must be a list of 64 lowercase hex characters each |
| a stored hash of the wrong length is refused | 000g-40r4-0m30-e209, abc | → | error: hashes must be a list of 64 lowercase hex characters each |
Show the other 1 test
| Case | Arguments | Expected | |
|---|---|---|---|
| a stored hash with a trailing newline is refused | 000g-40r4-0m30-e209, 02734a8cb7d9e671c0e80b3eee14dc9ad421b0bb87d15a6fef52f8f121aab497 | → | error: hashes must be a list of 64 lowercase hex characters each |
Verification
Verified by the operator, not the sandbox 39 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
## 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.