Skip to content

Run the operator tools

For: an operator or an app developer who does support work on the users of a deployment.

What it does: this guide turns on the operator tools of core. Each act checks its actor, and writes its change and one audit row in one transaction.

  1. Make one operator secret for each job with authtempo secret --operator.
  2. Put the SHA-256 of each secret in operator.secrets, with the scopes of its job only.
  3. Set operator.users: true. Each tool is off by default.
  4. Send each audit row to a separate system from hooks.operator.afterAction.
  5. Call auth.api.operator from your admin route, with an app actor.
The config and an admin route
import {
type Auth,
createAuth,
type MailPort,
type OperatorAuditRow,
type StorageAdapter,
} from "@authtempo/core";
/** The jobs of the operator secrets, and the copy of the audit rows. The host gives each value. */
export interface OperatorSetup {
/** The SHA-256 of each secret, as `authtempo secret --operator` prints it. Never the secret. */
supportHash: string;
incidentHash: string;
/** Sends one audit row to a system that the app's database cannot change. */
copy: (row: OperatorAuditRow) => Promise<void>;
}
/**
* The user tools on. With no setup, only the platform operators and the app
* act. With a setup, each job gets its own named secret, and each audit row
* gets a copy.
*/
export function createOperatorAuth(
deps: { storage: StorageAdapter; mail: MailPort; secret: string },
setup?: OperatorSetup,
) {
return createAuth({
baseURL: "https://api.example.com",
trustedOrigins: [],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
// A platform operator is a user with the role `admin` in the organization `staff`.
organizations: { platformOrganization: "staff", platformRole: "admin" },
operator: {
users: true,
...(setup && {
secrets: [
// The support desk reads and bans users, and reads the audit table.
{ name: "support", secretHash: setup.supportHash, scopes: ["users", "audit"] },
// The incident script ends sessions, and does nothing else.
{ name: "incident", secretHash: setup.incidentHash, scopes: ["sessions"] },
],
}),
},
...(setup && {
hooks: {
operator: {
// After the commit, once per row. A person with write access to the database can change the table.
afterAction: ({ audit }) => setup.copy(audit),
},
},
}),
});
}
/**
* The actor of the app's admin page. Each audit row names it. Core trusts an
* app actor, so the app checks its own staff and counts its own limit first.
*/
export const ADMIN_ACTOR = { kind: "app", name: "admin-page" } as const;
/**
* The app's admin route: POST with the JSON body `{ userId, reason }`.
* `isStaff` is the app's own check of the person who calls it.
*/
export async function adminBan(
auth: Auth,
request: Request,
isStaff: (request: Request) => Promise<boolean>,
): Promise<Response> {
if (!(await isStaff(request))) return Response.json({ error: "forbidden" }, { status: 403 });
const body: unknown = await request.json().catch(() => null);
const { userId, reason } = (body ?? {}) as { userId?: unknown; reason?: unknown };
if (typeof userId !== "string" || typeof reason !== "string")
return Response.json({ error: "invalid_body" }, { status: 400 });
const banned = await auth.api.operator.users.ban({
actor: ADMIN_ACTOR,
userId,
reason,
// The staff member's address and browser, never the user's. Off Workers, pass the IP of your host.
ip: request.headers.get("cf-connecting-ip"),
userAgent: request.headers.get("user-agent"),
});
if (!banned.ok) return Response.json({ error: banned.code }, { status: banned.status });
return Response.json({ auditId: banned.value.auditId });
}
/** The audit rows of one user, oldest first, for the admin page. */
export async function adminAudit(auth: Auth, userId: string) {
const page = await auth.api.operator.audit.list({ actor: ADMIN_ACTOR, targetUserId: userId });
return page.ok ? page.value.rows : [];
}
The operator tools as a test
import { createHash } from "node:crypto";
import type { OperatorAuditRow } from "@authtempo/core";
import { describe, expect, it } from "vitest";
import { APP, call, harness, linkIn, signIn } from "../support/harness.ts";
import { ADMIN_ACTOR, adminAudit, adminBan, createOperatorAuth } from "./operator-tools.ts";
const SUPPORT = "support-secret-0123456789abcdef0123456789";
const INCIDENT = "incident-secret-0123456789abcdef012345678";
const hash = (s: string) => createHash("sha256").update(s).digest("hex");
function setup() {
const h = harness();
const copies: OperatorAuditRow[] = [];
const auth = createOperatorAuth(h, {
supportHash: hash(SUPPORT),
incidentHash: hash(INCIDENT),
copy: async (row) => {
copies.push(row);
},
});
return { h, auth, copies };
}
/** A POST of the admin page to the app's own route. */
const banRequest = (body: unknown) =>
new Request(`${APP}/admin/ban`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
async function userIdOf(auth: ReturnType<typeof setup>["auth"], email: string): Promise<string> {
const found = await auth.api.operator.users.search({ actor: ADMIN_ACTOR, email });
if (!found.ok) throw new Error(found.code);
return found.value.users[0]?.id ?? "";
}
describe("the operator tools", () => {
it("bans a user from the app's admin route, with an audit row and its copy", async () => {
const { h, auth, copies } = setup();
const cookie = await signIn(auth, h, "ada@example.com");
const userId = await userIdOf(auth, "ada@example.com");
const res = await adminBan(
auth,
banRequest({ userId, reason: "Spam from this account" }),
async () => true,
);
expect([res.status, await res.json()]).toEqual([200, { auditId: expect.any(String) }]);
// The ban ended the session in its transaction.
expect((await call(auth, "GET", "/auth/session", undefined, { cookie })).status).toBe(401);
// A new sign-in proves the credential first, and then learns of the ban.
await call(auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" });
const token = linkIn(h, "ada@example.com").searchParams.get("token") ?? "";
const again = await call(auth, "POST", "/auth/magic-link/verify", { token });
expect([again.status, await again.json()]).toEqual([403, { error: "account_banned" }]);
const rows = await adminAudit(auth, userId);
expect(rows.map((r) => [r.actorKind, r.actorId, r.action, r.reason])).toEqual([
["app", "admin-page", "ban", "Spam from this account"],
]);
expect(copies.map((r) => r.id)).toEqual(rows.map((r) => r.id));
});
it("writes nothing when the app's own staff check refuses", async () => {
const { h, auth, copies } = setup();
await signIn(auth, h, "ada@example.com");
const userId = await userIdOf(auth, "ada@example.com");
const res = await adminBan(auth, banRequest({ userId, reason: "Spam" }), async () => false);
expect(res.status).toBe(403);
expect([await adminAudit(auth, userId), copies]).toEqual([[], []]);
});
it("gives each named secret the scopes of its job only", async () => {
const { h, auth } = setup();
await signIn(auth, h, "ada@example.com");
const list = (secret: string) =>
call(auth, "GET", "/auth/operator/users", undefined, {
authorization: `Operator ${secret}`,
});
const support = await list(SUPPORT);
expect(support.status).toBe(200);
const incident = await list(INCIDENT);
expect([incident.status, await incident.json()]).toEqual([403, { error: "operator_required" }]);
});
});

Three actors can act. Each audit row names its actor, and never holds a secret.

Actor Who acts The name in the audit row
secret A script or the CLI, with a named operator secret The name of the entry in operator.secrets
user A platform operator: a user who holds organizations.platformRole in the platform organization The user id
app Your own code in process, as { kind: "app", name } The name: 1 to 64 characters of [a-z0-9_.-]
  • A secret needs the scope of the route: users, sessions, or audit. With no such scope, the route answers operator_required.
  • The scopes keys and secrets open the key rotation and the secret routes. The old operator.secretHash is one secret named default with these two scopes only.
  • A platform operator passes the operator user guard at each request. The guard checks five steps, in this order:
    • The session is not an impersonation session.
    • The user holds the platform role, and the session is not older than the last write of that role.
    • The address is verified.
    • A second factor has a method.
    • The session is fresh.
  • Each failed step answers one code, operator_required. So a caller learns nothing about the step that failed.
  • A user actor never acts on their own user (operator_self) or on another platform operator (operator_required). A secret and the app can act on a platform operator.
  • Core trusts an app actor, and checks only its name. Your app checks its own staff before the call.
  • An in-process call counts on no limiter. Your admin route needs a limit of its own.
  • A secret never starts an impersonation. Only a platform operator starts one.

The routes are under <basePath>/operator/. Routes lists each one. auth.api.operator holds the same acts in process, with the actor as an input. The in-process API lists each entry. The CLI wraps the routes in authtempo users, authtempo sessions, authtempo audit, and authtempo create-admin.

  • A request with an operator secret and a session answers 401 unauthorized: it has no single actor.
  • A route of a tool that is off answers 404, the answer of a path that does not exist. An in-process call answers not_found.
  • Each answer has cache-control: no-store.
  • Each write reads a JSON body only. Each write takes a reason. It is 1 to 500 UTF-16 code units with no control character, line or paragraph separator, lone surrogate, or format character except U+200C and U+200D.
  • A secret call counts on operator-users:ip:<ip> before the compare, 600 an hour. A secret that matches also counts on operator-users:secret:<name>, 600 an hour from any IP.
  • A platform operator counts on operator:user:<userId>, 600 an hour. Limits lists each key.

users.create makes an account for a person, with an address or with a phone number only. It needs the scope users. The route is POST /operator/users/create, and authtempo users create wraps it.

  • firstSignIn: "invite" mails an invitation link. It is the default with an address.
  • firstSignIn: "reset" mails a reset link, so the person sets a password. It needs the password config.
  • firstSignIn: "none" mails nothing. The person signs in by any proof of the address, such as a magic link.
  • email: null with a phone in E.164 makes a user with no address. It needs the phone config, and allows none only.
  • The phone form sends no SMS at the create. The person asks for a phone code at the first sign-in.
  • A phone beside an address answers invalid_body, after the scope check and before any read. A phone number that the operator chose would let the operator sign in to the account by a phone code. That sign-in would have no impersonation mark, no time limit, and no audit row.
  • The create does not read signUp. It is the way in of an app whose self sign-up is closed: the operator, not a stranger, makes the user.
  • user.beforeCreate runs with via: "operator", so a hook of the app can still refuse the user.
  • No operator path sets a password. The answer holds no token, no link, and no code.
  • A caller with no users scope gets operator_required before any read. So the create tells nothing about an address to that caller.
  • A taken address or number answers email_taken or phone_taken, writes nothing, and mails no one.
  • The mail goes after the commit. A mail that fails keeps the user, answers mailed: null, and emits the event operator.create_mail_failed.
  • An address of a domain that enforces SSO gets no link. The create writes no invitation row, mails nothing, and answers mailed: null. The person signs in through the SSO connection.
  • The audit row user_create holds four flags: emailVerified, firstSignIn, hasAddress, and hasPhone. It never holds the address, the number, or the name.
  • Each actor gets 200 creates an hour through the route, on operator-create:actor:<kind>:<id>. A refused call counts too.
An app with a closed sign-up, and the create of a ticket
import {
type Auth,
createAuth,
type LimiterPort,
type MailPort,
type SmsPort,
type StorageAdapter,
} from "@authtempo/core";
import { inviteMail } from "./operator-invite.ts";
/** A placeholder port that sends nothing. Write the port of your SMS supplier. */
const NO_SMS: SmsPort = { send: async () => "unavailable" };
/**
* An app whose self sign-up is closed. The support desk creates each account.
* Pass the limiter of your D1, Postgres, or MySQL adapter: the phone config
* needs a shared limiter. Only a test passes "isolate-for-tests".
*/
export function createOperatorUsersAuth(
deps: {
storage: StorageAdapter;
mail: MailPort;
secret: string;
limiter: LimiterPort | "isolate-for-tests";
},
sms: SmsPort = NO_SMS,
) {
const forTests = deps.limiter === "isolate-for-tests";
return createAuth({
baseURL: "https://api.example.com",
appURL: "https://app.example.com",
trustedOrigins: ["https://app.example.com"],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
...(deps.limiter === "isolate-for-tests" ? {} : { limiter: deps.limiter }),
// No stranger makes an account. The operator create does not read this rule.
signUp: false,
// The first sign-in "reset" needs the password config.
password: {},
// A user with a phone number only signs in with a phone code.
phone: {
sms,
regions: ["+44"],
signUp: false,
...(forTests ? { isolateLimiter: "allow" as const } : {}),
},
// The gate of the invitation, totp.gate.invite, is on by default.
totp: { issuer: "Example" },
// A platform operator is a user with the role `admin` in the organization `staff`.
organizations: { platformOrganization: "staff", platformRole: "admin" },
// The invitation mail in the words of the app (operator-invite.ts).
account: { mail: inviteMail },
operator: {
users: true,
// The life of an invitation link: 1 to 168 hours. The default is 72.
invite: { ttlHours: 24 },
},
});
}
/**
* The actor of the support desk. Core trusts an app actor, so the app checks
* its own staff and counts its own limit before each call.
*/
export const SUPPORT_DESK = { kind: "app", name: "support-desk" } as const;
/** A ticket that asks for an account. Give an address, or a phone number only. */
export interface AccountRequest {
ticket: string;
email: string | null;
phone?: string;
name?: string;
/** "invite" by default with an address. A phone number only allows "none". */
firstSignIn?: "invite" | "reset" | "none";
}
/** Creates the account of a ticket. The answer holds no token and no link. */
export async function createForPerson(auth: Auth, request: AccountRequest) {
const created = await auth.api.operator.users.create({
actor: SUPPORT_DESK,
email: request.email,
...(request.phone !== undefined && { phone: request.phone }),
...(request.name !== undefined && { name: request.name }),
...(request.firstSignIn !== undefined && { firstSignIn: request.firstSignIn }),
// The audit row keeps the reason after the account is gone: put your case id here.
reason: `ticket ${request.ticket}`,
// The staff member's address and browser, never the person's.
ip: null,
userAgent: null,
});
if (!created.ok) return { error: created.code };
// mailed is "invite", "reset", or null: what the person got.
return { userId: created.value.userId, mailed: created.value.mailed };
}
  • The link lives operator.invite.ttlHours: 1 to 168 hours, 72 by default. Core stores the SHA-256 of the ui_ token only.
  • The mail is the kind user_invite of account.mail. An app writes its own text, and core sends it to the address of the user.
  • GET /user/invite/confirm shows a page that reads nothing and spends nothing, because a mail scanner fetches links. Its button posts the token.
  • POST /user/invite/confirm spends the link once, in one conditional update. A second use answers invalid_token.
  • The link holds the address of the create. After a change of the address, the old link answers invalid_token.
  • A wrong, spent, or expired link answers the same invalid_token. The person signs in by a magic link at the address.
  • The link proves the address, and opens a session with the via invite.
  • totp.gate.invite is on by default. A user with the second factor on gets a challenge, not a session. A trusted device skips it.
  • An address of a domain that enforces SSO answers sso_required. The person signs in through the SSO connection.
  • Each POST counts on user-invite-confirm:ip:<ip>, 20 per 15 minutes, before the token check.
  • The operator never sees the link. It is not in an answer, an audit row, a log line, a hook event, or the CLI output.
  • An account delete removes the invitation row of the user.
The invitation mail in the words of the app
import { type AccountMailInput, defaultAccountMail, type MailMessage } from "@authtempo/core";
/**
* The account mails of the app. Only the invitation changes here: the other
* kinds keep the default text. Core sends each mail to the address of the
* input. The link is the only copy of the token: no answer holds it.
*/
export function inviteMail(input: AccountMailInput): MailMessage {
if (input.kind !== "user_invite") return defaultAccountMail(input);
const life = input.ttlHours === 1 ? "1 hour" : `${input.ttlHours} hours`;
return {
to: input.email,
subject: `Your ${input.appName} account is ready`,
text: [
`Our support team made an account on ${input.appName} for this address.`,
`Open this link to sign in. It works once, for ${life}.`,
"",
input.link,
"",
"Our support team cannot see this link. If you did not ask for an account, ignore this mail.",
].join("\n"),
};
}

emailVerified: true is a statement of the operator, not a proof. Give it only after your own check of the address.

  • It lets the app add the user to an organization before the first sign-in. A member add needs a verified address.
  • Core takes the address as proved. So no later proof resets the account, and the claim rule never runs for it.
  • A wrong address gives the account to the owner of that address. That person can sign in by a magic link.
  • The audit row records the flag, so a later reader sees who stated it.
  • It needs an address. A user with a phone number only cannot have the flag.
Add a created user to an organization
import type { Auth, UserRow } from "@authtempo/core";
import { SUPPORT_DESK } from "./operator-users.ts";
/**
* Creates a user and adds the user to an organization before the first
* sign-in. `owner` is the user of the admin page, with the rank to add a
* member. A member add needs a verified address, so the desk states it.
* Set `emailVerified: true` only after your own check of the address: a
* wrong address gives the account to the owner of that address.
*/
export async function addCreatedMember(
auth: Auth,
owner: UserRow,
input: { email: string; organizationId: string; ticket: string },
) {
const created = await auth.api.operator.users.create({
actor: SUPPORT_DESK,
email: input.email,
// The statement of the desk, not a proof. The audit row records the flag.
emailVerified: true,
firstSignIn: "invite",
reason: `ticket ${input.ticket}`,
ip: null,
userAgent: null,
});
if (!created.ok) return created;
return auth.api.addMember({
user: owner,
organizationId: input.organizationId,
userId: created.value.userId,
role: "member",
});
}

users.update corrects the name or the image of a user. It needs the scope users.

  • Give name, image, or both. Null clears a field, and an absent field stays. With neither, the act answers invalid_body.
  • The name and the image follow the rules of the profile update of the user.
  • The act never changes the address, emailVerified, a password, a passkey, the username, the phone, the second factor, or a ban. Each has its own flow.
  • The route answers invalid_body for any other key, such as password, email, or emailVerified.
  • The act ends no session and sends no mail: a name and an image are not credentials.
  • user.beforeUpdate and user.afterUpdate run with via: "operator". The audit row user_update names the changed fields, never a value.
  • A platform operator cannot update their own user (operator_self) or another platform operator (operator_required).
Correct a profile from a ticket
import type { Auth } from "@authtempo/core";
import { SUPPORT_DESK } from "./operator-users.ts";
/**
* Corrects the name or the image of a user. Null clears a field, and a
* field that is absent stays. The address, the verified flag, the
* credentials, and the sessions have their own flows: this act never
* changes them.
*/
export async function correctProfile(
auth: Auth,
userId: string,
change: { name?: string | null; image?: string | null },
ticket: string,
) {
const done = await auth.api.operator.users.update({
actor: SUPPORT_DESK,
userId,
...change,
reason: `ticket ${ticket}`,
ip: null,
userAgent: null,
});
if (!done.ok) return { error: done.code };
// The audit row names the changed fields, never a value.
return { name: done.value.user.name, auditId: done.value.auditId };
}
  • With the phone config, core counts a stored phone as a proved handle (plan 12i). A proved handle opens the username, a phone add, and an API token.
  • A phone that an operator stored is not proved until the first phone sign-in. No code went to it at the create.
  • Every route that needs a proved handle also needs a session. The only session of that user is a phone session, and a phone session proves the number.
  • An in-process call of the app on that user, before the first phone sign-in, is the decision of the app. Wait for the first phone session.
Create a user with a phone number only
import type { Auth } from "@authtempo/core";
import { SUPPORT_DESK } from "./operator-users.ts";
/**
* Creates a user with a phone number only. No SMS goes out at the create:
* the person asks for a phone code at the first sign-in. Until then, no
* code proved the number. Do not act on that user in process as if the
* number were proved: wait for the first phone session.
*/
export async function createPhoneOnly(auth: Auth, phone: string, ticket: string) {
const created = await auth.api.operator.users.create({
actor: SUPPORT_DESK,
// Null on purpose: the user has no address.
email: null,
phone,
reason: `ticket ${ticket}`,
ip: null,
userAgent: null,
});
return created.ok ? { userId: created.value.userId } : { error: created.code };
}
The user acts as a test
import { base32Decode, createRecordingSms, totpCode } from "@authtempo/core/testing";
import { describe, expect, it } from "vitest";
import { call, callSettled, harness, linkIn, sessionCookieOf, signIn } from "../support/harness.ts";
import { createPhoneOnly } from "./operator-phone.ts";
import { correctProfile } from "./operator-update.ts";
import { createForPerson, createOperatorUsersAuth, SUPPORT_DESK } from "./operator-users.ts";
import { addCreatedMember } from "./operator-verified.ts";
const CONFIRM = "/auth/user/invite/confirm";
const PASSWORD = "correct horse battery";
const PHONE = "+447700900123";
/** A test passes the test limiter. An app passes the limiter of its adapter. */
function setup() {
const h = harness();
const sms = createRecordingSms();
const auth = createOperatorUsersAuth({ ...h, limiter: "isolate-for-tests" }, sms);
return { h, sms, auth };
}
type World = ReturnType<typeof setup>;
/** The audit rows of one user, as the desk reads them. */
async function auditOf({ auth }: World, userId: string) {
const page = await auth.api.operator.audit.list({ actor: SUPPORT_DESK, targetUserId: userId });
if (!page.ok) throw new Error(page.code);
return page.value.rows;
}
/** The token of the invitation link in the last mail to an address. */
const inviteToken = (h: World["h"], to: string) => linkIn(h, to).searchParams.get("token") ?? "";
/** The user of a session cookie pair. */
async function userOf({ auth }: World, cookie: string) {
const resolved = await auth.api.getSession(cookie.slice(cookie.indexOf("=") + 1));
if (!resolved) throw new Error("no session");
return resolved.user;
}
describe("create a user", () => {
it("mails an invitation, a reset link, or nothing, with self sign-up closed", async () => {
const w = setup();
expect(await createForPerson(w.auth, { ticket: "4710", email: "ada@example.com" })).toEqual({
userId: expect.any(String),
mailed: "invite",
});
expect(linkIn(w.h, "ada@example.com").pathname).toBe(CONFIRM);
const reset = await createForPerson(w.auth, {
ticket: "4711",
email: "bo@example.com",
firstSignIn: "reset",
});
expect(reset).toEqual({ userId: expect.any(String), mailed: "reset" });
const none = await createForPerson(w.auth, {
ticket: "4712",
email: "cy@example.com",
firstSignIn: "none",
});
expect(none).toEqual({ userId: expect.any(String), mailed: null });
expect(w.h.sent.map((m) => m.to)).toEqual(["ada@example.com", "bo@example.com"]);
// A taken address mails no one, and writes nothing.
expect(await createForPerson(w.auth, { ticket: "4713", email: "ada@example.com" })).toEqual({
error: "email_taken",
});
expect(w.h.sent.length).toBe(2);
});
it("creates a user with a phone number only, and sends no SMS", async () => {
const w = setup();
const made = await createForPerson(w.auth, { ticket: "4714", email: null, phone: PHONE });
expect(made).toEqual({ userId: expect.any(String), mailed: null });
expect([w.sms.sent, w.h.sent]).toEqual([[], []]);
});
});
describe("the invitation link", () => {
it("opens one session, and the operator never sees the link", async () => {
const w = setup();
const made = await createForPerson(w.auth, { ticket: "4720", email: "ada@example.com" });
const mail = w.h.sent.at(-1);
expect(mail?.text).toContain("It works once, for 24 hours.");
const token = inviteToken(w.h, "ada@example.com");
expect(token.startsWith("ui_")).toBe(true);
if (!("userId" in made)) throw new Error(made.error);
// The answer and the audit row hold no part of the link.
const rows = await auditOf(w, made.userId);
expect(JSON.stringify([made, rows]).includes(token)).toBe(false);
expect(rows.map((r) => [r.action, r.data])).toEqual([
[
"user_create",
{ emailVerified: false, firstSignIn: "invite", hasAddress: true, hasPhone: false },
],
]);
const first = await call(w.auth, "POST", CONFIRM, { token });
expect(first.status).toBe(200);
const user = await userOf(w, sessionCookieOf(first));
expect([user.id, user.emailVerified]).toEqual([made.userId, true]);
const again = await call(w.auth, "POST", CONFIRM, { token });
expect([again.status, await again.json()]).toEqual([400, { error: "invalid_token" }]);
});
it("answers the challenge for a user with the second factor on", async () => {
const w = setup();
const made = await w.auth.api.operator.users.create({
actor: SUPPORT_DESK,
email: "ada@example.com",
emailVerified: true,
reason: "ticket 4721",
ip: null,
userAgent: null,
});
if (!made.ok) throw new Error(made.code);
const token = inviteToken(w.h, "ada@example.com");
// The person signs in by a magic link first, and turns TOTP on.
const ada = await signIn(w.auth, w.h, "ada@example.com");
await call(w.auth, "POST", "/auth/password/change", { newPassword: PASSWORD }, { cookie: ada });
const setupRes = await call(
w.auth,
"POST",
"/auth/totp/setup",
{ password: PASSWORD },
{ cookie: ada },
);
const { secret } = (await setupRes.json()) as { secret: string };
const enabled = await call(
w.auth,
"POST",
"/auth/totp/enable",
{ code: await totpCode(base32Decode(secret), new Date()) },
{ cookie: ada },
);
expect(enabled.status).toBe(200);
const res = await call(w.auth, "POST", CONFIRM, { token });
expect(res.status).toBe(200);
expect("twoFactor" in ((await res.json()) as object)).toBe(true);
expect(sessionCookieOf(res)).toBe("");
});
});
describe("the verified flag", () => {
it("lets an owner add the user before the first sign-in", async () => {
const w = setup();
await createForPerson(w.auth, {
ticket: "4730",
email: "ada@example.com",
firstSignIn: "none",
});
const ada = await signIn(w.auth, w.h, "ada@example.com");
const org = await call(
w.auth,
"POST",
"/auth/organizations/create",
{ slug: "team", name: "Team" },
{ cookie: ada },
);
const { organization } = (await org.json()) as { organization: { id: string } };
const owner = await userOf(w, ada);
const added = await addCreatedMember(w.auth, owner, {
email: "bo@example.com",
organizationId: organization.id,
ticket: "4731",
});
expect(added.ok && added.value.role).toBe("member");
if (!added.ok) throw new Error(added.code);
const [row] = await auditOf(w, added.value.userId);
expect(row?.data).toMatchObject({ emailVerified: true });
// Without the flag, the add waits for a proof of the address.
const cy = await createForPerson(w.auth, { ticket: "4732", email: "cy@example.com" });
if (!("userId" in cy)) throw new Error(cy.error);
const refused = await w.auth.api.addMember({
user: owner,
organizationId: organization.id,
userId: cy.userId,
role: "member",
});
expect(refused.ok ? "ok" : refused.code).toBe("email_unverified");
});
});
describe("update a name or an image", () => {
it("changes the name only, and keeps the address and the sessions", async () => {
const w = setup();
await createForPerson(w.auth, {
ticket: "4740",
email: "ada@example.com",
firstSignIn: "none",
});
const ada = await signIn(w.auth, w.h, "ada@example.com");
const before = await userOf(w, ada);
const done = await correctProfile(w.auth, before.id, { name: "Ada King" }, "4741");
expect(done).toEqual({ name: "Ada King", auditId: expect.any(String) });
const after = await userOf(w, ada);
expect([after.name, after.email, after.emailVerified]).toEqual([
"Ada King",
before.email,
before.emailVerified,
]);
const rows = await auditOf(w, before.id);
expect(rows.find((r) => r.action === "user_update")?.data).toEqual({ fields: ["name"] });
expect(await correctProfile(w.auth, before.id, { name: null }, "4742")).toEqual({
name: null,
auditId: expect.any(String),
});
expect(await correctProfile(w.auth, before.id, {}, "4743")).toEqual({
error: "invalid_body",
});
});
});
describe("the phone-only residual", () => {
it("proves the number at the first phone sign-in", async () => {
const w = setup();
const made = await createPhoneOnly(w.auth, PHONE, "4750");
if (!("userId" in made)) throw new Error(made.error);
expect(w.sms.sent).toEqual([]);
// The SMS goes out after the answer: callSettled waits for that work.
await callSettled(w.auth, "POST", "/auth/phone/request", { phone: PHONE });
const code = /\d{6}/.exec(w.sms.sent.at(-1)?.text ?? "")?.[0] ?? "";
const res = await call(w.auth, "POST", "/auth/phone/verify", { phone: PHONE, code });
expect(res.status).toBe(200);
const { user } = (await res.json()) as { user: { id: string; email: string | null } };
expect([user.id, user.email]).toEqual([made.userId, null]);
});
});
  • users.ban writes the ban in one transaction. The same transaction ends every challenge, handoff code, and OAuth refresh token and code of the user. It ends a page of the sessions too.
  • The whole call fits 50 storage calls, the limit of one D1 Free run. The sessions that do not fit stay, with one pending-end row. The sweep ends them with session.afterEnd and the reason banned.
  • Until the sweep ends a left session, every door refuses it: the session read, the session JWT mint, and api.jwt.sessionLive.
  • The pending-end row also covers a session that began in the 5 seconds after the act. So does the row of a revoke and of a SCIM deactivate.
  • This bound covers a server whose clock runs ahead of the clock of the act. The cost: the sweep also ends a sign-in in those 5 seconds, for example after a fast unban.
  • A test on D1 banned a user with 60 sessions and a session.afterEnd hook. A secret ban ended 31 sessions in 50 queries. Two sweeps of 48 and 24 queries ended the other 29.
  • A sign-in of a banned user answers account_banned only after the credential check. So only a person who proved the credential learns of the ban. A wrong password answers invalid_credentials, as for any user.
  • The mail flows answer a banned user as any user.
  • An API token stays. Core refuses it while the ban holds, and it works again after an unban.
  • A refused call of an API token spends nothing of its window or its quota: the ban check comes first (plan 12k).
  • An organization token that the user made still acts: it belongs to the organization. Revoke it, or remove the member with revokeTokens: true.
  • The unban restores no session. A session, a refresh token, or an access token from before the end of the ban stays refused. For a refresh token, the start of its family counts: the refresh grant and introspection refuse a new row of an old family too.
  • A ban of a platform operator also ends the impersonation sessions that the operator opened. The call ends those that fit, and the sweep ends the rest. Until then each door refuses them.
  • A session JWT and an OAuth access token live to their exp. Ban a user gives the check of a resource server.
  • An answer with familyEndFailed: true means that the ban committed, and the end of the OAuth families after the commit failed. Call sessions.endUser for the user: it reads the refresh tokens again, and ends each family. The CLI prints a warning: line for it and exits 1.
  • sessions.endUser ends the sessions, challenges, handoff codes, and OAuth refresh tokens and codes of one user. One call ends one page. Call again while more is true.
  • sessions.endAll ends up to limit sessions of all users in one call: 500 by default, at most 1000. It keeps the session of a user actor. Call again while more is true.
  • ASVS 5.0.0 7.4.5 asks for both: “Verify that application administrators are able to terminate active sessions for an individual user or for all users.”
  • sessions.endAll ends the sessions only. The OAuth refresh tokens and the API tokens of every user stay. No tool ends every grant of every user after a breach.
  • Each call fits 50 storage calls with the calls before it. With a session.afterEnd hook, one page ends 45 sessions for the app, 43 for a secret, and 36 for a user actor.
  • No act sends a back-channel sign-out message in its call. The messages are due at once, and the sweep sends them.
  • platformRole.grant adds the role to a user with a verified address and no active ban. platformRole.revoke takes it away.
  • A revoke ends the access of the user as a ban does: a page of the sessions in the act, the rest at the sweep. A second revoke ends one more page. Until then each operator check refuses the left sessions.
  • A revoke that leaves the platform organization with no owner answers last_owner.
  • A session from before the last write of the role row holds no operator power. So after a grant or a re-grant, the operator signs in again.
  • createAdmin makes the first operator. The first operator gives the steps.
  • secondFactor.disable turns the whole second factor of a user off. It takes the proof of an identity check, { method, reference, checkedAt }.
  • ASVS 5.0.0 6.4.4: “Verify that if a multi-factor authentication factor is lost, evidence of identity proofing is performed at the same level as during enrollment.”
  • Core checks no proof. It keeps the method, the reference, and the time in the audit row. Your controls are that row and hooks.operator.beforeAction, which can check the reference in your case system.
  • The method knowledge alone is below the level of an enrollment. Answers about an account prove less than the factor did. Use document, in_person, or video.
  • Before the act, look for a recent change of the address. A person who took the account can change the address, and then ask for a recovery. user.afterUpdate with via: "email_change" sees each change.
  • checkedAt is at most 7 days old, and not later than the clock of the deployment.
  • The act ends no session. The user gets the notice factor_disabled unless account.notices is false. The notice holds no IP of the operator.
  • operator.impersonation turns it on, and needs operator.users and organizations.platformRole. ttlMinutes is 5 to 240, and 60 by default.
  • A platform operator starts it with POST /operator/impersonate, from their own fresh session with a second factor. Each operator gets 20 starts an hour.
  • A target that is the operator, a platform operator, banned, or absent answers impersonation_refused. It is one code for the four cases.
  • The new session has a fixed expiry. No refresh moves it, and it has no fresh time.
  • The operator’s own token goes into the actor cookie: the session cookie name with _actor at its end. POST /operator/impersonate/stop ends the session and gives the operator’s token back.
  • A session JWT of the session holds act: { sub: <operator id> } (RFC 8693 section 4.1). Its exp is no later than the expiry of the session.
  • The user’s session list marks the session with impersonation: true, with no operator id.
  • The user gets the notice impersonation_started at each start. operator.impersonation.notice: false turns it off, and so does account.notices: false. The notice holds no IP of the operator.
  • When the operator loses the platform role, each impersonation session of the operator ends. A ban, a revoke, a removal, a leave, a role change, and an account delete of the operator each count.
  • A ban and a revoke end those sessions inside their call budget, and the sweep ends the rest.
  • An account delete of an operator ends a page of the impersonation sessions of that operator at once. So does a removal, a leave, or a role change of the platform member row. The sweep ends the rest with stop rows (cause account_delete or role_loss). Until then every door refuses each left session.

An impersonation session can never reach the routes of IMPERSONATION_REFUSED. Each answers 403 impersonation_session before its handler:

  • each operator route but the stop;
  • the sign-out: the operator stops the session instead;
  • each multi-session route: the bag of the browser holds the operator’s other sessions, not the user’s;
  • the re-authentication, which would make the session fresh;
  • each change of a way in: the password, a passkey, the address, the username, the phone, an unlink, a social link, a new API token;
  • the account delete, and the delete of an anonymous user;
  • each second-factor route;
  • the handoff start and the handoff continue;
  • the OAuth authorize, sign-in, device approval, grant revoke, and end-session routes;
  • the organization delete, and the add, the role change, the removal, and the invitation of a member.
  • the role writes of dynamic roles, and the token writes: an API token narrow, and an organization token create, narrow, or revoke.
  • the domain writes of SSO: the add, the verify, the update, and the delete of a domain (plan 12d).
  • the connection writes of SSO: the create, the update, and the delete of a connection to a sign-in provider (plan 12d).
  • the SCIM token writes: the create and the revoke of the tokens of a directory, because a token outlives the impersonation (plan 12d).
  • the setup link routes of SSO: the mint, the list, the get, the revoke, and the activate (plan 13a).
  • each route of a setup session, because the link gives the power of the organization (plan 13a).
  • Each act writes one row of operatorAudit (table ta_operator_audit), as the last write of its transaction. The act commits with its row, or neither commits.
  • A row holds actorKind, actorId, action, targetUserId, reason, data, ip, userAgent, and the time. ip and userAgent are the actor’s, never the target’s.
  • An impersonation start and its stop each write a row. An expiry writes none. Each other end of an impersonation session writes a stop row, with its cause in data.
  • On a storage whose user delete cascades, an account delete records the impersonation sessions that the cascade ends. The sweep writes their stop rows from its next run. Such a row also holds endedAt in data, the time of the delete. A delete of a user with more than 100 live impersonation sessions answers delete_too_large.
  • afterAction runs for these stop rows too, after the commit of the flow. beforeAction does not run for them.
  • Core never updates or deletes a row. The sweep reads the table only for a user whose delete recorded impersonation sessions. It reads the stop rows of that user from 5 s before the delete, at most the newest 200. It writes no second stop row for a session that one of these rows names. A person with write access to the database can still change a row.
  • ASVS 5.0.0 16.4.3: “Verify that logs are securely transmitted to a logically separate system for analysis, detection, alerting, and escalation.” hooks.operator.afterAction is that path.
  • afterAction runs once per row after the commit. A throw writes one log line, and the act stays.
  • On D1, core undoes a failed act with an undo log. When the Worker stops inside the act, the undo cannot run. So an act can stay with no row.
  • The account delete keeps the rows. A kept row holds the user id, the operator’s reason, and data, such as the reference of a factor proof.
  • The table has no address column. A row holds an IP of a deleted user only when that user was a platform operator who acted.
  • Core has no retention rule for the table. Your app owns it: decide how long you keep the rows, and delete old rows with your own database job.

users.search takes one key: email, id, or emailPrefix. A prefix has 3 to 254 characters, and matches with case and with no wildcard. It compiles to substr(<column>, 1, <n>) = <prefix>, and no index serves that. So a prefix search reads the whole user table.

The measurement of 2026-10-20 at 03:00 UTC: one search for a prefix that no address has, on a table of 10 000 users. The load averages of the machine were 4.98, 7.68, and 8.85.

Engine Plan Rows read
D1 in Miniflare 5.20261006.0-alpha, in memory SCAN ta_user 10 000 (meta.rows_read)
Postgres 17 (postgres:17-alpine in Docker) Seq Scan, 0.386 ms 10 000, all removed by the filter
  • limit bounds the rows that come back, not the rows read.
  • The limits per IP, per secret, and per operator bound the scans an hour. An in-process call counts on no limiter.
  • not_found: the tool is off, or no user has the id.
  • unauthorized: no credential, a wrong secret, or a secret beside a session.
  • operator_required: the secret lacks the scope, or the session fails a step of the guard.
  • rate_limited: a limit of the hour is spent.
  • invalid_body: a body that is not JSON, a bad reason, a bad app name, a bad proof, or a date out of range. A create with a phone beside an address answers it too.
  • origin_not_trusted: a session caller posted from an origin outside trustedOrigins.
  • operator_self: a platform operator acted on their own user.
  • account_banned: the target of a grant or of createAdmin is banned.
  • email_unverified: the target of a grant has no verified address.
  • last_owner: the revoke would leave the platform organization with no owner.
  • member_limit: the platform organization holds its most members.
  • totp_not_enabled: the user has no second factor to turn off.
  • email_taken: an account holds the address of the create. Find it with a search; the create mailed no one.
  • phone_taken: an account holds the phone number of the create.
  • phone_invalid: the phone number of the create is not in E.164 form.
  • phone_region: the phone number of the create is outside phone.regions.
  • sole_owner: the delete target is the last owner of an organization with other members, or of the platform organization.
  • delete_too_large: the user alone holds more than 50 organizations, or on D1 the delete cannot fit 50 queries. Delete the solo organizations of the user, or let the user leave the organizations that the user owns with another owner, first.
  • impersonation_refused: the target is the operator, a platform operator, banned, or absent.
  • impersonation_session: an impersonation session called a refused route.
  • conflict: another write changed the row at the same time. Try again.
  • hook_refused: hooks.operator.beforeAction or another before hook refused the act.
  • hook_failed: a before hook threw another error.
  • invalid_token: the person opened an invitation link that is wrong, spent, or past its life, or the address of the user changed since the create. Create no second user: the person signs in by a magic link at the address.
  • sso_required: the invitation link names an address of a domain that enforces SSO. The person signs in through the SSO connection.