Several accounts in one browser
For: an app developer whose users have a work account and a home account, and switch between them.
What it does: with multiSession, a sign-in of a second user keeps the first session in an HttpOnly bag cookie. GET /multi-session lists the sessions, and POST /multi-session/switch makes one active.
Before you start
Section titled “Before you start”- A browser sign-in with the session cookie, as in Sign in with a magic link.
- The cookie rules of Cookies. The bag cookie follows them.
- Set
multiSessionto{}, or to{ max }from 2 to 10. - Offer “Add an account”: it runs a normal sign-in in the same browser.
- Call
GET /multi-sessionwith the cookies, and show eachuser. - On a click, post
{ sessionId }toPOST /multi-session/switch. - Offer “Sign out of this account”: it posts
{ sessionId }toPOST /multi-session/sign-out. - Offer “Sign out of all accounts”: it posts to
POST /sign-out. - In a browser app, call
client.multiSession.list,client.multiSession.switch, andclient.multiSession.signOutof the client package in place of the calls.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** The sessions of several users in one browser, with a switch between them. */export function createMultiSessionAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { 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, magicLink: {}, multiSession: { // The sessions of one browser, the active one included: 2 to 10, 5 by default. max: 3, }, });}import { describe, expect, it } from "vitest";import { call, type Harness, harness, linkIn, sessionCookieOf } from "../support/harness.ts";import { createMultiSessionAuth } from "./multi-session.ts";
type Auth = ReturnType<typeof createMultiSessionAuth>;
/** A cookie jar of one browser: each Set-Cookie replaces or clears its name. */function jar() { const cookies = new Map<string, string>(); return { header: () => [...cookies].map(([k, v]) => `${k}=${v}`).join("; "), // The bag cookie holds its tokens joined by dots. values: () => [...cookies.values()].flatMap((v) => v.split(".")), take(res: Response) { for (const line of res.headers.getSetCookie()) { const [pair = ""] = line.split(";"); const at = pair.indexOf("="); const [name, value] = [pair.slice(0, at), pair.slice(at + 1)]; if (value === "" || /max-age=0/i.test(line)) cookies.delete(name); else cookies.set(name, value); } }, };}
/** A magic link sign-in in the browser of the jar. */async function signIn(auth: Auth, h: Harness, browser: ReturnType<typeof jar>, email: string) { await call(auth, "POST", "/auth/magic-link/request", { email }); const token = linkIn(h, email).searchParams.get("token") ?? ""; const res = await call( auth, "POST", "/auth/magic-link/verify", { token }, { cookie: browser.header(), }, ); browser.take(res);}
describe("multi-session", () => { it("keeps two users in one browser, and answers no token", async () => { const h = harness(); const auth = createMultiSessionAuth(h); const browser = jar(); await signIn(auth, h, browser, "ada@example.com"); await signIn(auth, h, browser, "bo@example.com"); expect(browser.header()).toContain("__Host-tempo_sessions=");
const res = await call(auth, "GET", "/auth/multi-session", undefined, { cookie: browser.header(), }); const text = await res.text(); const { sessions } = JSON.parse(text) as { sessions: { sessionId: string; active: boolean; user: { email: string } }[]; }; expect(sessions.map((s) => [s.user.email, s.active])).toEqual([ ["bo@example.com", true], ["ada@example.com", false], ]); // The tokens stay in the HttpOnly cookies. for (const value of browser.values()) expect(text).not.toContain(value);
const other = sessions.find((s) => !s.active)?.sessionId; const switched = await call( auth, "POST", "/auth/multi-session/switch", { sessionId: other }, { cookie: browser.header(), }, ); expect(switched.status).toBe(200); });
it("answers 401 to a bearer client: it has no bag", async () => { const h = harness(); const auth = createMultiSessionAuth(h); await call(auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" }); const link = linkIn(h, "ada@example.com").searchParams.get("token") ?? ""; const verified = await call(auth, "POST", "/auth/magic-link/verify", { token: link }); // A native app keeps the token of the answer and sends it as a bearer token. // The Bearer scheme refuses the request, also with the session cookie beside it. const { token } = (await verified.json()) as { token: string }; const res = await call(auth, "GET", "/auth/multi-session", undefined, { authorization: `Bearer ${token}`, cookie: sessionCookieOf(verified), }); expect(res.status).toBe(401); });});How it behaves
Section titled “How it behaves”- The session cookie holds the active token. The bag cookie
__Host-tempo_sessionsholds the others, withHttpOnly,Secure, andPath=/. - A browser sign-in of another user moves the old session into the bag. A sign-in of the same user ends the old session, so each user has one session in the browser.
- A sign-in past
max(5 by default) ends the bag session that the browser used least recently, with the reasondisplaced. It never ends the active session. - No answer holds a token.
GET /multi-sessionanswerssessionId,active, and theid,name,email,username, andimageof each user. - Each route resolves each token of the bag at each read. A revoked, expired, or banned session leaves the bag cookie in the same answer.
- A read of a bag token never slides its expiry. So a list does not keep an idle session alive.
- A switch is no sign-in. It makes no session fresh, and it links no anonymous user.
POST /sign-outends every session of the browser and clears both cookies.POST /multi-session/sign-outends one session.- A request with the Bearer scheme answers 401: a bearer client has no bag. Another scheme, such as HTTP Basic in front of the site, does not refuse a browser.
- An anonymous session never enters the bag. A sign-in over it upgrades the anonymous user, as in Anonymous sessions.
- An impersonation session gets
impersonation_sessionat each route. - The limit
multi-session:ipallows 60 calls per IP per 15 minutes, over the three routes.
Residuals
Section titled “Residuals”- When the active session ends elsewhere, the three routes answer 401. The browser reaches its bag only after a new sign-in.
- Such a stranded bag stays in the browser. An anonymous sign-in needs no credential, and it makes the bag reachable again. On a shared computer, sign out with
POST /sign-out: it clears the bag. - A session that a SCIM deactivate revoked keeps its place in the bag until the next list or switch. Until then, a sign-in can displace a live session in its place.
If it fails
Section titled “If it fails”unauthorized: the browser has no live active session, or the request has the Bearer scheme.not_found: thesessionIdnames no live session of this browser.invalid_body: the body has nosessionId.rate_limited: the IP made 60 calls in 15 minutes.impersonation_session: an operator who impersonates a user cannot use the bag.