Sign in with an email code
For: an app developer whose users sign in on a device where the mailbox is not, or whose mail client strips links.
What it does: core mails a code. The person types the code into the app, and the app gets a session.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- A
passwordconfig, only if you also want the reset by code. Passwords lists its keys.
- Keep
emailOtpon. It is on by default.emailOtp: falseturns it off. - Set
emailOtp.lengthto 8 for an account of high value.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
export function createEmailCodeAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, // Email codes are on by default. `emailOtp: false` turns them off. emailOtp: { // 6 or 8 digits. Eight digits divide the odds of a guess by 100. length: 8, // The life of a code, 1 to 60 minutes. The default is 10. ttlMinutes: 10, // The wrong codes that spend a code, 3 to 10. The default is 5. maxAttempts: 5, }, });}- In the app, call
client.emailOtp.request({ email }). - Show a field for the code. Then call
client.emailOtp.verify({ email, code }). - Store the
tokenof the answer in the device’s secure store. A browser app keeps the cookie.
import type { Client } from "@authtempo/client";
/** * The sign-in of a phone or desktop app by email code. `askCode` shows a field * and answers what the person types. The answer holds the bearer token: store * it in the device's secure store. */export async function signInByCode(client: Client, email: string, askCode: () => Promise<string>) { const sent = await client.emailOtp.request({ email }); if (!sent.ok) return sent; return client.emailOtp.verify({ email, code: await askCode() });}import { createClient } from "@authtempo/client";import { describe, expect, it } from "vitest";import { API, call, codeIn, harness } from "../support/harness.ts";import { createEmailCodeAuth } from "./email-code.ts";import { signInByCode } from "./email-code-client.ts";
describe("sign in with an email code", () => { it("signs a device in with the code of the mail", async () => { const h = harness(); const auth = createEmailCodeAuth(h); const client = createClient({ baseURL: API, credentials: "omit", fetch: ((input: RequestInfo | URL, init?: RequestInit) => auth.handle(new Request(input, init))) as typeof fetch, }); const r = await signInByCode(client, "ada@example.com", async () => codeIn(h, "ada@example.com"), ); expect(r.ok && "token" in r.value && r.value.token.startsWith("ts_")).toBe(true); });
it("answers invalid_code to a wrong code, and too_many_attempts at the fifth", async () => { const h = harness(); const auth = createEmailCodeAuth(h); await call(auth, "POST", "/auth/otp/request", { email: "bo@example.com" }); const right = codeIn(h, "bo@example.com"); const wrong = right === "00000000" ? "11111111" : "00000000"; for (let i = 0; i < 4; i++) expect( await ( await call(auth, "POST", "/auth/otp/verify", { email: "bo@example.com", code: wrong }) ).json(), ).toEqual({ error: "invalid_code", }); expect( await ( await call(auth, "POST", "/auth/otp/verify", { email: "bo@example.com", code: wrong }) ).json(), ).toEqual({ error: "too_many_attempts", }); expect( await ( await call(auth, "POST", "/auth/otp/verify", { email: "bo@example.com", code: right }) ).json(), ).toEqual({ error: "too_many_attempts", }); });});How it behaves
Section titled “How it behaves”- One code per address and purpose is live. A new request spends the earlier code.
- A wrong code counts one guess. The guess that reaches
maxAttemptsspends the code. Every later try then answerstoo_many_attemptsuntil a new request. - A wrong, expired, spent, or unknown code answers
invalid_code. Core does not tell them apart. - Core stores HMAC-SHA256 under
secretof the row id and the code. A copy of the table gives no code. - Core sends each code to the address of the code, whatever
toyour mail builder answers. - A request has three limits:
otp:email:<email>3 per 15 minutes,otp:ip:<ip>20 per 15 minutes, andotp:email-day:<email>20 per 24 hours. - A verify or a reset by code has two limits:
otp-verify:email:<email>10 per 15 minutes, andotp-verify:ip:<ip>30 per 15 minutes. - A reset by code takes
{ email, code, password }atPOST /auth/otp/reset. A refused password spends the code. - A sign-in or a reset by code of a user with the second factor on answers a challenge, not a session. Turn on the second factor tells the next step.
If it fails
Section titled “If it fails”invalid_body: the request has no valid address or code.invalid_code: the code is wrong, old, or spent. Ask the person to type it again.too_many_attempts: the code took its last guess. Request a new code.rate_limited: a limit of the request or of the verify is full. Wait 15 minutes, or 24 hours after 20 requests in a day.password_policyandpassword_breached: the reset refused the new password, and spent the code.