Skip to content

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.

  1. Show the sessions with client.sessions.list(). Each row has current, the device, and the time of the last refresh.
  2. End one session with client.sessions.revoke({ id }), or all the others with client.sessions.revokeOthers(). End every session, this one too, with client.sessions.revokeAll().
  3. Wrap each sensitive change in client.withFresh(change, prove). prove asks for the password, an email code, or a passkey.
  4. Change the name and the picture with client.user.update({ name, image }).
  5. Change the address with client.user.changeEmail({ newEmail }). The person opens the link in the new mailbox.
  6. List the providers with client.identities.list().
  7. Link a provider with client.identities.link({ provider }). Unlink one with client.identities.unlink({ id }).
  8. Delete the account with client.user.delete().
The config
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 } : {}),
});
}
The delete button with a re-authentication
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() });
},
);
}
The settings page as a test
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,
});
});
});
  • 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, and identities.link.
  • The calls of the other guides can answer it too: passkey.register, passkeys.delete, tokens.create, and tokens.update.
  • The three role writes can answer it: organizations.roles.create, organizations.roles.update, and organizations.roles.delete.
  • The organization calls can answer it: organizations.tokens.create, organizations.tokens.update, and organizations.members.remove with revokeTokens: true.
  • Each call of sso.domains, sso.connections, and scim.tokens can answer it, for an owner of an organization.
  • password.change can 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, and secondFactor.disable.
  • withFresh runs the change. On session_not_fresh it 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_fresh is the answer too, so withFresh never loops.
  • Core checks the rule of secondFactor.passkey.enable after its passkey prompt. So under withFresh, 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 token function. The client reads it once per call, so the change and its retry each read the token once.
  • GET /sessions and GET /identities need a session only.
  • lastSeenAt of a session moves only at the sliding refresh, at most once per session.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 }) answers current from the server. When current is 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.confirmPage replaces 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: false removes the delete route.
  • With account.deleteConfirm on, 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, and session-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, and user-delete:user:<userId> 5 per hour.
  • 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: false turns every notice off. account.notices.mail replaces the text. The proof mails stay on in both cases.
  • 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.