auth.email-token
Hashed single-use tokens for email verification, password reset and magic links, with expiry, as pure steps.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 43 tests, run in TypeScript, Python and Rust.generateEmailToken 12 · hashEmailToken 9 · checkEmailToken 12 · consumeEmailToken 10
What it does
The tokens behind "verify your email", "reset your password" and "sign in with a link": random, single-use, expiring, and stored only as a hash. Four pure functions; your code does the storage and the email (`email.send`).
- `generateEmailToken(randomBytes, purpose, subject, now, ttlSeconds)` makes a token from your random bytes. `token` goes in the link; store the rest. - `hashEmailToken(token, purpose)` is the stored key: the lowercase hex SHA-256 of `purpose + ":" + token`. - `checkEmailToken(records, token, purpose, now)` says what a token is worth now (`ok`, `unknown`, `expired`, `used`) without using it up: for the page that shows the new-password form. - `consumeEmailToken(records, token, purpose, now)` uses it up, as a pure state change: the records in, the outcome and the records to write back out.
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_email_token (randomBytes: int[], purpose: string, subject: string, now: int, ttlSeconds: int) -> IssuedEmailToken
- hash_email_token (token: string, purpose: string) -> string
- check_email_token (records: EmailTokenRecord[], token: string, purpose: string, now: int) -> EmailTokenCheck
- consume_email_token (records: EmailTokenRecord[], token: string, purpose: string, now: int) -> EmailTokenResult
The types it declares, generated into your project
/// A new token: the token goes in the email, the rest is stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssuedEmailToken {
/// base64url of the random bytes, for the link only; never store it
pub token: String,
/// lowercase hex SHA-256; the stored key
pub token_hash: String,
pub purpose: String,
pub subject: String,
/// Unix seconds
pub expires_at: i64,
}
/// One stored token.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmailTokenRecord {
/// as hashEmailToken gives it
pub token_hash: String,
pub purpose: String,
/// the user's id or address
pub subject: String,
/// Unix seconds; the token is expired from this second on
pub expires_at: i64,
/// when it was used up, or null while it is still usable
pub used_at: Option<i64>,
}
// EmailTokenOutcome is a string in Rust, one of: "ok", "unknown", "expired", "used".
// Parameters take it as &str and results hold it as String.
/// What a token from a link is worth now.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmailTokenCheck {
pub outcome: String,
/// the matching record, except when unknown
pub record: Option<EmailTokenRecord>,
}
/// The outcome of using a token, and the records to store after it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmailTokenResult {
pub outcome: String,
/// the matching record, with usedAt set when ok; null when unknown
pub record: Option<EmailTokenRecord>,
/// the records passed in, changed only when ok
pub records: Vec<EmailTokenRecord>,
}
Once installed, your code imports each one from the group's module.
generate_email_token throws on bad input 12 tests
pub fn generate_email_token(random_bytes: &[i64], purpose: &str, subject: &str, now: i64, ttl_seconds: i64) -> IssuedEmailToken
| random_bytes | int[] | at least 16 bytes from a CSPRNG (32 is usual) |
| purpose | string | what the token is for: verify-email, reset-password, magic-link, or your own (a-z, 0-9 and -) |
| subject | string | whose token it is: the user's id, or the address for a sign-up not yet an account |
| now | int | the current time in Unix seconds, read by the caller |
| ttl_seconds | int | lifetime, 1 to 2592000 (30 days); 3600 for a reset link |
| returns | IssuedEmailToken | the token for the link, and the record to store |
For example
generate_email_token(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, reset-password, user_42, 1,767,225,600, 3,600)→ token AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, token hash 9fcef89e68380b953250664a13ea640cce304de826a8a140cb92c39fb7a0d764, purpose reset-password, subject user_42, expires at… a reset link: 32 bytes, an hourgenerate_email_token(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, verify-email, ada@example.com, 1,767,225,600, 86,400)→ token AAECAwQFBgcICQoLDA0ODw, token hash 4eca11009db8d28488bc549b54de2d985e52e9873770099bc08a6a00452cf8a6, purpose verify-email, subject ada@example.com, expires at 1,767,312,000 the 16-byte minimum, verify-email for a daygenerate_email_token(255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, magic-link, user_7,…)→ token __________________________________________8, token hash 79ea628b36f54b404ab706543984c9feaa46fe399990da977e9e6b0849e9e453, purpose magic-link, subject user_7, expires at 1,76… 0xff bytes encode as base64url underscores, no padding
fune!(auth.email-token@^1); // then call generate_email_token(…)
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_email_token_hash_email_token::{check_email_token_purpose, hash_email_token}; ← hashEmailToken, another function of this group · built into the same file, even by a slim install
use super::encoding_base64_base64_url_encode::base64_url_encode;
/// A new single-use token from the caller's random bytes. The token goes in
/// the email's link only; store the rest.
///
/// # Panics
/// Panics on a byte outside 0-255, fewer than 16 bytes, a malformed purpose,
/// an empty subject or a ttl outside 1-2592000.
pub fn generate_email_token(
random_bytes: &[i64],
purpose: &str,
subject: &str,
now: i64,
ttl_seconds: i64,
) -> IssuedEmailToken {
if random_bytes.iter().any(|b| !(0..=255).contains(b)) {
panic!("randomBytes must be a list of integers from 0 to 255");
}
if random_bytes.len() < 16 {
panic!("randomBytes must hold at least 16 bytes");
}
check_email_token_purpose(purpose);
if subject.is_empty() {
panic!("subject must be a non-empty string");
}
if !(1..=2_592_000).contains(&ttl_seconds) {
panic!("ttlSeconds must be a whole number from 1 to 2592000");
}
let token = base64_url_encode(random_bytes);
let token_hash = hash_email_token(&token, purpose);
IssuedEmailToken {
token,
token_hash,
purpose: purpose.to_string(),
subject: subject.to_string(),
expires_at: now + ttl_seconds,
}
}
pub fn fune_vector(args: &[Value]) -> Value {
let bytes: Vec<i64> = match &args[0] {
Value::Arr(items) => items
.iter()
.map(|item| match item {
Value::Int(i) => *i,
_ => panic!("randomBytes must be a list of integers from 0 to 255"),
})
.collect(),
_ => panic!("randomBytes must be a list of integers from 0 to 255"),
};
let text = |i: usize, message: &str| -> String {
match &args[i] {
Value::Str(s) => s.clone(),
_ => panic!("{}", message),
}
};
let now = match &args[3] {
Value::Int(i) => *i,
_ => panic!("now must be a whole number of Unix seconds"),
};
let ttl = match &args[4] {
Value::Int(i) => *i,
_ => panic!("ttlSeconds must be a whole number from 1 to 2592000"),
};
let issued = generate_email_token(
&bytes,
&text(1, "purpose must be 1 to 40 characters of a-z, 0-9 and -"),
&text(2, "subject must be a non-empty string"),
now,
ttl,
);
Value::obj(vec![
("token", Value::str(&issued.token)),
("tokenHash", Value::str(&issued.token_hash)),
("purpose", Value::str(&issued.purpose)),
("subject", Value::str(&issued.subject)),
("expiresAt", Value::Int(issued.expires_at)),
])
}hash_email_token throws on bad input 9 tests
pub fn hash_email_token(token: &str, purpose: &str) -> String
| token | string | the token from the link |
| purpose | string | the purpose it was issued for |
| returns | string | the lowercase hex SHA-256 of purpose, ":" and the token: the stored key |
For example
hash_email_token(AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password)→ 9fcef89e68380b953250664a13ea640cce304de826a8a140cb92c39fb7a0d764 a reset tokenhash_email_token(AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, verify-email)→ 7931edf47b595f7b175cc2dc23c7eb4ecad68fd6fa09bf592e65f16bc5995306 the same token for verify-email is another hashhash_email_token(__________________________________________8, magic-link)→ 79ea628b36f54b404ab706543984c9feaa46fe399990da977e9e6b0849e9e453 a magic-link token
fune!(auth.email-token@^1); // then call hash_email_token(…)
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::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;
/// Refuses a purpose that is not 1 to 40 characters of a-z, 0-9 and -.
pub fn check_email_token_purpose(purpose: &str) {
let ok = !purpose.is_empty()
&& purpose.len() <= 40
&& purpose.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
if !ok {
panic!("purpose must be 1 to 40 characters of a-z, 0-9 and -");
}
}
/// The stored key for a token: the hex SHA-256 of the purpose, ":" and the
/// token, so a token issued for one purpose never matches another.
///
/// # Panics
/// Panics on a malformed purpose or an empty token.
pub fn hash_email_token(token: &str, purpose: &str) -> String {
check_email_token_purpose(purpose);
if token.is_empty() {
panic!("token must be a non-empty string");
}
hex_encode(&sha256(&utf8_encode(&format!("{}:{}", purpose, token))))
}
pub fn fune_vector(args: &[Value]) -> Value {
let token = match &args[0] {
Value::Str(s) => s.clone(),
_ => panic!("token must be a non-empty string"),
};
let purpose = match &args[1] {
Value::Str(s) => s.clone(),
_ => panic!("purpose must be 1 to 40 characters of a-z, 0-9 and -"),
};
Value::Str(hash_email_token(&token, &purpose))
}check_email_token throws on bad input 12 tests
pub fn check_email_token(records: &[EmailTokenRecord], token: &str, purpose: &str, now: i64) -> EmailTokenCheck
| records | EmailTokenRecord[] | the stored records to look in, usually the one row found by the token's hash |
| token | string | the token from the link |
| purpose | string | the purpose this page accepts |
| now | int | the current time in Unix seconds |
| returns | EmailTokenCheck | ok, unknown, expired or used, without using the token up |
For example
check_email_token(records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600)→ outcome ok, record … a fresh token is okcheck_email_token(records ×4, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610)→ outcome ok, record … found among several recordscheck_email_token(records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,229,199)→ outcome ok, record … one second before expiry is still ok
fune!(auth.email-token@^1); // then call check_email_token(…)
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_email_token_hash_email_token::{check_email_token_purpose, hash_email_token}; ← hashEmailToken, 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))
}
/// Where a token's record is among records, and its outcome now: None when unknown.
pub fn find_email_token(
records: &[EmailTokenRecord],
token: &str,
purpose: &str,
now: i64,
) -> (Option<usize>, EmailTokenCheck) {
check_email_token_purpose(purpose);
if records.iter().any(|r| !is_hash(&r.token_hash)) {
panic!("tokenHash must be 64 lowercase hex characters");
}
let unknown = EmailTokenCheck { outcome: "unknown".to_string(), record: None };
if token.is_empty() {
return (None, unknown);
}
let attempt = hex_decode(&hash_email_token(token, purpose));
let mut index: Option<usize> = None;
for (i, r) in records.iter().enumerate() {
// Every record is compared, with no early exit.
let same = constant_time_equal(&attempt, &hex_decode(&r.token_hash));
if same && index.is_none() {
index = Some(i);
}
}
let found = match index {
Some(i) if records[i].purpose == purpose => i,
_ => return (None, unknown),
};
let record = records[found].clone();
let outcome = if record.used_at.is_some() {
"used"
} else if now >= record.expires_at {
"expired"
} else {
"ok"
};
(Some(found), EmailTokenCheck { outcome: outcome.to_string(), record: Some(record) })
}
/// What a token from a link is worth now, without using it up.
///
/// # Panics
/// Panics on a malformed purpose or a stored tokenHash that is not 64
/// lowercase hex characters.
pub fn check_email_token(records: &[EmailTokenRecord], token: &str, purpose: &str, now: i64) -> EmailTokenCheck {
find_email_token(records, token, purpose, now).1
}
pub fn email_token_record_from_value(value: &Value) -> EmailTokenRecord {
let text = |key: &str| match value.get(key) {
Value::Str(s) => s.clone(),
_ => panic!("tokenHash must be 64 lowercase hex characters"),
};
EmailTokenRecord {
token_hash: text("tokenHash"),
purpose: text("purpose"),
subject: text("subject"),
expires_at: match value.get("expiresAt") {
Value::Int(i) => *i,
_ => panic!("expiresAt must be a whole number of Unix seconds"),
},
used_at: match value.get("usedAt") {
Value::Int(i) => Some(*i),
_ => None,
},
}
}
pub fn email_token_record_to_value(r: &EmailTokenRecord) -> Value {
Value::obj(vec![
("tokenHash", Value::str(&r.token_hash)),
("purpose", Value::str(&r.purpose)),
("subject", Value::str(&r.subject)),
("expiresAt", Value::Int(r.expires_at)),
("usedAt", match r.used_at {
Some(i) => Value::Int(i),
None => Value::Null,
}),
])
}
pub fn email_token_args(args: &[Value]) -> (Vec<EmailTokenRecord>, String, String, i64) {
let records: Vec<EmailTokenRecord> = match &args[0] {
Value::Arr(items) => items.iter().map(email_token_record_from_value).collect(),
_ => panic!("records must be a list of EmailTokenRecord"),
};
let token = match &args[1] {
Value::Str(s) => s.clone(),
_ => panic!("token must be a string"),
};
let purpose = match &args[2] {
Value::Str(s) => s.clone(),
_ => panic!("purpose must be 1 to 40 characters of a-z, 0-9 and -"),
};
let now = match &args[3] {
Value::Int(i) => *i,
_ => panic!("now must be a whole number of Unix seconds"),
};
(records, token, purpose, now)
}
pub fn fune_vector(args: &[Value]) -> Value {
let (records, token, purpose, now) = email_token_args(args);
let check = check_email_token(&records, &token, &purpose, now);
Value::obj(vec![
("outcome", Value::str(&check.outcome)),
("record", match &check.record {
Some(r) => email_token_record_to_value(r),
None => Value::Null,
}),
])
}consume_email_token throws on bad input 10 tests
pub fn consume_email_token(records: &[EmailTokenRecord], token: &str, purpose: &str, now: i64) -> EmailTokenResult
| records | EmailTokenRecord[] | the stored records: the token's row, plus the subject's other rows for that purpose to retire them too |
| token | string | the token from the link |
| purpose | string | the purpose this action accepts |
| now | int | the current time in Unix seconds |
| returns | EmailTokenResult | the outcome, and the records to write back |
For example
consume_email_token(records ×4, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610)→ outcome ok, record …, records ×4 ok: the token and the same user's older reset link are used up; other purposes and users untouchedconsume_email_token(records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600)→ outcome ok, record …, records ×1 ok: a lone record gets usedAtconsume_email_token(records ×2, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610)→ outcome ok, record …, records ×2 an already used sibling keeps its own usedAt
fune!(auth.email-token@^1); // then call consume_email_token(…)
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_email_token_check_email_token::{email_token_args, email_token_record_to_value, find_email_token}; ← checkEmailToken, another function of this group · built into the same file, even by a slim install
/// Uses a token up, as a pure state change. When ok, the token's record and
/// every other unused record of the same subject and purpose get
/// used_at = now; any other outcome returns the records unchanged.
///
/// # Panics
/// Panics on a malformed purpose or a stored tokenHash that is not 64
/// lowercase hex characters.
pub fn consume_email_token(records: &[EmailTokenRecord], token: &str, purpose: &str, now: i64) -> EmailTokenResult {
let (index, check) = find_email_token(records, token, purpose, now);
let (found, used) = match (index, &check.record) {
(Some(i), Some(r)) if check.outcome == "ok" => (i, r.clone()),
_ => {
return EmailTokenResult { outcome: check.outcome, record: check.record, records: records.to_vec() };
}
};
let next: Vec<EmailTokenRecord> = records
.iter()
.enumerate()
.map(|(i, r)| {
if i == found || (r.used_at.is_none() && r.subject == used.subject && r.purpose == used.purpose) {
EmailTokenRecord { used_at: Some(now), ..r.clone() }
} else {
r.clone()
}
})
.collect();
EmailTokenResult { outcome: "ok".to_string(), record: Some(next[found].clone()), records: next }
}
pub fn fune_vector(args: &[Value]) -> Value {
let (records, token, purpose, now) = email_token_args(args);
let result = consume_email_token(&records, &token, &purpose, now);
Value::obj(vec![
("outcome", Value::str(&result.outcome)),
("record", match &result.record {
Some(r) => email_token_record_to_value(r),
None => Value::Null,
}),
("records", Value::Arr(result.records.iter().map(email_token_record_to_value).collect())),
])
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 5 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.email-token
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add auth.email-token --only generateEmailToken
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./auth.email-token-1.0.0-rust.fune, or fetch it from a terminal with fune pull auth.email-token@1.0.0:rust.
The whole function, every language, is one file too: auth.email-token-1.0.0.fune, 63,634 bytes, sha256 87299b8ddbba991769feb51af8a208fd3cb128547edaf13f94d4659b66687168. 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.email-token.generateEmailToken
// fune: before auth.email-token.hashEmailToken
// fune: before auth.email-token.checkEmailToken
// fune: before auth.email-token.consumeEmailToken
after — your function gets the result and the arguments, and returns the final result.
// fune: after auth.email-token.generateEmailToken
// fune: after auth.email-token.hashEmailToken
// fune: after auth.email-token.checkEmailToken
// fune: after auth.email-token.consumeEmailToken
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.email-token
// fune: replace crypto.sha256 in auth.email-token
// fune: replace encoding.base64 in auth.email-token
// fune: replace encoding.hex in auth.email-token
// fune: replace encoding.utf8 in auth.email-token
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.email-token --steps.
// fune: step auth.email-token.<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.
generateEmailToken 12 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a reset link: 32 bytes, an hour | 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, reset-password, user_42, 1,767,225,600, 3,600 | → | token AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, token hash 9fcef89e68380b953250664a13ea640cce304de826a8a140cb92c39fb7a0d764, purpose reset-password, subject user_42, expires at… |
| the 16-byte minimum, verify-email for a day | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, verify-email, ada@example.com, 1,767,225,600, 86,400 | → | token AAECAwQFBgcICQoLDA0ODw, token hash 4eca11009db8d28488bc549b54de2d985e52e9873770099bc08a6a00452cf8a6, purpose verify-email, subject ada@example.com, expires at 1,767,312,000 |
| 0xff bytes encode as base64url underscores, no padding | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, magic-link, user_7,… | → | token __________________________________________8, token hash 79ea628b36f54b404ab706543984c9feaa46fe399990da977e9e6b0849e9e453, purpose magic-link, subject user_7, expires at 1,76… |
| the same bytes for another purpose hash differently | 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, magic-link, user_42, 1,767,225,600, 3,600 | → | token AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, token hash b89ead9738bf967f9e26f10c2d0c55642a04c65c7649d5f205c6aa6b1451cfbf, purpose magic-link, subject user_42, expires at 1,7… |
| a purpose of the app's own, 30 days (the longest) | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, invite, org_1:ada@example.com, 1,767,225,600, 2,592,000 | → | token AAECAwQFBgcICQoLDA0ODw, token hash db75498ed184e290272aa363011254d82887067ae08d5d95f183e0d8ff1ab625, purpose invite, subject org_1:ada@example.com, expires at 1,769,817,600 |
| 15 bytes is too few | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, reset-password, user_42, 1,767,225,600, 3,600 | → | error: randomBytes must hold at least 16 bytes |
| a byte over 255 | 256, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, reset-password, user_42, 1,767,225,600, 3,600 | → | error: randomBytes must be a list of integers from 0 to 255 |
| an upper-case purpose | 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, Reset, user_42, 1,767,225,600, 3,600 | → | error: purpose must be 1 to 40 characters of a-z, 0-9 and - |
| a purpose with a colon | 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, reset:password, user_42, 1,767,225,600, 3,600 | → | error: purpose must be 1 to 40 characters of a-z, 0-9 and - |
| an empty subject | 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, reset-password, , 1,767,225,600, 3,600 | → | error: subject must be a non-empty string |
Show the other 2 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a ttl of 0 | 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, reset-password, user_42, 1,767,225,600, 0 | → | error: ttlSeconds must be a whole number from 1 to 2592000 |
| a ttl over 30 days | 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, reset-password, user_42, 1,767,225,600, 2,592,001 | → | error: ttlSeconds must be a whole number from 1 to 2592000 |
hashEmailToken 9 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a reset token | AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password | → | 9fcef89e68380b953250664a13ea640cce304de826a8a140cb92c39fb7a0d764 |
| the same token for verify-email is another hash | AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, verify-email | → | 7931edf47b595f7b175cc2dc23c7eb4ecad68fd6fa09bf592e65f16bc5995306 |
| a magic-link token | __________________________________________8, magic-link | → | 79ea628b36f54b404ab706543984c9feaa46fe399990da977e9e6b0849e9e453 |
| a one-character token | a, x | → | e0f54fd6052d3e5f44277e62835f679b8e107257db5d41f1b473f47dc71f4100 |
| a 40-character purpose is the longest | AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | → | acc209673714f79fd889a7f6131765046c713c5a0f0141916245728065414070 |
| an empty token | , reset-password | → | error: token must be a non-empty string |
| a 41-character purpose | AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | → | error: purpose must be 1 to 40 characters of a-z, 0-9 and - |
| a purpose with a trailing newline | AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password | → | error: purpose must be 1 to 40 characters of a-z, 0-9 and - |
| an empty purpose | AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, | → | error: purpose must be 1 to 40 characters of a-z, 0-9 and - |
checkEmailToken 12 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a fresh token is ok | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600 | → | outcome ok, record … |
| found among several records | records ×4, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610 | → | outcome ok, record … |
| one second before expiry is still ok | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,229,199 | → | outcome ok, record … |
| at the expiry second it is expired | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,229,200 | → | outcome expired, record … |
| a used token says used, even after expiry | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,232,800 | → | outcome used, record … |
| presented for another purpose it is unknown | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, verify-email, 1,767,225,600 | → | outcome unknown, record — |
| a record whose stored purpose differs is unknown | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600 | → | outcome unknown, record — |
| a token not stored is unknown | records ×2, not-a-real-token, reset-password, 1,767,225,600 | → | outcome unknown, record — |
| an empty token is unknown, not an error | records ×1, , reset-password, 1,767,225,600 | → | outcome unknown, record — |
| no records | , AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600 | → | outcome unknown, record — |
Show the other 2 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a stored hash in upper case is corrupt | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600 | → | error: tokenHash must be 64 lowercase hex characters |
| a bad purpose | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, Reset, 1,767,225,600 | → | error: purpose must be 1 to 40 characters of a-z, 0-9 and - |
consumeEmailToken 10 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| ok: the token and the same user's older reset link are used up; other purposes and users untouched | records ×4, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610 | → | outcome ok, record …, records ×4 |
| ok: a lone record gets usedAt | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600 | → | outcome ok, record …, records ×1 |
| an already used sibling keeps its own usedAt | records ×2, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610 | → | outcome ok, record …, records ×2 |
| a second use is refused and nothing changes | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,620 | → | outcome used, record …, records ×1 |
| expired: nothing changes | records ×4, AAECAwQFBgcICQoLDA0ODw, reset-password, 1,767,227,400 | → | outcome expired, record …, records ×4 |
| the verify token used as a reset token is unknown | records ×4, __________________________________________8, reset-password, 1,767,225,600 | → | outcome unknown, record —, records ×4 |
| the verify token for verify-email: only it is used (no other verify rows) | records ×4, __________________________________________8, verify-email, 1,767,225,610 | → | outcome ok, record …, records ×4 |
| the older link used first retires the newer one too | records ×4, AAECAwQFBgcICQoLDA0ODw, reset-password, 1,767,225,610 | → | outcome ok, record …, records ×4 |
| a corrupt stored hash | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600 | → | error: tokenHash must be 64 lowercase hex characters |
| a purpose with a space | records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset password, 1,767,225,600 | → | error: purpose must be 1 to 40 characters of a-z, 0-9 and - |
Verification
Verified by the operator, not the sandbox 43 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
## Purposes
`verify-email`, `reset-password` and `magic-link` are the usual ones; any 1 to 40 characters of `a-z`, `0-9` and `-` is accepted (`invite`, `change-email`). The purpose is inside the hash, so a token emailed for one purpose can never be used for another: presented elsewhere it is simply `unknown`. A record whose stored purpose differs from the one asked for is `unknown` too.
## Randomness and the hash
Pass at least 16 bytes (128 bits) from a CSPRNG; 32 is usual: `crypto.getRandomValues(new Uint8Array(32))`, `list(secrets.token_bytes(32))`. The token is their base64url text, with no padding, safe in a URL. Because it is that random, a plain SHA-256 is the right hash: nobody can guess their way back from a leaked hash, and the lookup stays an index hit. **The raw token is never stored**, only sent, so a database leak holds no usable link.
## Storing tokens
One row per token:
CREATE TABLE email_tokens (
token_hash text PRIMARY KEY, -- hashEmailToken(token, purpose)
purpose text NOT NULL,
subject text NOT NULL, -- user id, or the address for a sign-up
expires_at bigint NOT NULL, -- Unix seconds
used_at bigint -- null until used
);
CREATE INDEX email_tokens_subject ON email_tokens (subject, purpose);Issue: `generateEmailToken`, insert the record, email the link with `token` in it.
Use (the POST that sets the new password, or the magic-link landing):
1. `hash = hashEmailToken(tokenFromLink, "reset-password")`. 2. In one transaction, select the row by `token_hash = hash` and, to retire older links, the same subject's unused rows for that purpose (`FOR UPDATE`). 3. `result = consumeEmailToken(rows, tokenFromLink, "reset-password", now)`. 4. If `result.outcome` is `ok`, write back each record whose `usedAt` changed, do the action (set the password, mark the email verified, sign in) for `result.record.subject`, and commit. Otherwise show the matching message: expired asks for a new link; used and unknown say the link is no longer valid.
Doing steps 2 to 4 in one transaction is what makes the token single-use under two simultaneous clicks; the function decides, the transaction makes the decision stick. Writing `UPDATE ... SET used_at = $now WHERE token_hash = $hash AND used_at IS NULL` and checking that one row changed gives the same guarantee without a lock.
## What consuming does
On `ok`, the token's record gets `usedAt = now`, and so does every other record in the list that is still unused and has the same subject and purpose: once a user has reset their password with one link, the other reset links in their inbox stop working. Records of other purposes or other subjects are untouched. On any other outcome the records come back unchanged. The list keeps its order, and nothing passed in is modified.
Stored hashes are compared in constant time, against every record, with no early exit. A stored hash that is not 64 lowercase hex characters is an error (corrupt data); an empty token from a link is `unknown`.
Expiry: the token is usable while `now < expiresAt`; at `expiresAt` it is expired. An hour suits a password reset, 15 minutes a magic link, a day or more an email verification; the longest accepted is 30 days. Expired and used rows can be deleted by a periodic job.
Throttle requests for new links per address, and send the same response whether or not the address has an account.