Functional Weave
Code in TypeScript

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.

  1. generateEmailToken (randomBytes: int[], purpose: string, subject: string, now: int, ttlSeconds: int) -> IssuedEmailToken
  2. hashEmailToken (token: string, purpose: string) -> string
  3. checkEmailToken (records: EmailTokenRecord[], token: string, purpose: string, now: int) -> EmailTokenCheck
  4. consumeEmailToken (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. */
export interface IssuedEmailToken {
  /** base64url of the random bytes, for the link only; never store it */
  readonly token: string;
  /** lowercase hex SHA-256; the stored key */
  readonly tokenHash: string;
  readonly purpose: string;
  readonly subject: string;
  /** Unix seconds */
  readonly expiresAt: number;
}

/** One stored token. */
export interface EmailTokenRecord {
  /** as hashEmailToken gives it */
  readonly tokenHash: string;
  readonly purpose: string;
  /** the user's id or address */
  readonly subject: string;
  /** Unix seconds; the token is expired from this second on */
  readonly expiresAt: number;
  /** when it was used up, or null while it is still usable */
  readonly usedAt: number | null;
}

export type EmailTokenOutcome = "ok" | "unknown" | "expired" | "used";

/** What a token from a link is worth now. */
export interface EmailTokenCheck {
  readonly outcome: EmailTokenOutcome;
  /** the matching record, except when unknown */
  readonly record: EmailTokenRecord | null;
}

/** The outcome of using a token, and the records to store after it. */
export interface EmailTokenResult {
  readonly outcome: EmailTokenOutcome;
  /** the matching record, with usedAt set when ok; null when unknown */
  readonly record: EmailTokenRecord | null;
  /** the records passed in, changed only when ok */
  readonly records: readonly EmailTokenRecord[];
}

Once installed, your code imports each one from the group's module.

generateEmailToken throws on bad input 12 tests

export function generateEmailToken(randomBytes: readonly number[], purpose: string, subject: string, now: number, ttlSeconds: number): IssuedEmailToken
randomBytesint[]at least 16 bytes from a CSPRNG (32 is usual)
purposestringwhat the token is for: verify-email, reset-password, magic-link, or your own (a-z, 0-9 and -)
subjectstringwhose token it is: the user's id, or the address for a sign-up not yet an account
nowintthe current time in Unix seconds, read by the caller
ttlSecondsintlifetime, 1 to 2592000 (30 days); 3600 for a reset link
returnsIssuedEmailTokenthe token for the link, and the record to store

For example

  • generateEmailToken(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 hour
  • generateEmailToken(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 day
  • generateEmailToken(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
import { generateEmailToken } from "#fune/auth.email-token@^1";
impl/typescript/generate_email_token.ts · 32 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { type IssuedEmailToken } from "./auth_email_token_types.ts";
import { base64UrlEncode } from "./encoding_base64_base64_url_encode.ts";
import { checkEmailTokenPurpose, hashEmailToken } from "./auth_email_token_hash_email_token.ts";  ← hashEmailToken, another function of this group · built into the same file, even by a slim install

/**
 * A new single-use token from the caller's random bytes. The token goes in
 * the email's link and nowhere else; store the rest (tokenHash, purpose,
 * subject, expiresAt, usedAt null), so a leaked database holds no usable link.
 */
export function generateEmailToken(
  randomBytes: readonly number[],
  purpose: string,
  subject: string,
  now: number,
  ttlSeconds: number,
): IssuedEmailToken {
  if (!Array.isArray(randomBytes)) throw new TypeError("randomBytes must be a list of integers from 0 to 255");
  for (const b of randomBytes) {
    if (typeof b !== "number" || !Number.isInteger(b) || b < 0 || b > 255) {
      throw new RangeError("randomBytes must be a list of integers from 0 to 255");
    }
  }
  if (randomBytes.length < 16) throw new RangeError("randomBytes must hold at least 16 bytes");
  checkEmailTokenPurpose(purpose);
  if (typeof subject !== "string" || subject.length === 0) throw new Error("subject must be a non-empty string");
  if (typeof now !== "number" || !Number.isInteger(now)) throw new TypeError("now must be a whole number of Unix seconds");
  if (typeof ttlSeconds !== "number" || !Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > 2592000) {
    throw new RangeError("ttlSeconds must be a whole number from 1 to 2592000");
  }
  const token = base64UrlEncode(randomBytes);
  return { token, tokenHash: hashEmailToken(token, purpose), purpose, subject, expiresAt: now + ttlSeconds };
}

hashEmailToken throws on bad input 9 tests

export function hashEmailToken(token: string, purpose: string): string
tokenstringthe token from the link
purposestringthe purpose it was issued for
returnsstringthe lowercase hex SHA-256 of purpose, ":" and the token: the stored key

For example

  • hashEmailToken(AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password) → 9fcef89e68380b953250664a13ea640cce304de826a8a140cb92c39fb7a0d764 a reset token
  • hashEmailToken(AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, verify-email) → 7931edf47b595f7b175cc2dc23c7eb4ecad68fd6fa09bf592e65f16bc5995306 the same token for verify-email is another hash
  • hashEmailToken(__________________________________________8, magic-link) → 79ea628b36f54b404ab706543984c9feaa46fe399990da977e9e6b0849e9e453 a magic-link token
import { hashEmailToken } from "#fune/auth.email-token@^1";
impl/typescript/hash_email_token.ts · 24 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { sha256 } from "./crypto_sha256.ts";  ← from crypto.sha256 ^1.0.0 · built alongside by fune
import { hexEncode } from "./encoding_hex_hex_encode.ts";
import { utf8Encode } from "./encoding_utf8_utf8_encode.ts";

const PURPOSE = /^[a-z0-9-]{1,40}$/;

/** Refuses a purpose that is not 1 to 40 characters of a-z, 0-9 and -. */
export function checkEmailTokenPurpose(purpose: string): void {
  if (typeof purpose !== "string" || !PURPOSE.test(purpose)) {
    throw new Error("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. The purpose is inside the hash, so a verify-email token can never
 * be replayed as a reset-password one. A fast hash is enough because the
 * token is at least 128 random bits.
 */
export function hashEmailToken(token: string, purpose: string): string {
  checkEmailTokenPurpose(purpose);
  if (typeof token !== "string" || token.length === 0) throw new Error("token must be a non-empty string");
  return hexEncode(sha256(utf8Encode(`${purpose}:${token}`)));
}

checkEmailToken throws on bad input 12 tests

export function checkEmailToken(records: readonly EmailTokenRecord[], token: string, purpose: string, now: number): EmailTokenCheck
recordsEmailTokenRecord[]the stored records to look in, usually the one row found by the token's hash
tokenstringthe token from the link
purposestringthe purpose this page accepts
nowintthe current time in Unix seconds
returnsEmailTokenCheckok, unknown, expired or used, without using the token up

For example

  • checkEmailToken(records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600) → outcome ok, record … a fresh token is ok
  • checkEmailToken(records ×4, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610) → outcome ok, record … found among several records
  • checkEmailToken(records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,229,199) → outcome ok, record … one second before expiry is still ok
import { checkEmailToken } from "#fune/auth.email-token@^1";
impl/typescript/check_email_token.ts · 45 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { type EmailTokenCheck, type EmailTokenRecord } from "./auth_email_token_types.ts";
import { constantTimeEqual } from "./crypto_constant_time_equal.ts";  ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
import { hexDecode } from "./encoding_hex_hex_decode.ts";
import { checkEmailTokenPurpose, hashEmailToken } from "./auth_email_token_hash_email_token.ts";  ← hashEmailToken, another function of this group · built into the same file, even by a slim install

const HASH = /^[0-9a-f]{64}$/;

/** Where a token's record is among records, and its outcome now: index -1 when unknown. */
export function findEmailToken(
  records: readonly EmailTokenRecord[],
  token: string,
  purpose: string,
  now: number,
): { readonly index: number; readonly check: EmailTokenCheck } {
  checkEmailTokenPurpose(purpose);
  if (typeof token !== "string") throw new TypeError("token must be a string");
  if (typeof now !== "number" || !Number.isInteger(now)) throw new TypeError("now must be a whole number of Unix seconds");
  if (!Array.isArray(records)) throw new TypeError("records must be a list of EmailTokenRecord");
  for (const r of records) {
    if (typeof r !== "object" || r === null || typeof r.tokenHash !== "string" || !HASH.test(r.tokenHash)) {
      throw new Error("tokenHash must be 64 lowercase hex characters");
    }
  }
  if (token.length === 0) return { index: -1, check: { outcome: "unknown", record: null } };
  const attempt = hexDecode(hashEmailToken(token, purpose));
  let index = -1;
  for (let i = 0; i < records.length; i++) {
    // Every record is compared, with no early exit.
    const same = constantTimeEqual(attempt, hexDecode(records[i].tokenHash));
    if (same && index < 0) index = i;
  }
  if (index < 0 || records[index].purpose !== purpose) return { index: -1, check: { outcome: "unknown", record: null } };
  const record = records[index];
  if (record.usedAt !== null && record.usedAt !== undefined) return { index, check: { outcome: "used", record } };
  if (now >= record.expiresAt) return { index, check: { outcome: "expired", record } };
  return { index, check: { outcome: "ok", record } };
}

/**
 * What a token from a link is worth now, without using it up: for the GET
 * that shows a reset form. Act only on consumeEmailToken's answer.
 */
export function checkEmailToken(records: readonly EmailTokenRecord[], token: string, purpose: string, now: number): EmailTokenCheck {
  return findEmailToken(records, token, purpose, now).check;
}

consumeEmailToken throws on bad input 10 tests

export function consumeEmailToken(records: readonly EmailTokenRecord[], token: string, purpose: string, now: number): EmailTokenResult
recordsEmailTokenRecord[]the stored records: the token's row, plus the subject's other rows for that purpose to retire them too
tokenstringthe token from the link
purposestringthe purpose this action accepts
nowintthe current time in Unix seconds
returnsEmailTokenResultthe outcome, and the records to write back

For example

  • consumeEmailToken(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 untouched
  • consumeEmailToken(records ×1, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,600) → outcome ok, record …, records ×1 ok: a lone record gets usedAt
  • consumeEmailToken(records ×2, AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8, reset-password, 1,767,225,610) → outcome ok, record …, records ×2 an already used sibling keeps its own usedAt
import { consumeEmailToken } from "#fune/auth.email-token@^1";
impl/typescript/consume_email_token.ts · 23 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { type EmailTokenRecord, type EmailTokenResult } from "./auth_email_token_types.ts";
import { findEmailToken } from "./auth_email_token_check_email_token.ts";  ← 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: the stored records in, the
 * outcome and the records to write back out. When ok, the token's record
 * gets usedAt = now, and so does every other unused record of the same
 * subject and purpose, so an older reset link dies when a newer one is used.
 * Any other outcome returns the records unchanged.
 */
export function consumeEmailToken(records: readonly EmailTokenRecord[], token: string, purpose: string, now: number): EmailTokenResult {
  const { index, check } = findEmailToken(records, token, purpose, now);
  if (check.outcome !== "ok" || check.record === null) {
    return { outcome: check.outcome, record: check.record, records: records.slice() };
  }
  const used = check.record;
  const next = records.map((r, i) =>
    i === index || ((r.usedAt === null || r.usedAt === undefined) && r.subject === used.subject && r.purpose === used.purpose)
      ? { ...r, usedAt: now }
      : r,
  );
  return { outcome: "ok", record: next[index], records: next };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 5 dependencies, pins them in fune.lock, downloads only the TypeScript 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
Download for TypeScript auth.email-token-1.0.0-typescript.fune · 46,602 bytes sha256 5e50e8643e1b51c3378f8c9bc6dba1135f22d181aed0fbf39a7a1da65b4a2672

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./auth.email-token-1.0.0-typescript.fune, or fetch it from a terminal with fune pull auth.email-token@1.0.0:typescript.

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

CaseArgumentsExpected
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
CaseArgumentsExpected
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

CaseArgumentsExpected
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

CaseArgumentsExpected
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
CaseArgumentsExpected
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

CaseArgumentsExpected
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.

Files

PathBytes
README.md4,303
impl/python/check_email_token.py2,037
impl/python/consume_email_token.py1,225
impl/python/generate_email_token.py1,592
impl/python/hash_email_token.py900
impl/rust/check_email_token.rs4,275
impl/rust/consume_email_token.rs1,919
impl/rust/generate_email_token.rs2,763
impl/rust/hash_email_token.rs1,402
impl/typescript/check_email_token.ts2,338
impl/typescript/consume_email_token.ts1,185
impl/typescript/generate_email_token.ts1,689
impl/typescript/hash_email_token.ts1,041
vectors.json24,409