Anonymous sessions
For: an app developer who lets a person use the app before they make an account, such as a shop with a cart.
What it does: POST /anonymous/sign-in makes a user with no address and opens its session. A later sign-in in the same browser replaces that user, and hooks.anonymous moves the app’s data.
Before you start
Section titled “Before you start”- A sign-in method for the real account, such as Sign in with a magic link.
- A limiter that counts for the whole deployment: the D1, Postgres, or MySQL limiter. Limits names each one.
- A scheduled sweep, as in The sweep. It deletes the old guests.
- Set
anonymousto{}, or to an object withttlDays. - Pass the limiter of your adapter as
limiter. - Post
{}toPOST /anonymous/sign-inwhen a guest first needs a session.client.anonymous.signIn()makes the same call. - Store the guest’s data under the user id of that session.
- Move the data in
hooks.anonymous.afterLink, and only whenproofisverified. - Offer “Delete my data”: it posts
{}toPOST /anonymous/delete. - On a public site, add the captcha flow
anonymous-sign-intocaptcha.flows.
import { createAuth, type LimiterPort, type MailPort, type StorageAdapter } from "@authtempo/core";
/** The app's own data: here, the cart of each user id. */export type Carts = Map<string, string[]>;
/** * The link hook body: move the guest's cart into the account. Move data only * on a verified proof. An unverified proof can be a claim of an address by * someone else, and the real owner would get the data. */export function moveGuestCart(carts: Carts) { return (e: { anonymousUser: { id: string }; user: { id: string }; proof: "verified" | "unverified"; }): void => { const { anonymousUser, user, proof } = e; if (proof !== "verified") return; const cart = carts.get(anonymousUser.id) ?? []; carts.set(user.id, [...(carts.get(user.id) ?? []), ...cart]); carts.delete(anonymousUser.id); };}
/** * A guest session first, and the guest's cart moves at the first real * sign-in. Pass the limiter of your D1, Postgres, or MySQL adapter: the * daily cap counts per deployment. Only a test passes "isolate-for-tests", * and its cap then counts per isolate. */export function createGuestAuth( deps: { storage: StorageAdapter; mail: MailPort; secret: string; limiter: LimiterPort | "isolate-for-tests"; }, carts: Carts = new Map(),) { 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 }), magicLink: {}, anonymous: { // The sweep deletes a guest with no live session after this many days. ttlDays: 30, // Tests only. With a limiter that counts per isolate, createAuth refuses anonymous. ...(forTests ? { isolateLimiter: "allow" as const } : {}), }, hooks: { anonymous: { afterLink: moveGuestCart(carts) }, }, });}import { createMemoryLimiter, systemClock } from "@authtempo/core";import { describe, expect, it } from "vitest";import { call, harness, linkIn, sessionCookieOf } from "../support/harness.ts";import { type Carts, createGuestAuth, moveGuestCart } from "./anonymous.ts";
/** A test passes the test value. An app passes the limiter of its adapter. */const forTests = () => ({ ...harness(), limiter: "isolate-for-tests" as const });
describe("anonymous sessions", () => { it("moves the guest cart into the account at a magic link in the same browser", async () => { const h = forTests(); const carts: Carts = new Map(); const auth = createGuestAuth(h, carts); const guest = await call(auth, "POST", "/auth/anonymous/sign-in", {}); const { user } = (await guest.json()) as { user: { id: string; email: string | null } }; expect(user.email).toBeNull(); carts.set(user.id, ["tea"]);
// The request and the verify both carry the guest session cookie. const cookie = sessionCookieOf(guest); await call(auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" }, { cookie }); const token = linkIn(h, "ada@example.com").searchParams.get("token") ?? ""; const res = await call(auth, "POST", "/auth/magic-link/verify", { token }, { cookie }); const signedIn = (await res.json()) as { user: { id: string } };
expect(carts.get(signedIn.user.id)).toEqual(["tea"]); expect(carts.has(user.id)).toBe(false); });
it("moves no data on an unverified proof", () => { // A password sign-in with uniformSignUp false links with proof "unverified". const carts: Carts = new Map([["guest", ["tea"]]]); const move = moveGuestCart(carts); move({ anonymousUser: { id: "guest" }, user: { id: "claimant" }, proof: "unverified" }); expect(carts.get("guest")).toEqual(["tea"]); expect(carts.has("claimant")).toBe(false); move({ anonymousUser: { id: "guest" }, user: { id: "owner" }, proof: "verified" }); expect(carts.get("owner")).toEqual(["tea"]); });
it("refuses a way in on a guest session", async () => { const auth = createGuestAuth(forTests()); const cookie = sessionCookieOf(await call(auth, "POST", "/auth/anonymous/sign-in", {})); const res = await call(auth, "POST", "/auth/user/update", { name: "Ada" }, { cookie }); expect(res.status).toBe(403); expect(await res.json()).toEqual({ error: "anonymous_refused" }); });
it("refuses a memory limiter outside tests: the cap is per deployment", () => { const limiter = createMemoryLimiter(systemClock); expect(() => createGuestAuth({ ...harness(), limiter })).toThrow(/shared limiter/); });
it("refuses a call with no limiter, as from plain JavaScript", () => { // The type needs a limiter. A call that skips the type check gets the refusal. const deps = harness() as never; expect(() => createGuestAuth(deps)).toThrow(/shared limiter/); });});The proof rule
Section titled “The proof rule”The link event holds proof: "verified" or proof: "unverified". Move data only on verified.
An unverified proof can be a claim. With password.uniformSignUp: false, a person can sign in with a password to an address that nobody verified. When the real owner later proves the address, the claim rule gives the owner the account. Data that moved on the unverified proof would then reach the owner.
With uniformSignUp: true, the default, the session of a password sign-up opens at the confirm link. That proof is verified.
How it behaves
Section titled “How it behaves”- The anonymous user has no address, no phone, no passkey, and no password. Its session is its only key. No second factor gates it.
- A live anonymous session answers itself and makes nothing. A live session of another kind answers
conflict. - An anonymous session gets 403
anonymous_refusedat each route that needs a way in, or that would change the user in place. These are the re-authentication, the profile, the address, the username, the account delete, each way in, and the second factor. - The list also holds the organization create, the invitation accept, the API token create, the OAuth consent, and the device approve. It holds with
anonymousoff too. - A sign-in that carries a live anonymous session makes or finds its own user. It never changes the anonymous user into the user of the sign-in.
beforeLinkruns inside the transaction of the sign-in. A refusal answershook_refused, and the anonymous user and its session stay.afterLinkruns after the commit. Then the anonymous session ends withanonymous_upgrade, and the anonymous user goes, withuser.afterDelete.- A proof by mail or SMS links only when the completing request carries the anonymous session that asked for it. So a stranger cannot move data into your account with a link for your address.
- A social sign-in links the anonymous user of its start. A password, passkey, or ID-token sign-in links the anonymous session of its own request.
- An SSO sign-in, a password reset that opens a session, and a handoff link nothing. The sweep deletes that anonymous user later.
- The sweep deletes an anonymous user made more than
ttlDaysago (30 by default) with no live session, at mostanonymous.sweepBatchper run. - The limits:
anonymous:ip10 per hour, the capanonymous:all-dayofanonymous.dailyCap(1000 by default) per 24 hours, andanonymous-delete:user5 per hour. createAuthrefusesanonymouswith a limiter that counts per isolate. For tests only, setanonymous.isolateLimiter: "allow".
Residuals
Section titled “Residuals”- A throw of
afterLinkwrites the linehook.after_failedand keeps the anonymous user, but no later sign-in links it. Move the data from that line before the sweep deletes the user. POST /handoff/continueis open to an anonymous session, so an anonymous user can hold more than one session. An upgrade ends each of them.- A
POST /anonymous/deletein parallel with an upgrade can delete the anonymous user beforeafterLinkruns. The same person does both, so no other person gets the data. - Two sign-ins at once from one anonymous session can each run
beforeLink, and only one links. So move data inafterLinkonly.
If it fails
Section titled “If it fails”anonymous_refused: the route needs a real account. Sign in first.conflict: the browser holds a session of another kind already.rate_limited: the IP made 10 guests this hour, or the deployment reached the daily cap.captcha_required,captcha_failed, andcaptcha_unavailable: the captcha flowanonymous-sign-inrefused the request.sign_up_closed:signUpis not"open".hook_refused:beforeLinkrefused the sign-in. The guest session stays.hook_failed: a hook of your app threw.unauthorized:POST /anonymous/deleteneeds a session.invalid_body: the body is not JSON.impersonation_session: an operator who impersonates a user cannot delete the guest.