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
@dataclass(frozen=True)
class IssuedEmailToken:
"""A new token: the token goes in the email, the rest is stored."""
#: base64url of the random bytes, for the link only; never store it
token: str
#: lowercase hex SHA-256; the stored key
token_hash: str
purpose: str
subject: str
#: Unix seconds
expires_at: int
@dataclass(frozen=True)
class EmailTokenRecord:
"""One stored token."""
#: as hashEmailToken gives it
token_hash: str
purpose: str
#: the user's id or address
subject: str
#: Unix seconds; the token is expired from this second on
expires_at: int
#: when it was used up, or null while it is still usable
used_at: Optional[int]
EmailTokenOutcome = Literal["ok", "unknown", "expired", "used"]
@dataclass(frozen=True)
class EmailTokenCheck:
"""What a token from a link is worth now."""
outcome: EmailTokenOutcome
#: the matching record, except when unknown
record: Optional[EmailTokenRecord]
@dataclass(frozen=True)
class EmailTokenResult:
"""The outcome of using a token, and the records to store after it."""
outcome: EmailTokenOutcome
#: the matching record, with usedAt set when ok; null when unknown
record: Optional[EmailTokenRecord]
#: the records passed in, changed only when ok
records: List[EmailTokenRecord]
Once installed, your code imports each one from the group's module.
generate_email_token throws on bad input 12 tests
def generate_email_token(random_bytes: Sequence[int], purpose: str, subject: str, now: int, ttl_seconds: int) -> 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
from fune.auth.email_token import generate_email_token # auth.email-token@^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 Sequence
from .auth_email_token_hash_email_token import check_email_token_purpose, hash_email_token ← hashEmailToken, another function of this group · built into the same file, even by a slim install
from .auth_email_token_types import IssuedEmailToken
from .encoding_base64_base64_url_encode import base64_url_encode
def generate_email_token(
random_bytes: Sequence[int], purpose: str, subject: str, now: int, ttl_seconds: int
) -> IssuedEmailToken:
"""A new single-use token from the caller's random bytes. The token goes
in the email's link only; store the rest."""
if isinstance(random_bytes, (str, dict)) or not hasattr(random_bytes, "__len__"):
raise TypeError("randomBytes must be a list of integers from 0 to 255")
for b in random_bytes:
if type(b) is not int or b < 0 or b > 255:
raise ValueError("randomBytes must be a list of integers from 0 to 255")
if len(random_bytes) < 16:
raise ValueError("randomBytes must hold at least 16 bytes")
check_email_token_purpose(purpose)
if not isinstance(subject, str) or len(subject) == 0:
raise ValueError("subject must be a non-empty string")
if type(now) is not int:
raise TypeError("now must be a whole number of Unix seconds")
if type(ttl_seconds) is not int or ttl_seconds < 1 or ttl_seconds > 2592000:
raise ValueError("ttlSeconds must be a whole number from 1 to 2592000")
token = base64_url_encode(random_bytes)
return IssuedEmailToken(
token=token,
token_hash=hash_email_token(token, purpose),
purpose=purpose,
subject=subject,
expires_at=now + ttl_seconds,
)hash_email_token throws on bad input 9 tests
def hash_email_token(token: str, purpose: str) -> str
| 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
from fune.auth.email_token import hash_email_token # auth.email-token@^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 .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
_PURPOSE = re.compile(r"[a-z0-9-]{1,40}")
def check_email_token_purpose(purpose: str) -> None:
"""Refuses a purpose that is not 1 to 40 characters of a-z, 0-9 and -."""
if not isinstance(purpose, str) or not _PURPOSE.fullmatch(purpose):
raise ValueError("purpose must be 1 to 40 characters of a-z, 0-9 and -")
def hash_email_token(token: str, purpose: str) -> str:
"""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."""
check_email_token_purpose(purpose)
if not isinstance(token, str) or len(token) == 0:
raise ValueError("token must be a non-empty string")
return hex_encode(sha256(utf8_encode(purpose + ":" + token)))check_email_token throws on bad input 12 tests
def check_email_token(records: Sequence[EmailTokenRecord], token: str, purpose: str, now: int) -> 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
from fune.auth.email_token import check_email_token # auth.email-token@^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, Tuple
from .auth_email_token_hash_email_token import check_email_token_purpose, hash_email_token ← hashEmailToken, another function of this group · built into the same file, even by a slim install
from .auth_email_token_types import EmailTokenCheck, EmailTokenRecord
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 find_email_token(
records: Sequence[EmailTokenRecord], token: str, purpose: str, now: int
) -> Tuple[int, EmailTokenCheck]:
"""Where a token's record is among records, and its outcome now: index -1 when unknown."""
check_email_token_purpose(purpose)
if not isinstance(token, str):
raise TypeError("token must be a string")
if type(now) is not int:
raise TypeError("now must be a whole number of Unix seconds")
for r in records:
if not isinstance(r.token_hash, str) or not _HASH.fullmatch(r.token_hash):
raise ValueError("tokenHash must be 64 lowercase hex characters")
if len(token) == 0:
return -1, EmailTokenCheck(outcome="unknown", record=None)
attempt = hex_decode(hash_email_token(token, purpose))
index = -1
for i, r in enumerate(records):
# Every record is compared, with no early exit.
same = constant_time_equal(attempt, hex_decode(r.token_hash))
if same and index < 0:
index = i
if index < 0 or records[index].purpose != purpose:
return -1, EmailTokenCheck(outcome="unknown", record=None)
record = records[index]
if record.used_at is not None:
return index, EmailTokenCheck(outcome="used", record=record)
if now >= record.expires_at:
return index, EmailTokenCheck(outcome="expired", record=record)
return index, EmailTokenCheck(outcome="ok", record=record)
def check_email_token(records: Sequence[EmailTokenRecord], token: str, purpose: str, now: int) -> EmailTokenCheck:
"""What a token from a link is worth now, without using it up."""
return find_email_token(records, token, purpose, now)[1]consume_email_token throws on bad input 10 tests
def consume_email_token(records: Sequence[EmailTokenRecord], token: str, purpose: str, now: int) -> 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
from fune.auth.email_token import consume_email_token # auth.email-token@^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 Sequence
from .auth_email_token_check_email_token import find_email_token ← checkEmailToken, another function of this group · built into the same file, even by a slim install
from .auth_email_token_types import EmailTokenRecord, EmailTokenResult
def _used(r: EmailTokenRecord, now: int) -> EmailTokenRecord:
return EmailTokenRecord(
token_hash=r.token_hash, purpose=r.purpose, subject=r.subject, expires_at=r.expires_at, used_at=now
)
def consume_email_token(records: Sequence[EmailTokenRecord], token: str, purpose: str, now: int) -> EmailTokenResult:
"""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."""
index, check = find_email_token(records, token, purpose, now)
if check.outcome != "ok" or check.record is None:
return EmailTokenResult(outcome=check.outcome, record=check.record, records=list(records))
used = check.record
nxt = [
_used(r, now)
if i == index or (r.used_at is None and r.subject == used.subject and r.purpose == used.purpose)
else r
for i, r in enumerate(records)
]
return EmailTokenResult(outcome="ok", record=nxt[index], records=nxt)Install
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 5 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.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 Python implementation. Install it without the registry with fune add ./auth.email-token-1.0.0-python.fune, or fetch it from a terminal with fune pull auth.email-token@1.0.0:python.
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.