Verify an email address
If your app asks for an email address, you decide how far to trust it. Anyone can type someone else’s address into a sign-up form, so an address on its own proves nothing. Before you create an account for an address, mail a code to it, and create the account only after the person types that code back.
This guide shows that check in three parts: the code your server mails and checks, the browser step that holds the passkey back until the address is confirmed, and the account write that runs after the passkey exists. Keyhaw never sees the address, so every part lives in your app.
The confirmation belongs to the one browser that asked for the code. keyhaw.dev’s own sign-up checks an address this way, and the samples follow its token, its single-use code, and its spent confirmation. The browser sends the cookie on its own, since fetch sends cookies to the same origin by default.
Mail and check the code
Section titled “Mail and check the code”Your server mails a six-digit code and keeps only a keyed digest of it, so a leaked table gives no code away. The code lives five minutes and accepts five wrong guesses at most. It also works once, since the confirm route deletes it when a guess matches.
The server also mints a random token and sets it in an HttpOnly cookie, and it keys the pending code by the token’s SHA-256 and never by the address. The browser that asked for the code holds the token, and your table holds only the hash, so a leaked table gives no cookie away. Your route also caps how many codes one address and one client can request, so nobody can use it to flood a stranger’s inbox. Keyhaw does not count these limits for you, so your own code enforces them.
The sketch below uses your own database and mailer, so swap in yours.
const CODE_SPACE = 1_000_000const UINT32_LIMIT = 4_294_967_296 - (4_294_967_296 % CODE_SPACE)
// Draws again above the limit, so every six-digit code is equally likely.function drawCode(): string { const draw = new Uint32Array(1) do { crypto.getRandomValues(draw) } while (draw[0] >= UINT32_LIMIT) return String(draw[0] % CODE_SPACE).padStart(6, "0")}
// 32 random bytes in base64url, the token only this browser will hold.function mintToken(): string { const bytes = crypto.getRandomValues(new Uint8Array(32)) return btoa(String.fromCharCode(...bytes)) .replaceAll("+", "-") .replaceAll("/", "_") .replaceAll("=", "")}
export async function POST(request: Request) { const { email } = await request.json() const address = email.trim().toLowerCase() const code = drawCode() // The browser keeps the token and your table keeps only its hash, so no one who reads the table // can act for this browser const token = mintToken() const id = await sha256Hex(token) await db.emailCodes.upsert({ id, email: address, // HMAC-SHA-256 of the row's ID and the code, keyed with a secret only your server holds code_digest: await keyedDigest(id, code), attempts: 0, expires_at: Date.now() + 5 * 60_000, }) await mailer.send({ to: address, text: `Your code is ${code}` }) return Response.json( { sent: true }, { headers: { // HttpOnly keeps the token from page script, and the __Host- prefix makes a browser refuse // the cookie from a subdomain or without Secure and Path=/ "set-cookie": `__Host-sign_up=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600`, }, }, )}The confirm route checks a guess. It finds the code by the cookie’s token, and it spends an attempt before it compares anything, so a guess always counts against the limit, even one that is right. A match stores the confirmation under the same token hash.
export async function POST(request: Request) { const { code } = await request.json() // The cookie's token finds this browser's code, and no other browser has it const token = readCookie(request, "__Host-sign_up") if (token === null) return Response.json({ status: "code_void" }) const id = await sha256Hex(token) // One update spends the attempt, and its condition checks that the code is live and under the limit. const spent = await db.emailCodes.spendAttempt({ id, maxAttempts: 5, now: Date.now() }) if (spent === null) return Response.json({ status: "code_void" }) if ((await keyedDigest(id, code)) !== spent.code_digest) { return Response.json({ status: "wrong_code", attempts_left: 5 - spent.attempts }) } // One batch stores the confirmation under this token and deletes the code, so the code cannot // confirm again await db.batch([ db.confirmedEmails.upsert({ id, email: spent.email, confirmed_at: Date.now() }), db.emailCodes.remove({ id }), ]) return Response.json({ status: "confirmed" })}A code_void answer means the code expired, used up its attempts, was never sent to this browser, or was already used, so the person asks for a new one.
Hold the passkey until the address is confirmed
Section titled “Hold the passkey until the address is confirmed”The browser holds the sign-up back with keyhaw.on("user.creating", ...). The handler runs before the passkey prompt opens, and it cannot wait for anything, so it stops the sign-up with preventDefault() and starts the code request without awaiting it. Once the server confirms the address, the handler lets the next click through.
import { createKeyhaw } from "keyhaw/client"
const keyhaw = createKeyhaw()const form = document.querySelector<HTMLFormElement>("#sign-up")const email = document.querySelector<HTMLInputElement>("#email")const createButton = document.querySelector<HTMLButtonElement>("#create")// The address the server confirmed. Null until a code is confirmed.let confirmed: string | null = null
keyhaw.on("user.creating", (event) => { if (event.form !== form || email === null) return const address = email.value.trim().toLowerCase() if (address === confirmed) return // Stop the sign-up before any await, so no passkey opens for an address nobody confirmed event.preventDefault() void mailCode(address)})
if (createButton !== null) { createButton.addEventListener("click", async () => { const result = await keyhaw.signUp({ button: createButton }) // A stopped sign-up resolves with no data, so the account is written only after the passkey exists if (result.data !== null && confirmed !== null) { // The server writes the account with the address it confirmed for this browser's cookie const { status } = (await postJson("/api/account", {})) as { status: string } // Show the person what the answer says. `address_taken` means sign in with that address's passkey. if (status !== "completed") showError(status) } })}
// The address a code was last mailed to, which the code form confirmslet pending: string | null = null
async function mailCode(address: string): Promise<void> { await postJson("/api/email-code", { email: address }) pending = address // Show the code input beside the sign-up button, as your UI does}
// Submit handler for the code input, whose field is named `code`document.querySelector<HTMLFormElement>("#code")?.addEventListener("submit", (event) => { event.preventDefault() const code = new FormData(event.currentTarget as HTMLFormElement).get("code") if (pending !== null && typeof code === "string") void confirmCode(pending, code)})
async function confirmCode(address: string, code: string): Promise<void> { const { status } = (await postJson("/api/email-confirm", { code })) as { status: string } if (status === "confirmed") confirmed = address}
async function postJson(url: string, body: unknown): Promise<unknown> { const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), }) return response.json()}The handler lets the passkey open only when the address in the input is the one the server confirmed, so the passkey is always named after a confirmed address. Changing the address stops the sign-up again, until the new address is confirmed too.
Write the account after the passkey exists
Section titled “Write the account after the passkey exists”The account is written by your server, after the passkey signs the user in. The server finds the confirmation by the cookie’s token, checks that it is under 30 minutes old, and writes the account with the address the confirmation holds. It deletes the confirmation in the same batch that writes the account, so one confirmation makes one account. The browser check is not enough on its own, since a script can call your server without the page. So your own routes must refuse a user with no account row, as keyhaw.dev’s dashboard does.
The confirmation is tied to the browser because an address alone proves nothing about who is asking. If the account route looked a confirmation up by address, someone else who signs up with an address another person just confirmed could claim that confirmation and create an account for it. With the cookie, only the browser that received the code can use it, and spending it ends the claim.
import { session } from "keyhaw/server"
export async function POST(request: Request) { const user = await session(request) if (user === null) return new Response(null, { status: 401 }) // Find the confirmation by the cookie's token and never by the address, so only the browser that // confirmed the address can use it const token = readCookie(request, "__Host-sign_up") if (token === null) return Response.json({ status: "not_confirmed" }, { status: 409 }) const id = await sha256Hex(token) // Only a confirmation made in the last 30 minutes counts const since = Date.now() - 30 * 60_000 const confirmed = await db.confirmedEmails.findRecent({ id, since }) if (confirmed === null) return Response.json({ status: "not_confirmed" }, { status: 409 }) // One batch writes the account with the confirmed address and deletes the confirmation, so the // confirmation is spent only if the account is written. The unique index on the account's email // refuses an address another account holds, and that rolls the batch back. try { const [written] = await db.batch([ db.accounts.insertFromConfirmation({ user_id: user.id, id, since }), db.confirmedEmails.remove({ id, since }), ]) // Nothing written means a request with the same cookie already spent the confirmation if (written === 0) return Response.json({ status: "not_confirmed" }, { status: 409 }) } catch (error) { if ((await db.accounts.findByEmail(confirmed.email)) === null) throw error return Response.json({ status: "address_taken" }, { status: 409 }) } return Response.json( { status: "completed" }, { headers: { // Clear the cookie, since its confirmation is spent "set-cookie": "__Host-sign_up=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0", }, }, )}The unique index does the work that a check cannot. Two sign-ups that race for one address both pass the check, and the index lets only one write. The other gets address_taken. The duplicate sign-up guide covers an account that gets through both checks.