Functional Weave
Code in Rust

auth.email-token@1.0.0

README.md

4,303 bytes · view raw

# auth.email-token

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.

## 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:

```sql
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.