Skip to content

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.

  • 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.
  1. Set anonymous to {}, or to an object with ttlDays.
  2. Pass the limiter of your adapter as limiter.
  3. Post {} to POST /anonymous/sign-in when a guest first needs a session. client.anonymous.signIn() makes the same call.
  4. Store the guest’s data under the user id of that session.
  5. Move the data in hooks.anonymous.afterLink, and only when proof is verified.
  6. Offer “Delete my data”: it posts {} to POST /anonymous/delete.
  7. On a public site, add the captcha flow anonymous-sign-in to captcha.flows.
A guest cart in the config
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) },
},
});
}
The guest and the upgrade as a test
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 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.

  • 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_refused at 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 anonymous off 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.
  • beforeLink runs inside the transaction of the sign-in. A refusal answers hook_refused, and the anonymous user and its session stay.
  • afterLink runs after the commit. Then the anonymous session ends with anonymous_upgrade, and the anonymous user goes, with user.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 ttlDays ago (30 by default) with no live session, at most anonymous.sweepBatch per run.
  • The limits: anonymous:ip 10 per hour, the cap anonymous:all-day of anonymous.dailyCap (1000 by default) per 24 hours, and anonymous-delete:user 5 per hour.
  • createAuth refuses anonymous with a limiter that counts per isolate. For tests only, set anonymous.isolateLimiter: "allow".
  • A throw of afterLink writes the line hook.after_failed and 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/continue is open to an anonymous session, so an anonymous user can hold more than one session. An upgrade ends each of them.
  • A POST /anonymous/delete in parallel with an upgrade can delete the anonymous user before afterLink runs. 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 in afterLink only.