Prove the address by a code
For: an app developer whose users sign up with a password on a device with no mailbox, such as a TV or a kiosk.
What it does: password.verifyBy: "code" mails a code (6 digits by default) at sign-up in place of the verify link. The person types it in the app, and POST /password/verify/code confirms the address and opens the session.
Before you start
Section titled “Before you start”- Password sign-in, as in Passwords.
- A mail transport in
mail.sendthat delivers within the life of the code, 10 minutes by default. Top level lists themailkey. - The
waitUntilof your host, passed toauth.handle, as in Start on Workers with D1. The sign-up work goes after the answer.
- Set
password.verifyByto"code". Setpassword.verifyCodeMailfor your own text, or keep the default. Setpassword.verifyCodefor another length, life, or count of tries. - Show a code field after the sign-up answers
{ sent: true, signUpProof }. A browser keeps the proof as a cookie. A native app keepssignUpProof. So does an app on another site than the auth origin, because many browsers drop its third-party cookie. - Post
{ email, code }toPOST /password/verify/code. A native app addssignUpProof, and so does an app on another site. A browser gets the session cookie. A native app readstokenfrom the answer. - When the answer says
passwordKept: false, show a first-password form. It posts{ newPassword }toPOST /password/changewith the new session. - Offer “Send a new code”: it posts
{ email }toPOST /password/verify/resend. An app that keepssignUpProofadds it. - With
password.requireVerifiedon, a sign-in before the confirm mails a new code. An app that keepssignUpProofadds it to the sign-in body, so the new code keeps the password.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** Password sign-up that proves the address by a mailed code, not a link. */export function createCodeProofAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, password: { verifyBy: "code", // Optional: your own text. Core sends it to the address, whatever `to` says. verifyCodeMail: ({ email, code, appName, ttlMinutes }) => ({ to: email, subject: `Your ${appName} code`, text: `${code} confirms your address. It expires in ${ttlMinutes} minutes.`, }), }, });}import { describe, expect, it } from "vitest";import { API, APP, codeIn, harness } from "../support/harness.ts";import { createCodeProofAuth } from "./verify-by-code.ts";
const post = (path: string, body: unknown) => new Request(`${API}/auth${path}`, { method: "POST", headers: { "content-type": "application/json", origin: APP }, body: JSON.stringify(body), });
describe("prove the address at sign-up by a code", () => { it("mails a code, and the code opens the session", async () => { const h = harness(); const auth = createCodeProofAuth(h); const work: Promise<unknown>[] = []; // The code goes out after the answer: give handle the waitUntil of your host. const up = await auth.handle( post("/password/sign-up", { email: "ada@example.com", password: "correct horse battery" }), { waitUntil: (p) => void work.push(p) }, ); // A native app keeps the sign-up proof and sends it with the code, so the password stays. const { signUpProof } = (await up.json()) as { sent: true; signUpProof: string }; await Promise.all(work); const code = codeIn(h, "ada@example.com"); const res = await auth.handle( post("/password/verify/code", { email: "ada@example.com", code, signUpProof }), ); expect(res.status).toBe(200); expect(await res.json()).toMatchObject({ passwordKept: true }); expect(res.headers.getSetCookie()[0]).toMatch(/^__Host-tempo_session=/); });
it("answers invalid_code for a wrong code and for an address with no code", async () => { const auth = createCodeProofAuth(harness()); const res = await auth.handle( post("/password/verify/code", { email: "nobody@example.com", code: "123456" }), ); expect(res.status).toBe(400); expect(await res.json()).toEqual({ error: "invalid_code" }); });});How it behaves
Section titled “How it behaves”- By default, the code has 6 digits from
crypto.getRandomValuesand lives 10 minutes. Core stores HMAC-SHA256 of the row id and the code under the app secret, never the code. password.verifyCodechanges the code:length6 to 10 digits,ttlMinutes1 to 30, andmaxAttempts1 to 10 (default 5). A value outside its range stopscreateAuth.- One code is live per address. A resend spends the earlier code.
- A wrong code counts one try. The wrong try number
maxAttemptsspends the code and answerstoo_many_attempts. Then the person asks for a new code. - A wrong, expired, or spent code and an address with no code answer
invalid_codealike, with the same work. The answer does not tell whether the address has an account. - With a
waitUntil, the sign-up answers{ sent: true }after the limits, the body checks, and the password hash. The user rows, theuser.afterCreatehooks, and the mail then run after the answer. - A known and a new address do the same work before the answer. So the time of the answer does not tell whether the address has an account.
- On Workers with no
waitUntil,auth.handlewaits for that work before it answers, so delivery holds. Then the time can tell the two apart. Pass thewaitUntil. - The resend reads the user and sends the code after the answer too.
- A right code runs the confirm of the link. It verifies the address and applies the claim rule: the other sessions and credentials of the unverified user end. Then it opens the session with
via: "password". - A code confirmed with the proof of its sign-up keeps the password. A code confirmed without it is a claim: the password goes, and the answer says
passwordKept: false. See The confirm of a sign-up. - A user who is already verified gets
{ verified: true, passwordKept: true }and no session. An unverified user cannot turn on the second factor, so the code never opens a session past it. - A code asked from an anonymous session links that anonymous user only when the confirm carries the same anonymous session.
- The code check counts
password-verify-code:ip30 andpassword-verify-code:email10 per 15 minutes. The resend counts the limits of Limits. - The sign-up and each resend count
password-verify-code:email-day: 10 code mails per address a day. A known and an unknown address count the same. - So one address gets at most 10 times
maxAttemptsguesses a day. With the defaults that is 50 guesses at a code of 6 digits: 1 chance in 20 000. - The Better Auth shim maps
emailOTP({ overrideDefaultEmailVerification: true })to this mode./email-otp/verify-emailand theemail-verificationresend map onto these routes. Its verify answer addspasswordKept. - The shim maps the plugin’s
otpLength,expiresIn, andallowedAttemptsontopassword.verifyCode, with Better Auth’s defaults of 300 seconds and 3 tries. AnexpiresInover 1800 seconds stopsbetterAuth(). - The shim sets
password.uniformSignUpto false, as Better Auth does. So its sign-up answer tells a known address. On Workers, the time of its resend also tells an unverified user with a password.
If it fails
Section titled “If it fails”invalid_code: the code is wrong, expired, or spent, or the address has no code. Ask for a new code.too_many_attempts:maxAttemptswrong tries spent the code. Ask for a new code.rate_limited: too many tries from this IP or for this address. Wait 15 minutes. After 10 code mails to the address, wait a day.sso_required: the address is of a domain that signs in by SSO only.account_banned: an operator banned the account after the mail.