Build an account settings page
For: an app developer who builds the settings page of a signed-in person.
What it does: the page lists and ends the sessions, and asks for a re-authentication before a sensitive change. It changes the profile, the address, the providers, and the account.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- The fresh rule: read which changes need a fresh session.
- Nothing in the config. The account routes exist in every deployment.
- Show the sessions with
client.sessions.list(). Each row hascurrent, the device, and the time of the last refresh. - End one session with
client.sessions.revoke({ id }), or all the others withclient.sessions.revokeOthers(). End every session, this one too, withclient.sessions.revokeAll(). - Wrap each sensitive change in
client.withFresh(change, prove).proveasks for the password, an email code, or a passkey. - Change the name and the picture with
client.user.update({ name, image }). - Change the address with
client.user.changeEmail({ newEmail }). The person opens the link in the new mailbox. - List the providers with
client.identities.list(). - Link a provider with
client.identities.link({ provider }). Unlink one withclient.identities.unlink({ id }). - Delete the account with
client.user.delete().
import { type Clock, createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** * A settings page needs no config key: its routes exist in every deployment. * `session.freshMinutes` sets the fresh window. The default is 1440, one day. * A shorter window asks the person to prove it again sooner before a change. */export function createAccountAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string; /** Tests move the time. An app leaves it out. */ clock?: Clock;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, // One hour: a session older than this proves it again before a change. session: { freshMinutes: 60 }, // On by default. `delete: false` removes POST /user/delete. // `notices: false` turns the notice mails off. account: { delete: true }, ...(deps.clock ? { clock: deps.clock } : {}), });}import type { Client } from "@authtempo/client";
/** * The delete button of a settings page. A stale session answers * `session_not_fresh`. Then `withFresh` asks for an email code once, and sends * the delete again. A second refusal is the answer: `withFresh` never loops. * `askCode` is the app's own prompt. */export async function deleteAccount(client: Client, askCode: () => Promise<string>) { return client.withFresh( () => client.user.delete(), async () => { const sent = await client.reauth.requestEmailCode(); if (!sent.ok) return sent; return client.reauth.emailCode({ emailCode: await askCode() }); }, );}import { createClient } from "@authtempo/client";import { describe, expect, it } from "vitest";import { API, call, codeIn, harness, lastMailTo, linkIn, signIn } from "../support/harness.ts";import { createAccountAuth } from "./account-settings.ts";import { deleteAccount } from "./account-settings-client.ts";
/** A clock that the test moves. */function clock() { let now = Date.now(); return { now: () => new Date(now), advance(ms: number) { now += ms; }, };}
const HOUR = 3_600_000;
describe("account settings", () => { it("lists the sessions, and ends the others", async () => { const h = harness(); const auth = createAccountAuth(h); const phone = await signIn(auth, h, "ada@example.com"); await signIn(auth, h, "ada@example.com"); const list = (await ( await call(auth, "GET", "/auth/sessions", undefined, { cookie: phone }) ).json()) as { sessions: { current: boolean }[] }; expect(list.sessions.map((s) => s.current).sort()).toEqual([false, true]); const ended = await call(auth, "POST", "/auth/sessions/revoke-others", {}, { cookie: phone }); expect(await ended.json()).toEqual({ ended: 1 }); });
it("changes the address by a link to the new address, and tells the old one", async () => { const h = harness(); const auth = createAccountAuth(h); const ada = await signIn(auth, h, "ada@example.com"); const asked = await call( auth, "POST", "/auth/user/change-email", { newEmail: "ada@new.example.com" }, { cookie: ada }, ); expect(await asked.json()).toEqual({ sent: true }); const token = linkIn(h, "ada@new.example.com").searchParams.get("token"); const moved = await call(auth, "POST", "/auth/user/change-email/confirm", { token }); expect(((await moved.json()) as { user: { email: string } }).user.email).toBe( "ada@new.example.com", ); expect(lastMailTo(h, "ada@example.com").text).toContain( "The new address is ada@new.example.com.", ); });
it("asks a stale session to prove it again, and the same session deletes the account", async () => { const h = harness(); const time = clock(); const auth = createAccountAuth({ ...h, clock: time }); const cookie = await signIn(auth, h, "ada@example.com"); // Past the fresh window of one hour. The session itself lives on. time.advance(2 * HOUR); const token = cookie.split("=")[1] ?? ""; const sent: string[] = []; const client = createClient({ baseURL: API, credentials: "omit", token: () => token, broadcast: false, fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input, init); const res = await auth.handle(req); sent.push(`${new URL(req.url).pathname} ${res.status}`); return res; }) as typeof fetch, }); const r = await deleteAccount(client, async () => codeIn(h, "ada@example.com")); expect(r).toEqual({ ok: true, value: { ok: true } }); // The refusal, the code, the proof, and the delete once more. expect(sent).toEqual([ "/auth/user/delete 403", "/auth/reauth/email 200", "/auth/reauth 200", "/auth/user/delete 200", ]); expect(lastMailTo(h, "ada@example.com").text).toContain("Your account was deleted."); expect(await call(auth, "GET", "/auth/session", undefined, { cookie })).toMatchObject({ status: 401, }); });});The fresh rule
Section titled “The fresh rule”- A sign-in makes a session fresh for
session.freshMinutes, 1440 by default. A re-authentication makes it fresh again. The session token and the expiry stay the same. - These client calls can answer
session_not_fresh:sessions.revoke,sessions.revokeOthers,sessions.revokeAll,user.changeEmail,user.delete,username.set,phone.add,phone.verifyAdd,phone.remove,identities.unlink, andidentities.link. - The calls of the other guides can answer it too:
passkey.register,passkeys.delete,tokens.create, andtokens.update. - The three role writes can answer it:
organizations.roles.create,organizations.roles.update, andorganizations.roles.delete. - The organization calls can answer it:
organizations.tokens.create,organizations.tokens.update, andorganizations.members.removewithrevokeTokens: true. - Each call of
sso.domains,sso.connections, andscim.tokenscan answer it, for an owner of an organization. password.changecan answer it while the second factor is on, and for a first password.- The second factor calls can answer it:
totp.enable,totp.disable,totp.regenerateBackupCodes,secondFactor.passkey.enable,secondFactor.email.enable, andsecondFactor.disable. withFreshruns the change. Onsession_not_freshit runs your re-authentication, then the change once more.- A failed re-authentication is the answer, and the change does not run again. A second
session_not_freshis the answer too, sowithFreshnever loops. - Core checks the rule of
secondFactor.passkey.enableafter its passkey prompt. So underwithFresh, that call can show the prompt two times. - A stale session counts no try on a limit. The refusal changes no row.
- A bearer app gives the client a
tokenfunction. The client reads it once per call, so the change and its retry each read the token once.
How it behaves
Section titled “How it behaves”GET /sessionsandGET /identitiesneed a session only.lastSeenAtof a session moves only at the sliding refresh, at most once persession.slidingRefreshDays. Do not show it as the last activity.- The profile update needs no fresh session, because a name and a picture do not sign anyone in.
client.sessions.revoke({ id })answerscurrentfrom the server. Whencurrentis true, the caller’s own session ended. A bearer app clears its stored token then.- A change of address sends a link to the new address.
method: "code"sends a code in place of the link. - The link opens a confirm page that does nothing on load, so a mail scanner changes nothing. Its button posts the token.
account.confirmPagereplaces the page. - The move happens at the confirm. Then every other session ends, and the old address gets a notice that names the new one.
- By a link, the session that asked stays. By a code, the session that sends the code stays.
- When an account holds the new address, the new address gets a note and no link. The answer is the same, so the page learns nothing.
- A link needs the provider’s address to be verified and equal to the account’s address.
- The unlink and the passkey delete keep at least one way in. The last one answers
last_credential. - The delete takes each organization where the person is the only member. Another membership goes, and its organization stays.
- The last owner of an organization with other members gets
sole_owner, and nothing goes.account.delete: falseremoves the delete route. - With
account.deleteConfirmon,client.user.delete()answers{ sent: true }, mails a link, and deletes nothing. The link opens a page whose button deletes the account, with a session of the same person. The link lives 60 minutes by default, and a new request ends the older link. - The limits of the routes:
reauth:user:<userId>allows 10 per 15 minutes, andsession-revoke:user:<userId>allows 30 per 15 minutes. - More limits:
email-change:user:<userId>allows 5 per hour,unlink:user:<userId>10 per 15 minutes, anduser-delete:user:<userId>5 per hour.
The notice mails
Section titled “The notice mails”- A notice goes to the address after each change of a way in. It holds the event, the time, the IP address when core has it, and what to do.
- These changes send one: a password change or a first password, and a reset by link or by code.
- These changes send one too: a passkey added or removed, a provider linked or unlinked, and a second factor method on or off.
- A change of address sends one to the old address. The account delete sends one to the address of the deleted row.
- A notice holds no link and no code. Core sends it after the commit. A refused change and a change that rolls back send none.
- A notice that fails writes the line
authtempo: notice mail failed <event> <error name>, and the change stays. account.notices: falseturns every notice off.account.notices.mailreplaces the text. The proof mails stay on in both cases.
If it fails
Section titled “If it fails”session_not_fresh: the session is older than the fresh window. Re-authenticate, then send the change again.email_unverified: the profile, the address, and a link need a verified address.last_credential: add another way in first.identity_taken: the provider account belongs to another account.email_mismatch: the provider’s address differs from the account’s address.sole_owner: make another member an owner first.email_taken: an account took the new address before the confirm.conflict: a parallel write won five rounds. Send the change again.