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
/// The answer to one recovery-code attempt, with the new stored set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecoveryCheck {
/// the code matched one of the stored hashes
pub valid: bool,
/// which stored hash it matched, when valid
pub index: Option<i64>,
/// the hashes to store now: the matched one removed, order kept
pub remaining: Vec<String>,
}
Once installed, your code imports each one from the group's module.
generate_recovery_codes throws on bad input 11 tests
pub fn generate_recovery_codes(entropy: &[i64], count: i64) -> Vec<String>
| 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
fune!(auth.recovery-codes@^1); // then call generate_recovery_codes(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
/// Crockford's base32 alphabet, lower case: no i, l, o or u to misread.
pub const RECOVERY_ALPHABET: &str = "0123456789abcdefghjkmnpqrstvwxyz";
const BYTES_PER_CODE: usize = 10;
/// 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 (getrandom), never a seeded generator.
///
/// # Panics
/// Panics on a byte outside 0-255, a count outside 1-50, or too few bytes.
pub fn generate_recovery_codes(entropy: &[i64], count: i64) -> Vec<String> {
if entropy.iter().any(|b| !(0..=255).contains(b)) {
panic!("entropy must be a list of integers from 0 to 255");
}
if !(1..=50).contains(&count) {
panic!("count must be a whole number from 1 to 50");
}
let needed = count as usize * BYTES_PER_CODE;
if entropy.len() < needed {
panic!(
"entropy must hold at least 10 bytes per code: {} needed, {} given",
needed,
entropy.len()
);
}
let alphabet = RECOVERY_ALPHABET.as_bytes();
let mut codes = Vec::with_capacity(count as usize);
for c in 0..count as usize {
let mut chars = String::with_capacity(16);
let mut buffer: i64 = 0;
let mut bits = 0;
for i in 0..BYTES_PER_CODE {
buffer = ((buffer << 8) | entropy[c * BYTES_PER_CODE + i]) & 0xffff;
bits += 8;
while bits >= 5 {
bits -= 5;
chars.push(alphabet[((buffer >> bits) & 31) as usize] as char);
}
}
codes.push(format!("{}-{}-{}-{}", &chars[0..4], &chars[4..8], &chars[8..12], &chars[12..16]));
}
codes
}
pub fn fune_vector(args: &[Value]) -> Value {
let entropy: Vec<i64> = match &args[0] {
Value::Arr(items) => items
.iter()
.map(|item| match item {
Value::Int(i) => *i,
_ => panic!("entropy must be a list of integers from 0 to 255"),
})
.collect(),
_ => panic!("entropy must be a list of integers from 0 to 255"),
};
let count = match &args[1] {
Value::Int(i) => *i,
_ => panic!("count must be a whole number from 1 to 50"),
};
Value::Arr(generate_recovery_codes(&entropy, count).iter().map(|s| Value::str(s)).collect())
}normalise_recovery_code 9 tests
pub fn normalise_recovery_code(code: &str) -> Option<String>
| 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
fune!(auth.recovery-codes@^1); // then call normalise_recovery_code(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::auth_recovery_codes_generate_recovery_codes::RECOVERY_ALPHABET; ← generateRecoveryCodes, another function of this group · built into the same file, even by a slim install
/// 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.
pub fn normalise_recovery_code(code: &str) -> Option<String> {
let mut out = String::with_capacity(16);
for raw in code.chars() {
if raw == ' ' || raw == '-' {
continue;
}
let mut ch = raw.to_ascii_lowercase();
if ch == 'i' || ch == 'l' {
ch = '1';
} else if ch == 'o' {
ch = '0';
}
if !RECOVERY_ALPHABET.contains(ch) {
return None;
}
out.push(ch);
}
if out.len() == 16 {
Some(out)
} else {
None
}
}
pub fn fune_vector(args: &[Value]) -> Value {
let code = match &args[0] {
Value::Str(s) => s.clone(),
_ => panic!("code must be a string"),
};
match normalise_recovery_code(&code) {
Some(s) => Value::Str(s),
None => Value::Null,
}
}hash_recovery_code throws on bad input 8 tests
pub fn hash_recovery_code(code: &str) -> String
| 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
fune!(auth.recovery-codes@^1); // then call hash_recovery_code(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::auth_recovery_codes_normalise_recovery_code::normalise_recovery_code; ← normaliseRecoveryCode, another function of this group · built into the same file, even by a slim install
use super::crypto_sha256::sha256; ← from crypto.sha256 ^1.0.0 · built alongside by fune
use super::encoding_hex_hex_encode::hex_encode;
use super::encoding_utf8_utf8_encode::utf8_encode;
/// 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.
///
/// # Panics
/// Panics with "not a recovery code" when the code cannot be normalised.
pub fn hash_recovery_code(code: &str) -> String {
let normal = match normalise_recovery_code(code) {
Some(n) => n,
None => panic!("not a recovery code"),
};
hex_encode(&sha256(&utf8_encode(&format!("fune.recovery-code:{}", normal))))
}
pub fn fune_vector(args: &[Value]) -> Value {
let code = match &args[0] {
Value::Str(s) => s.clone(),
_ => panic!("code must be a string"),
};
Value::Str(hash_recovery_code(&code))
}consume_recovery_code throws on bad input 11 tests
pub fn consume_recovery_code(code: &str, hashes: &[String]) -> 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
fune!(auth.recovery-codes@^1); // then call consume_recovery_code(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::auth_recovery_codes_hash_recovery_code::hash_recovery_code; ← hashRecoveryCode, another function of this group · built into the same file, even by a slim install
use super::auth_recovery_codes_normalise_recovery_code::normalise_recovery_code; ← normaliseRecoveryCode, another function of this group · built into the same file, even by a slim install
use super::crypto_constant_time_equal::constant_time_equal; ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
use super::encoding_hex_hex_decode::hex_decode;
fn is_hash(h: &str) -> bool {
h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
/// 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.
///
/// # Panics
/// Panics when a stored hash is not 64 lowercase hex characters.
pub fn consume_recovery_code(code: &str, hashes: &[String]) -> RecoveryCheck {
if hashes.iter().any(|h| !is_hash(h)) {
panic!("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: hashes.to_vec() };
}
let attempt = hex_decode(&hash_recovery_code(code));
let mut index: Option<usize> = None;
for (i, h) in hashes.iter().enumerate() {
let same = constant_time_equal(&attempt, &hex_decode(h));
if same && index.is_none() {
index = Some(i);
}
}
match index {
None => RecoveryCheck { valid: false, index: None, remaining: hashes.to_vec() },
Some(found) => RecoveryCheck {
valid: true,
index: Some(found as i64),
remaining: hashes
.iter()
.enumerate()
.filter(|(i, _)| *i != found)
.map(|(_, h)| h.clone())
.collect(),
},
}
}
pub fn recovery_check_to_value(check: &RecoveryCheck) -> Value {
Value::obj(vec![
("valid", Value::Bool(check.valid)),
("index", match check.index {
Some(i) => Value::Int(i),
None => Value::Null,
}),
("remaining", Value::Arr(check.remaining.iter().map(|h| Value::str(h)).collect())),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let code = match &args[0] {
Value::Str(s) => s.clone(),
_ => panic!("code must be a string"),
};
let hashes: Vec<String> = match &args[1] {
Value::Arr(items) => items
.iter()
.map(|item| match item {
Value::Str(s) => s.clone(),
_ => panic!("hashes must be a list of 64 lowercase hex characters each"),
})
.collect(),
_ => panic!("hashes must be a list of 64 lowercase hex characters each"),
};
recovery_check_to_value(&consume_recovery_code(&code, &hashes))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. 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 Rust implementation. Install it without the registry with fune add ./auth.recovery-codes-1.0.0-rust.fune, or fetch it from a terminal with fune pull auth.recovery-codes@1.0.0:rust.
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.