Skip to content

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.

  • Password sign-in, as in Passwords.
  • A mail transport in mail.send that delivers within the life of the code, 10 minutes by default. Top level lists the mail key.
  • The waitUntil of your host, passed to auth.handle, as in Start on Workers with D1. The sign-up work goes after the answer.
  1. Set password.verifyBy to "code". Set password.verifyCodeMail for your own text, or keep the default. Set password.verifyCode for another length, life, or count of tries.
  2. Show a code field after the sign-up answers { sent: true, signUpProof }. A browser keeps the proof as a cookie. A native app keeps signUpProof. So does an app on another site than the auth origin, because many browsers drop its third-party cookie.
  3. Post { email, code } to POST /password/verify/code. A native app adds signUpProof, and so does an app on another site. A browser gets the session cookie. A native app reads token from the answer.
  4. When the answer says passwordKept: false, show a first-password form. It posts { newPassword } to POST /password/change with the new session.
  5. Offer “Send a new code”: it posts { email } to POST /password/verify/resend. An app that keeps signUpProof adds it.
  6. With password.requireVerified on, a sign-in before the confirm mails a new code. An app that keeps signUpProof adds it to the sign-in body, so the new code keeps the password.
The code in place of the link
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.`,
}),
},
});
}
The code as a test
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" });
});
});
  • By default, the code has 6 digits from crypto.getRandomValues and lives 10 minutes. Core stores HMAC-SHA256 of the row id and the code under the app secret, never the code.
  • password.verifyCode changes the code: length 6 to 10 digits, ttlMinutes 1 to 30, and maxAttempts 1 to 10 (default 5). A value outside its range stops createAuth.
  • One code is live per address. A resend spends the earlier code.
  • A wrong code counts one try. The wrong try number maxAttempts spends the code and answers too_many_attempts. Then the person asks for a new code.
  • A wrong, expired, or spent code and an address with no code answer invalid_code alike, 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, the user.afterCreate hooks, 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.handle waits for that work before it answers, so delivery holds. Then the time can tell the two apart. Pass the waitUntil.
  • 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:ip 30 and password-verify-code:email 10 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 maxAttempts guesses 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-email and the email-verification resend map onto these routes. Its verify answer adds passwordKept.
  • The shim maps the plugin’s otpLength, expiresIn, and allowedAttempts onto password.verifyCode, with Better Auth’s defaults of 300 seconds and 3 tries. An expiresIn over 1800 seconds stops betterAuth().
  • The shim sets password.uniformSignUp to 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.
  • invalid_code: the code is wrong, expired, or spent, or the address has no code. Ask for a new code.
  • too_many_attempts: maxAttempts wrong 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.