Skip to content

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.

  1. Keep emailOtp on. It is on by default. emailOtp: false turns it off.
  2. Set emailOtp.length to 8 for an account of high value.
The email code config
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,
},
});
}
  1. In the app, call client.emailOtp.request({ email }).
  2. Show a field for the code. Then call client.emailOtp.verify({ email, code }).
  3. Store the token of the answer in the device’s secure store. A browser app keeps the cookie.
The sign-in by code in a device app
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() });
}
The flow as a test
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",
});
});
});
  • 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 maxAttempts spends the code. Every later try then answers too_many_attempts until a new request.
  • A wrong, expired, spent, or unknown code answers invalid_code. Core does not tell them apart.
  • Core stores HMAC-SHA256 under secret of 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 to your mail builder answers.
  • A request has three limits: otp:email:<email> 3 per 15 minutes, otp:ip:<ip> 20 per 15 minutes, and otp: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, and otp-verify:ip:<ip> 30 per 15 minutes.
  • A reset by code takes { email, code, password } at POST /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.