Skip to content

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.

  1. Set multiSession to {}, or to { max } from 2 to 10.
  2. Offer “Add an account”: it runs a normal sign-in in the same browser.
  3. Call GET /multi-session with the cookies, and show each user.
  4. On a click, post { sessionId } to POST /multi-session/switch.
  5. Offer “Sign out of this account”: it posts { sessionId } to POST /multi-session/sign-out.
  6. Offer “Sign out of all accounts”: it posts to POST /sign-out.
  7. In a browser app, call client.multiSession.list, client.multiSession.switch, and client.multiSession.signOut of the client package in place of the calls.
Multi-session in the config
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,
},
});
}
Two users in one browser as a test
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);
});
});
  • The session cookie holds the active token. The bag cookie __Host-tempo_sessions holds the others, with HttpOnly, Secure, and Path=/.
  • 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 reason displaced. It never ends the active session.
  • No answer holds a token. GET /multi-session answers sessionId, active, and the id, name, email, username, and image of 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-out ends every session of the browser and clears both cookies. POST /multi-session/sign-out ends 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_session at each route.
  • The limit multi-session:ip allows 60 calls per IP per 15 minutes, over the three routes.
  • 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.