Build a Protected Dashboard with Puzzle Auth
A beginner-friendly guide to accounts, passwords, sessions, authenticator-app MFA, recovery codes, and MongoDB persistence with Puzzle Auth and Bun.
What you will build
You will build the account system for a small app called Fieldnotes. By the end, a visitor can:
- Register with an email address and password.
- Set up an authenticator app (Google Authenticator, 1Password, Authy, ...) and save one-time recovery codes.
- Open a dashboard that only signed-in users can see, and save a company name to their profile.
- Sign out, and sign back in with password + authenticator code (or a recovery code if the phone is lost).
Everything — accounts, password hashes, sessions, authenticator secrets, and the profile — is stored in MongoDB through Puzzle's storage adapter.
You do not need to know how authentication works to follow this guide. The next two sections explain every concept the code uses. If you already know the basics, skip to Prerequisites.
Prefer a framework? After this guide, follow the TanStack Start or Next.js version. They reuse the same ideas.
Authentication in plain words
| Term | What it means here |
|---|---|
| Authentication | Proving who someone is (email + password + authenticator code). |
| Authorization | Deciding what that person may do (for example "edit only your own profile"). Puzzle Auth handles authentication; your app still decides authorization. |
| Password hash | Passwords are never stored. A slow, one-way function (Argon2id) turns each password into a hash. At sign-in the typed password is hashed again and compared. |
| Session | After a successful sign-in the server creates a session record in the database and gives the browser a random session token. |
| Cookie | The browser stores the token in an HttpOnly cookie and sends it automatically with every request. HttpOnly means page JavaScript cannot read it, so a malicious script cannot steal it. Secure means it is only sent over HTTPS. |
| MFA (multi-factor authentication) | Requiring a second proof besides the password. Here: a 6-digit code from an authenticator app. |
| TOTP | "Time-based one-time password", the 6-digit code that changes every 30 seconds. Server and app share a secret key (shown once during setup) and both calculate the same code from the current time. |
| Recovery code | A long one-time code the user writes down. It replaces the authenticator code once, for example after losing a phone. |
| Challenge | A short-lived "half signed in" state. After the correct password, the user must still answer the MFA challenge before getting a real session. |
| CSRF | Cross-site request forgery: another website tricking the browser into submitting a form to your site. Puzzle blocks this by checking that the request's Origin header matches your site. |
| Rate limiting | Slowing down repeated failed attempts so attackers cannot guess passwords or codes quickly. |
How a sign-in travels through the app
Browser Your server (Bun) MongoDB
─────── ───────────────── ───────
POST /api/auth/sign-in ──────▶ Puzzle Auth checks password hash ───────▶ auth_users, auth_credentials
◀────── "mfa-pending" + short-lived MFA cookie ─▶ auth_mfa_challenges
POST /api/auth/mfa/... ──────▶ Puzzle Auth checks the 6-digit code ────▶ auth_mfa_factors
◀────── session cookie (HttpOnly, Secure) ──────▶ sessions
GET /dashboard ──────▶ your code: auth.getCurrentUser(token) ──▶ sessions, auth_users
◀────── dashboard HTML, or 401 if not signed inThe browser never sees a password hash, an authenticator secret from the database, or a raw session record. It only holds cookies it cannot read.
Which Puzzle package does what
| Package | Job in this tutorial |
|---|---|
@puzzle-ui/auth | The rules: register, sign in, hash passwords, MFA, recovery codes, rate limits. |
@puzzle-ui/session | Creates, validates, rotates and revokes sessions; reads/writes cookies; CSRF checks. |
@puzzle-ui/storage | A database-neutral interface. Auth and Session only talk to this interface. |
@puzzle-ui/storage-mongodb | The MongoDB implementation of that interface (the storage adapter). |
@puzzle-ui/fullstack | Ready-made HTTP endpoints (/api/auth/...) on the server, and React hooks/forms in the browser. |
@puzzle-ui/theme, @puzzle-ui/ui | Styling and form components for the sign-in screen. |
Because Auth only depends on the storage interface, you could later swap MongoDB for another adapter without changing any authentication code.
API maturity: Auth, Session, Storage, and Fullstack client/server/framework APIs below have Stable classifications and within-major compatibility intent. UI components and the Theme component are also Stable. No Experimental API is required. Review the maturity policy, Auth configuration, and security reference.
Prerequisites
You need four things on your machine. Each item says how to get it.
-
Bun (runtime and package manager), from bun.sh. This tutorial uses Bun's built-in Argon2id password hashing (
Bun.password). On Node.js, use the hasher from the TanStack Start guide instead. -
TypeScript and React 19. Basic React knowledge is enough.
-
A MongoDB replica set. Puzzle Auth writes several documents in one all-or-nothing transaction (for example "create user + create password credential"), and MongoDB only supports transactions on a replica set. A single-node replica set is fine for development. With Docker:
docker run -d --name fieldnotes-mongo -p 27017:27017 mongo:8 --replSet rs0 --bind_ip_all docker exec fieldnotes-mongo mongosh --quiet --eval "rs.initiate({ _id: 'rs0', members: [{ _id: 0, host: 'localhost:27017' }] })"Your connection string is then
mongodb://localhost:27017/?directConnection=true. A free MongoDB Atlas cluster also works (Atlas is always a replica set); use itsmongodb+srv://string. -
Local HTTPS. The session and MFA cookies are always
Secure, so the browser only sends them over HTTPS — even on your laptop. Plain HTTP is not a supported shortcut. mkcert creates a certificate your browser trusts:mkcert -install mkdir -p certs mkcert -key-file certs/localhost-key.pem -cert-file certs/localhost.pem localhost 127.0.0.1
The app will run at https://localhost:3443.
Installation
Create a project folder and install the packages:
mkdir fieldnotes && cd fieldnotes
bun init -y
bun add @puzzle-ui/auth @puzzle-ui/session @puzzle-ui/storage @puzzle-ui/storage-mongodb mongodb @puzzle-ui/fullstack @puzzle-ui/theme @puzzle-ui/ui react react-dom
bun add -d @types/react @types/react-domThere is deliberately no root @puzzle-ui/fullstack import: use its
/auth/client (browser), /auth/server (server), /auth/next, or
/auth/tanstack entry points. In an existing application, reuse its installed
React version.
When you are done, the project looks like this. You will create every file in
auth/ step by step:
fieldnotes/
├── .env # secrets, never committed
├── certs/ # mkcert output, never committed
├── public/ # built browser bundle (generated)
└── auth/
├── database.ts # connect to MongoDB, create the storage adapter
├── services.ts # configure Auth, Session, MFA and HTTP handlers
├── profile.ts # your own app data (company name)
├── application.tsx # server routes: enrollment, dashboard, logout ...
├── client.tsx # browser UI: sign-in / register screen
├── server.tsx # starts the HTTPS server
└── verify.ts # automated end-to-end check (optional)Configuration
1. Create your secrets
Authentication needs a few values that must stay on the server and out of
Git. Create a .env file (Bun loads it automatically) and add .env and
certs/ to .gitignore:
MONGODB_URI="mongodb://localhost:27017/?directConnection=true"
# 32 random bytes as 64 hex characters: encrypts authenticator secrets in MongoDB.
AUTH_ENCRYPTION_KEY_HEX="paste output of: openssl rand -hex 32"
# At least 32 random characters: keys the rate-limit counters.
AUTH_RATE_LIMIT_SECRET="paste output of: openssl rand -base64 48"
TLS_CERT_FILE="certs/localhost.pem"
TLS_KEY_FILE="certs/localhost-key.pem"Generate each secret separately and paste the output:
openssl rand -hex 32
openssl rand -base64 48| Variable | Why it exists | What happens if it changes or leaks |
|---|---|---|
MONGODB_URI | Where accounts and sessions are stored. | Anyone with it can read your database. |
AUTH_ENCRYPTION_KEY_HEX | Authenticator secrets are encrypted before they are saved, so a database dump alone does not reveal them. | If you lose or change it, existing authenticator setups can no longer be read and users must use recovery codes. Never generate it on startup. |
AUTH_RATE_LIMIT_SECRET | Rate-limit records store a keyed hash of the email/IP instead of the raw value. | Changing it resets the counters. |
TLS_* | Your local HTTPS certificate. | Use your host's certificate in production. |
In production, store these in your hosting provider's secret manager instead of a file.
2. Connect MongoDB and create the storage adapter
The storage adapter is the bridge between Puzzle and your database. Auth and
Session never call MongoDB directly; they call the adapter's generic methods
(insert, findById, update, transactions, ...), and
MongoStorageAdapter translates those into MongoDB operations.
import { MongoClient } from "mongodb";
import { MongoStorageAdapter } from "@puzzle-ui/storage-mongodb";
export const connectStorage = async (uri: string, databaseName = "fieldnotes") => {
if (!uri.trim()) throw new Error("A server-only MongoDB URI is required.");
const client = new MongoClient(uri);
try {
await client.connect();
const storage = new MongoStorageAdapter({
database: client.db(databaseName),
client,
// Auth needs all-or-nothing writes. This requires a replica set.
transactionsEnabled: true,
});
return { storage, close: () => client.close() };
} catch (error) {
await client.close();
throw error;
}
};A few rules worth knowing:
- Connect once per server process and share the returned
storage. The MongoDB driver keeps a connection pool; do not connect per request. transactionsEnabled: truedoes not turn a standalone MongoDB server into a replica set. If transactions are unavailable, Auth refuses to start instead of silently writing half an account.- You never create Auth's collections or indexes yourself. When the server
starts, the managers call
registerCollectionon the adapter, which creates the collections and the unique indexes (for example "one account per email") that Auth relies on. - To share a database with another app, pass
collectionPrefix: "fieldnotes_"toMongoStorageAdapter; every collection name below is then prefixed.
What ends up in MongoDB
After you register and sign in once, the fieldnotes database contains:
| Collection | Contents | Sensitive data protection |
|---|---|---|
auth_users | One document per account: email, status, timestamps. | — |
auth_credentials | The password credential for each user. | Only the Argon2id hash is stored. |
auth_mfa_factors | The user's authenticator-app setup. | The TOTP secret is encrypted with AUTH_ENCRYPTION_KEY_HEX. |
auth_recovery_codes | One-time recovery codes. | Stored hashed; each works once. |
auth_mfa_challenges | Pending "password OK, waiting for code" sign-ins and enrollments. | Expire after a few minutes; token stored hashed. |
auth_mfa_step_up_challenges | Re-confirmations before sensitive actions (not used yet). | Short-lived. |
auth_rate_limits | Failed-attempt counters. | Keys are keyed hashes, not raw emails/IPs. |
auth_audit_events, auth_action_tokens | Security events and email/reset tokens for lifecycle flows. | Tokens stored hashed. |
sessions, session_data, session_user_locks | Active sessions and internal session bookkeeping. | The session token itself is stored hashed. |
profiles | Your data: the company name (step 1 below). | Your responsibility. |
Treat every auth_* and session* collection as owned by Puzzle: read them
for debugging if you like, but never insert or edit those documents by hand.
Put your own data in your own collections, like profiles.
3. Configure the auth services
This file creates all server-side objects once and connects them. It accepts the storage adapter as a parameter, so it does not care which database you use. Nothing in it is ever sent to the browser.
import {
StorageAuthManager,
StorageAuthMfaManager,
StorageAuthStepUpManager,
StorageRateLimitProvider,
WebCryptoAuthSecretProtector,
type PasswordHasher,
} from "@puzzle-ui/auth";
import { createAuthServer } from "@puzzle-ui/fullstack/auth/server";
import { createSessionCookieOptions, StorageSessionManager } from "@puzzle-ui/session";
import type { StorageAdapter } from "@puzzle-ui/storage";
export type ServiceOptions = {
storage: StorageAdapter;
origin: string;
rateLimitKeySecret: string;
encryptionKey: Uint8Array;
resolveClientIp: (request: Request) => string;
};
export const createServices = async (options: ServiceOptions) => {
if (new URL(options.origin).protocol !== "https:" ||
new URL(options.origin).origin !== options.origin) {
throw new Error("Configure an exact HTTPS origin without a trailing slash.");
}
const { storage, rateLimitKeySecret, resolveClientIp } = options;
// Turns passwords into slow Argon2id hashes, and checks them at sign-in.
const passwordHasher: PasswordHasher = {
async hash(password) {
return {
hash: await Bun.password.hash(password, {
algorithm: "argon2id", memoryCost: 65536, timeCost: 3,
}),
algorithm: "argon2id",
parameters: { memoryCost: 65536, timeCost: 3 },
};
},
verify: (password, stored) => Bun.password.verify(password, stored.hash, "argon2id"),
};
// Sessions end after 30 minutes of inactivity, or 24 hours at most.
const sessions = new StorageSessionManager(storage, {
lifetime: { idleTimeoutSeconds: 1800, absoluteLifetimeSeconds: 86400 },
});
const rateLimitProvider = new StorageRateLimitProvider(storage);
// Encrypts authenticator secrets before they are written to MongoDB.
const secretProtector = new WebCryptoAuthSecretProtector({
currentKeyId: "primary",
keys: { primary: options.encryptionKey },
});
// MFA: authenticator apps (TOTP) and recovery codes.
const mfa = new StorageAuthMfaManager({
storage, sessions, passwordHasher, rateLimitProvider, secretProtector,
}, { rateLimitKeySecret, issuer: "Fieldnotes" });
// Accounts: register, sign in, sign out, current user.
const auth = new StorageAuthManager({
storage, sessions, passwordHasher, rateLimitProvider, mfa,
}, {
rateLimitKeySecret,
minimumPasswordLength: 12,
mfaPolicy: { required: true },
});
// Re-confirmation before sensitive actions (required by the HTTP handlers).
const stepUp = new StorageAuthStepUpManager({ storage, sessions, mfa });
// __Host-puzzle.session cookie: HttpOnly, Secure, SameSite=Lax.
const cookie = createSessionCookieOptions({ production: true });
// Only POSTs coming from this exact origin are accepted (CSRF protection).
const csrf = { allowedOrigins: [options.origin] };
// The ready-made /api/auth/... HTTP handlers.
const authServer = createAuthServer({
auth, mfa, stepUp, sessions, cookie, csrf, resolveClientIp,
});
// Creates the MongoDB collections and unique indexes listed above.
await sessions.initialize();
await rateLimitProvider.initialize();
await authServer.initialize();
return { auth, mfa, sessions, cookie, csrf, authServer, resolveClientIp, storage };
};
export type Services = Awaited<ReturnType<typeof createServices>>;What each option means for you:
originis the exact address users type in the browser, such ashttps://localhost:3443orhttps://app.example.com. CSRF protection rejects form posts from anywhere else.resolveClientIptells Auth the visitor's IP address for rate limiting. It is a function because the right answer depends on your hosting; see Complete working example.minimumPasswordLength: 12is enforced on the server, whatever the browser form says.mfaPolicy: { required: true }means every user must set up an authenticator before reaching the dashboard. UsemfaPolicy: {}to make MFA optional, orrequiredFor(user)to require it only for some users (for example admins). Users who already set up MFA are always asked for it.- Argon2id cost (
memoryCost,timeCost) makes each hash deliberately slow, so stolen hashes are expensive to crack. Tune it with production measurements; never replace it with a fast hash such as SHA-256.
Step-by-step implementation
1. Store your own data next to the account
Puzzle's user record (AuthUser) intentionally only contains account fields
such as the email address. Anything your app needs — company, role,
preferences — goes into your own collection, keyed by the user's ID.
The important security rule: the user ID always comes from the server-verified session, never from the browser. A browser could send any ID it likes.
import {
StorageValidationError,
type StorageAdapter,
type StorageRecord,
} from "@puzzle-ui/storage";
export type Profile = StorageRecord & { company: string };
export const initializeProfiles = (storage: StorageAdapter) =>
storage.registerCollection<Profile>({ name: "profiles" });
export const saveCompany = async (
storage: StorageAdapter,
authenticatedUserId: string,
company: unknown,
) => {
if (typeof company !== "string" || !company.trim() || company.trim().length > 120) {
throw new StorageValidationError("Enter a company of 1 to 120 characters.");
}
const existing = await storage.findById<Profile>("profiles", authenticatedUserId);
if (existing) {
return storage.update<Profile>("profiles", authenticatedUserId, {
company: company.trim(),
}, { expectedRevision: existing.revision });
}
return storage.insert<Profile>("profiles", {
id: authenticatedUserId, company: company.trim(),
});
};registerCollection creates the profiles collection on startup. Saving uses
the record's revision so two simultaneous saves cannot silently overwrite
each other.
2. Understand which routes you need
Fullstack ships many ready-made endpoints under /api/auth/. This app only
needs six of them, and enables only those (an allowlist). Fewer enabled
endpoints means fewer things that can go wrong:
| Endpoint | Used for |
|---|---|
POST /api/auth/register | Create an account. |
POST /api/auth/sign-in | Check email + password. |
GET /api/auth/state | Ask "am I signed in, or is MFA pending?" |
POST /api/auth/sign-out | End the session. |
POST /api/auth/mfa/sign-in/totp | Answer the MFA challenge with an authenticator code. |
POST /api/auth/mfa/sign-in/recovery-code | Answer it with a recovery code instead. |
Your own pages complete the flow:
| Page | Purpose |
|---|---|
GET /enroll, POST /enroll/start, POST /enroll/verify | Show the authenticator secret once and confirm the first code. |
GET /dashboard | The protected page. |
POST /profile, POST /session/refresh, POST /logout | Dashboard actions. |
GET /account | The sign-in/register screen (React in the browser). |
Why enrollment is server-rendered HTML. During authenticator setup the server must show the user the TOTP secret once. Fullstack's stock enrollment endpoints return that secret as JSON to React state. This tutorial is stricter: the secret only ever appears in a single no-store HTML response with no scripts, so it never sits in browser JavaScript, URLs, logs, or storage. The pending factor stays encrypted in MongoDB. Recovery codes get the same treatment.
Why there is no session yet after registration. With required MFA, a new
account is not "signed in" until the authenticator is set up. Registration
returns the status mfa-enrollment-pending and a short-lived
__Host-puzzle.mfa cookie. That cookie only allows finishing enrollment; it
cannot open the dashboard.
3. Protect every page and action on the server
This is the main server file. Read it top to bottom; the comments below the code explain the important parts.
import type { ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { AuthError, AuthMfaChallengeError } from "@puzzle-ui/auth";
import {
createAuthRouteHandlers,
createSessionResponse,
readMfaChallengeCookie,
serializeClearedMfaChallengeCookie,
} from "@puzzle-ui/fullstack/auth/server";
import {
protectStateChangingRequest,
readSessionCookie,
serializeClearedSessionCookie,
SessionSecurityError,
} from "@puzzle-ui/session";
import {
StorageConflictError, StorageDuplicateError, StorageValidationError,
} from "@puzzle-ui/storage";
import { initializeProfiles, saveCompany, type Profile } from "./profile";
import type { Services } from "./services";
const page = (content: ReactNode) => "<!doctype html>" + renderToStaticMarkup(
<html lang="en"><head><meta charSet="utf-8" /><title>Fieldnotes account</title></head>
<body><main>{content}</main></body></html>,
);
const secureHtml = (response: Response) => {
response.headers.set("Content-Type", "text/html; charset=utf-8");
response.headers.set("Cache-Control", "no-store");
response.headers.set("Pragma", "no-cache");
response.headers.set("Referrer-Policy", "no-referrer");
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("X-Robots-Tag", "noindex, nofollow");
response.headers.set("Content-Security-Policy",
"default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'");
return response;
};
const html = (content: ReactNode, status = 200) =>
secureHtml(new Response(page(content), { status }));
const field = (form: FormData, key: string, maximum = 160) => {
const value = form.get(key);
if (typeof value !== "string" || !value.trim() || value.length > maximum) {
throw new StorageValidationError(`Invalid ${key}.`);
}
return value.trim();
};
export const createApplication = async (services: Services) => {
await initializeProfiles(services.storage);
const routes = createAuthRouteHandlers(services.authServer);
const allowed = new Set([
"/api/auth/register", "/api/auth/sign-in", "/api/auth/state", "/api/auth/sign-out",
"/api/auth/mfa/sign-in/totp", "/api/auth/mfa/sign-in/recovery-code",
]);
const tokenFor = (request: Request) =>
readSessionCookie(request.headers.get("cookie"), services.cookie.name);
const currentUser = async (request: Request) => {
const token = tokenFor(request);
return token ? services.auth.getCurrentUser(token) : null;
};
const enrollmentToken = async (request: Request) => {
const token = readMfaChallengeCookie(request.headers.get("cookie"));
if (!token || tokenFor(request) ||
(await services.auth.getAuthState(token)).status !== "mfa-enrollment-pending") {
throw new AuthMfaChallengeError();
}
return token;
};
const fetch = async (request: Request): Promise<Response> => {
const { pathname } = new URL(request.url);
try {
if (pathname.startsWith("/api/auth/")) {
if (!allowed.has(pathname)) return html(<p>Endpoint not enabled.</p>, 404);
const route = routes[pathname];
const handler = request.method === "GET" ? route?.GET :
request.method === "POST" ? route?.POST : undefined;
if (!handler) return new Response(null, { status: 405 });
return handler(request);
}
if (pathname === "/enroll" && request.method === "GET") {
await enrollmentToken(request);
return html(<>
<h1>Set up your authenticator</h1>
<p>Enrollment is required before dashboard access.</p>
<form method="post" action="/enroll/start">
<button type="submit">Show a new setup key</button>
</form>
</>);
}
if (pathname === "/enroll/start" && request.method === "POST") {
protectStateChangingRequest(request, services.csrf);
const challengeToken = await enrollmentToken(request);
const enrollment = await services.mfa.beginRequiredTotpEnrollment({
challengeToken, ipAddress: services.resolveClientIp(request),
});
return html(<>
<h1>Add Fieldnotes to your authenticator</h1>
<p>Enter this setup key manually. Do not share it.</p>
<code>{enrollment.secret}</code>
<p>Use a time-based code: six digits, changing every 30 seconds.</p>
<form method="post" action="/enroll/verify">
<input type="hidden" name="factorId" value={enrollment.factorId} />
<label htmlFor="totp">Authenticator code</label>
<input id="totp" name="code" inputMode="numeric" autoComplete="one-time-code" required />
<button type="submit">Verify and finish enrollment</button>
</form>
</>);
}
if (pathname === "/enroll/verify" && request.method === "POST") {
protectStateChangingRequest(request, services.csrf);
const challengeToken = await enrollmentToken(request);
const form = await request.formData();
const completed = await services.mfa.verifyRequiredTotpEnrollment({
challengeToken,
factorId: field(form, "factorId"),
code: field(form, "code", 8),
ipAddress: services.resolveClientIp(request),
});
const response = secureHtml(createSessionResponse(page(<>
<h1>Save your recovery codes now</h1>
<p>Each code works once. Store these securely outside this browser.</p>
<ul>{completed.recoveryCodes.map((code) => <li key={code}><code>{code}</code></li>)}</ul>
<a href="/dashboard">I saved my codes; open dashboard</a>
</>), completed.auth.token, services, completed.auth.session.expiresAt));
response.headers.append("Set-Cookie", serializeClearedMfaChallengeCookie());
return response;
}
if (pathname === "/dashboard" && request.method === "GET") {
const user = await currentUser(request);
if (!user) return html(<p>Sign in and complete MFA at <a href="/account">Account</a>.</p>, 401);
const profile = await services.storage.findById<Profile>("profiles", user.id);
return html(<>
<h1>Your Fieldnotes dashboard</h1><p>Signed in as {user.email}</p>
<form action="/profile" method="post">
<label htmlFor="company">Company</label>
<input id="company" name="company" defaultValue={profile?.company ?? ""} maxLength={120} required />
<button type="submit">Save profile</button>
</form>
<form action="/session/refresh" method="post"><button>Refresh session</button></form>
<form action="/logout" method="post"><button>Sign out</button></form>
</>);
}
if (pathname === "/api/me" && request.method === "GET") {
const user = await currentUser(request);
if (!user) return new Response(null, { status: 401, headers: { "Cache-Control": "no-store" } });
return Response.json({ id: user.id, email: user.email }, {
headers: { "Cache-Control": "no-store" },
});
}
if (pathname === "/profile" && request.method === "POST") {
protectStateChangingRequest(request, services.csrf);
const user = await currentUser(request);
if (!user) return html(<p>Authentication required.</p>, 401);
await saveCompany(services.storage, user.id, field(await request.formData(), "company", 120));
return html(<p>Profile saved. <a href="/dashboard">Return to dashboard</a>.</p>);
}
if (pathname === "/session/refresh" && request.method === "POST") {
protectStateChangingRequest(request, services.csrf);
const token = tokenFor(request);
const user = await currentUser(request);
const session = token ? await services.sessions.validate(token, { touch: false }) : null;
if (!user || !session || session.userId !== user.id) return html(<p>Sign in again.</p>, 401);
const rotated = await services.sessions.rotate({ sessionId: session.id });
return secureHtml(createSessionResponse(
page(<p>Session refreshed. <a href="/dashboard">Return to dashboard</a>.</p>),
rotated.token, services, rotated.session.expiresAt,
));
}
if (pathname === "/logout" && request.method === "POST") {
protectStateChangingRequest(request, services.csrf);
const token = tokenFor(request);
if (token) await services.auth.signOut(token);
const response = html(<p>Signed out. <a href="/account">Sign in</a>.</p>);
response.headers.append("Set-Cookie", serializeClearedSessionCookie(services.cookie));
response.headers.append("Set-Cookie", serializeClearedMfaChallengeCookie());
return response;
}
if (["/enroll", "/enroll/start", "/enroll/verify", "/dashboard", "/api/me",
"/profile", "/session/refresh", "/logout"].includes(pathname)) {
return html(<p>Method not allowed.</p>, 405);
}
return html(<p>Not found.</p>, 404);
} catch (error) {
if (error instanceof SessionSecurityError) return html(<p>Request origin rejected.</p>, 403);
if (error instanceof StorageValidationError) return html(<p>{error.message}</p>, 400);
if (error instanceof StorageConflictError || error instanceof StorageDuplicateError) {
return html(<p>The record changed. Reload and retry.</p>, 409);
}
if (error instanceof AuthError) {
if (error.code === "PROVIDER" || error.code === "CONFIGURATION") {
console.error("Fieldnotes authentication service unavailable", { code: error.code });
return html(<p>Authentication temporarily unavailable.</p>, 503);
}
const status = error.code === "RATE_LIMITED" ? 429 :
error.code === "MFA_CHALLENGE" || error.code === "SESSION" ||
error.code === "INVALID_CREDENTIALS" ? 401 : 400;
return html(<p>{error.message} <a href="/account">Return to account</a>.</p>, status);
}
console.error("Fieldnotes request failed", {
errorType: error instanceof Error ? error.name : "UnknownError",
});
return html(<p>Temporarily unavailable. Please retry.</p>, 500);
}
};
return { fetch };
};The key ideas in this file:
currentUser(request)reads the session cookie and callsauth.getCurrentUser(token). It returnsnullunless the session is valid and the account currently satisfies the MFA policy. Every protected page and action calls it — never trust what the browser says about being signed in. (sessions.validatealone only proves the session exists; it does not check MFA policy or the account state.)protectStateChangingRequest(request, services.csrf)is called first in everyPOST. It throws (→ 403) when the request comes from another origin.enrollmentToken(request)only accepts the short-lived MFA cookie while the account is in themfa-enrollment-pendingstate.- The hidden
factorIdfield is not a secret; without the HttpOnly MFA cookie it is useless. Only a correct code creates a normal session. createSessionResponse(...)sets the session cookie. After enrollment the MFA cookie is cleared in the same response.- Session refresh calls
sessions.rotate: the browser gets a brand-new token and the old one stops working. - Errors are mapped to safe messages and status codes. Raw database errors and credentials are never shown or logged.
Keep your normal authorization checks too: being signed in does not mean a user may access every record.
4. Build the sign-in screen in the browser
The browser part is a normal React app. AuthProvider talks to the
/api/auth/... endpoints and exposes the current status through useAuth().
The Account component simply shows the right screen for each status:
snapshot.status | What the user sees |
|---|---|
loading | "Loading account..." |
unauthenticated | Sign-in form, or the registration form. |
mfa-enrollment-pending | A link to /enroll to set up the authenticator. |
mfa-pending | The MFA form: enter an authenticator or recovery code. |
authenticated | A link to the dashboard. |
mfa-enrollment-required | The MFA policy changed for an old session: sign out and in again. |
"use client";
import { useState, type FormEvent } from "react";
import { createRoot } from "react-dom/client";
import { Theme } from "@puzzle-ui/theme";
import { Alert, Button, FormField, TextInput } from "@puzzle-ui/ui";
import {
AuthClientError, AuthProvider, MfaChallengeForm, SignUpForm, useAuth,
} from "@puzzle-ui/fullstack/auth/client";
const PasswordSignIn = () => {
const { signIn } = useAuth();
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
setBusy(true);
setError(null);
try {
await signIn({
email: String(form.get("email") ?? ""),
password: String(form.get("password") ?? ""),
});
} catch (cause) {
setError(cause instanceof AuthClientError && cause.code === "RATE_LIMITED"
? "Too many attempts. Wait before retrying."
: cause instanceof Error ? cause.message : "Sign-in failed.");
} finally {
setBusy(false);
}
};
return <form onSubmit={submit}>
<h1>Sign in to Fieldnotes</h1>
{error && <Alert severity="error">{error}</Alert>}
<FormField label="Email" controlId="email" required>
<TextInput id="email" name="email" type="email" autoComplete="email" required />
</FormField>
<FormField label="Password" controlId="password" required>
<TextInput id="password" name="password" type="password" autoComplete="current-password" required />
</FormField>
<Button type="submit" loading={busy}>Sign in</Button>
</form>;
};
const Account = () => {
const { snapshot, signOut } = useAuth();
const [register, setRegister] = useState(false);
const [error, setError] = useState<string | null>(null);
const logout = async () => {
try { await signOut(); }
catch { setError("Sign-out failed. Please retry."); }
};
if (snapshot.status === "loading") return <p role="status">Loading account...</p>;
if (snapshot.status === "mfa-enrollment-pending") {
return <p><a href="/enroll">Continue to secure authenticator enrollment</a></p>;
}
if (snapshot.status === "mfa-enrollment-required") {
return <><p>Policy changed. Sign out and sign in to start required enrollment.</p>
{error && <Alert severity="error">{error}</Alert>}
<Button onClick={logout}>Sign out</Button></>;
}
if (snapshot.status === "mfa-pending") {
return <MfaChallengeForm redirectTo="/dashboard" />;
}
if (snapshot.status === "authenticated") {
return <p><a href="/dashboard">Open your protected dashboard</a></p>;
}
return <>
{register ? <SignUpForm /> : <PasswordSignIn />}
<Button variant="ghost" onClick={() => setRegister(!register)}>
{register ? "Already registered? Sign in" : "Create an account"}
</Button>
</>;
};
const root = document.getElementById("root");
if (!root) throw new Error("Missing account root.");
createRoot(root).render(
<Theme theme="system">
<AuthProvider options={{ basePath: "/api/auth" }} locale="en"
messages={{ signUp: "Create your Fieldnotes account", invalidCredentials: "Check your email and password." }}>
<Account />
</AuthProvider>
</Theme>,
);The browser form is only for convenience. The server enforces everything that
matters — password length, rate limits, credential checks — so never call
storage from a form or treat snapshot as proof of identity.
SignUpFormandMfaChallengeFormare ready-made Puzzle forms; the password form is custom only so it does not advertise passkeys, which this app has not enabled.AuthProvider.messagesoverrides built-in English texts. Supply translations for your own text too.AuthClientErrorexposesstatusandcode(for exampleRATE_LIMITED) so you can show friendly messages without displaying raw server errors.- For a branded sign-up, see
AuthExperience. Its
custom fields are not saved automatically: save extra data after sign-in
through a server route such as
/profile.
Complete working example
The last file starts an HTTPS server. It connects MongoDB once, creates the
services, serves the browser bundle and the /account page, and sends every
other request to the application from step 3.
import { connectStorage } from "./database";
import { createServices } from "./services";
import { createApplication } from "./application";
const required = (name: string) => {
const value = process.env[name];
if (!value) throw new Error(`Missing server configuration: ${name}`);
return value;
};
if (import.meta.main) {
const connection = await connectStorage(required("MONGODB_URI"));
const keyHex = required("AUTH_ENCRYPTION_KEY_HEX");
if (!/^[a-f0-9]{64}$/i.test(keyHex)) throw new Error("The encryption key must encode exactly 32 bytes.");
const encryptionKey = Uint8Array.from(Buffer.from(keyHex, "hex"));
let server: Bun.Server<undefined>;
const services = await createServices({
storage: connection.storage,
origin: "https://localhost:3443",
encryptionKey,
rateLimitKeySecret: required("AUTH_RATE_LIMIT_SECRET"),
resolveClientIp: (request) => {
const peer = server.requestIP(request);
if (!peer) throw new Error("Trusted peer IP is unavailable.");
return peer.address;
},
});
const app = await createApplication(services);
server = Bun.serve({
hostname: "127.0.0.1",
port: 3443,
maxRequestBodySize: 16384,
tls: { cert: Bun.file(required("TLS_CERT_FILE")), key: Bun.file(required("TLS_KEY_FILE")) },
async fetch(request) {
const path = new URL(request.url).pathname;
if (request.method === "GET" && (path === "/client.js" || path === "/client.css")) {
const file = Bun.file(`public${path}`);
if (!await file.exists()) return new Response("Asset missing; build the client.", { status: 404 });
return new Response(file);
}
if (request.method === "GET" && path === "/account") {
return new Response(`<!doctype html><html lang="en"><head>
<meta charset="utf-8"><title>Fieldnotes account</title>
<link rel="stylesheet" href="/client.css"></head><body>
<div id="root"></div><script type="module" src="/client.js"></script></body></html>`, {
headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store",
"X-Robots-Tag": "noindex, nofollow", "Referrer-Policy": "no-referrer" },
});
}
return app.fetch(request);
},
});
const shutdown = async () => {
await server.stop();
await connection.close();
};
process.once("SIGINT", () => { void shutdown(); });
process.once("SIGTERM", () => { void shutdown(); });
}Build the browser bundle, then start the server:
bun build ./auth/client.tsx --target browser --outdir ./public
bun run auth/server.tsxOpen https://localhost:3443/account. You should see the sign-in screen with a
"Create an account" button.
About resolveClientIp. Locally, the visitor's IP comes straight from the
network connection (server.requestIP). In production behind a load balancer
or CDN, every request would appear to come from the proxy, so replace the
resolver with your platform's trusted client-IP header. Never blindly trust
X-Forwarded-For: browsers can set it to anything.
Before deploying, change origin to your real HTTPS address and let your
host or proxy terminate TLS. Keep CSRF checks and Secure cookies enabled.
For SSR applications, only pass a public AuthClientSnapshot as initialSnapshot
when preloading the client. Never serialize managers, cookies, tokens, raw
AuthResult values or database records, and never cache user-specific
responses. The framework guides show this in practice:
TanStack Start and
Next.js.
Testing and verification
Try it in the browser
- Register with a new email and a password of at least 12 characters.
You are redirected to "Continue to secure authenticator enrollment". Opening
/dashboardnow returns 401: the account is not fully set up. - Set up the authenticator. Follow the link, click "Show a new setup key" and type the key into your authenticator app (choose "enter a setup key").
- Enter the 6-digit code. Only now is a session cookie set. Save the recovery codes somewhere safe outside the browser.
- Open the dashboard and save a company name.
- Refresh session. You stay signed in with a brand-new token.
(
refresh()in the browser client only reloads the status; it does not rotate tokens.) - Sign out, then sign in. The password alone gives
mfa-pending. Enter an authenticator code. On another attempt, use a recovery code; using the same recovery code twice must fail. - Try to break it: a wrong code, an expired challenge, a deleted cookie, a
form post from another origin, or opening
/dashboardwhile signed out. None of these may grant access.
Look inside MongoDB
mongosh "mongodb://localhost:27017/fieldnotes?directConnection=true"show collections
db.auth_users.find({}, { email: 1, status: 1 })
db.auth_credentials.findOne() // contains an argon2id hash, never the password
db.auth_mfa_factors.findOne() // the TOTP secret is encrypted
db.sessions.countDocuments()
db.profiles.find()Run the automated check
The script below drives the whole flow with plain Request/Response objects:
registration, blocked access before enrollment, rejected cross-origin posts,
enrollment, password + TOTP sign-in, recovery codes, session rotation, expiry
and logout. Its in-memory cookie jar plays the role of the browser.
Run it only against a disposable database: it creates a random database name on each run.
TUTORIAL_MONGODB_URI="mongodb://localhost:27017/?directConnection=true" bun run auth/verify.tsimport assert from "node:assert/strict";
import {
AUTH_MFA_CHALLENGE_COLLECTION,
generateTotpCode,
type AuthMfaChallengeStorageRecord,
} from "@puzzle-ui/auth";
import type { AuthClientSnapshot } from "@puzzle-ui/fullstack/auth/shared";
import { SESSION_COLLECTION, type SessionStorageRecord } from "@puzzle-ui/session";
import { connectStorage } from "./database";
import { createServices } from "./services";
import { createApplication } from "./application";
const uri = process.env.TUTORIAL_MONGODB_URI;
if (!uri) throw new Error("Set TUTORIAL_MONGODB_URI to a disposable replica set.");
const connection = await connectStorage(uri, `fieldnotes_auth_${crypto.randomUUID().replaceAll("-", "")}`);
const origin = "https://localhost:3443";
const password = crypto.randomUUID() + crypto.randomUUID();
const email = `${crypto.randomUUID()}@example.com`;
const jar = new Map<string, string>();
try {
const services = await createServices({
storage: connection.storage, origin,
rateLimitKeySecret: crypto.randomUUID() + crypto.randomUUID(),
encryptionKey: crypto.getRandomValues(new Uint8Array(32)),
resolveClientIp: () => "127.0.0.1",
});
const app = await createApplication(services);
const send = async (path: string, method = "GET", body?: string,
contentType = "application/json", requestOrigin = origin) => {
const response = await app.fetch(new Request(origin + path, {
method,
headers: {
cookie: [...jar].map(([key, value]) => `${key}=${value}`).join("; "),
origin: requestOrigin, "Content-Type": contentType,
},
...(body === undefined ? {} : { body }),
}));
for (const cookie of response.headers.getSetCookie()) {
assert.match(cookie, /HttpOnly/i);
assert.match(cookie, /Secure/i);
const pair = cookie.split(";")[0]!;
const separator = pair.indexOf("=");
const name = pair.slice(0, separator);
if (/Max-Age=0(?:;|$)/i.test(cookie)) jar.delete(name);
else jar.set(name, pair.slice(separator + 1));
}
return response;
};
const post = (path: string, fields: Record<string, string>) =>
send(path, "POST", new URLSearchParams(fields).toString(),
"application/x-www-form-urlencoded");
const signIn = () => send("/api/auth/sign-in", "POST", JSON.stringify({ email, password }));
const registration = await send("/api/auth/register", "POST", JSON.stringify({ email, password }));
assert.equal(registration.status, 200);
const registrationText = await registration.text();
assert.equal(JSON.parse(registrationText).status, "mfa-enrollment-pending");
assert.ok(!registrationText.includes("challengeToken") && !registrationText.includes('"secret"'));
assert.ok(jar.has("__Host-puzzle.mfa"));
assert.ok(!registrationText.includes(jar.get("__Host-puzzle.mfa")!));
assert.ok(!jar.has(services.cookie.name!));
assert.equal((await send("/dashboard")).status, 401);
assert.equal((await send("/api/me")).status, 401);
assert.equal((await send("/enroll/start")).status, 405);
assert.equal((await send("/enroll/start", "POST", "", "text/plain", "https://attacker.example")).status, 403);
for (const endpoint of [
"/api/auth/mfa/enrollment/required/totp/start",
"/api/auth/mfa/enrollment/required/totp/finish",
"/api/auth/mfa/totp/enrollment/start",
"/api/auth/mfa/totp/enrollment/finish",
"/api/auth/mfa/recovery-codes/regenerate",
]) {
assert.equal((await send(endpoint, "POST", "{}")).status, 404);
}
assert.equal((await post("/enroll/verify", { factorId: "missing", code: "000000" })).status, 401);
const started = await post("/enroll/start", {});
assert.equal(started.status, 200);
assert.equal(started.headers.get("Cache-Control"), "no-store");
assert.match(started.headers.get("Content-Type")!, /text\/html/);
assert.match(started.headers.get("Content-Security-Policy")!, /default-src 'none'/);
const markup = await started.text();
assert.ok(!markup.includes("<script") && !markup.includes(jar.get("__Host-puzzle.mfa")!));
const secret = markup.match(/<code>([A-Z2-7]+)<\/code>/)?.[1];
const factorId = markup.match(/name="factorId" value="([^"]+)"/)?.[1];
assert.ok(secret && factorId);
const code = await generateTotpCode(secret, Date.now(), { digits: 6, periodSeconds: 30 });
const enrolled = await post("/enroll/verify", { factorId, code });
assert.equal(enrolled.status, 200);
const recoveryHtml = await enrolled.text();
const recoveryCode = [...recoveryHtml.matchAll(/<li><code>([^<]+)<\/code><\/li>/g)][0]?.[1];
assert.ok(recoveryCode);
assert.ok(!jar.has("__Host-puzzle.mfa"));
assert.ok(jar.has(services.cookie.name!));
assert.equal((await send("/dashboard")).status, 200);
assert.equal((await post("/profile", { company: "Fieldnotes Studio" })).status, 200);
assert.ok((await (await send("/dashboard")).text()).includes("Fieldnotes Studio"));
const oldToken = jar.get(services.cookie.name!)!;
assert.equal((await post("/session/refresh", {})).status, 200);
assert.equal(await services.auth.getCurrentUser(oldToken), null);
assert.notEqual(jar.get(services.cookie.name!), oldToken);
assert.equal((await post("/logout", {})).status, 200);
assert.equal((await send("/dashboard")).status, 401);
const login = await signIn();
assert.equal(login.status, 200);
const pending: AuthClientSnapshot = await (await send("/api/auth/state")).json();
assert.equal(pending.status, "mfa-pending");
assert.equal((await send("/dashboard")).status, 401);
const nextCode = await generateTotpCode(secret, Date.now() + 30000, { digits: 6, periodSeconds: 30 });
const verified = await send("/api/auth/mfa/sign-in/totp", "POST", JSON.stringify({ code: nextCode }));
assert.equal(verified.status, 200);
assert.equal((await send("/api/me")).status, 200);
const activeToken = jar.get(services.cookie.name!)!;
const activeSession = await services.sessions.validate(activeToken, { touch: false });
assert.ok(activeSession);
await services.storage.update<SessionStorageRecord>(SESSION_COLLECTION, activeSession.id, {
expiresAt: new Date(0),
});
assert.equal((await send("/dashboard")).status, 401);
await post("/logout", {});
await signIn();
assert.equal((await send("/api/auth/mfa/sign-in/recovery-code", "POST",
JSON.stringify({ code: recoveryCode }))).status, 200);
await post("/logout", {});
assert.equal((await signIn()).status, 200);
const repeatLogin: AuthClientSnapshot = await (await send("/api/auth/state")).json();
assert.equal((await send("/api/auth/mfa/sign-in/recovery-code", "POST",
JSON.stringify({ code: recoveryCode }))).status, 401);
assert.ok(repeatLogin.mfa);
await services.storage.update<AuthMfaChallengeStorageRecord>(
AUTH_MFA_CHALLENGE_COLLECTION, repeatLogin.mfa.challengeId, { expiresAt: new Date(0) },
);
assert.equal((await send("/api/auth/mfa/sign-in/totp", "POST",
JSON.stringify({ code: nextCode }))).status, 401);
assert.equal((await send("/dashboard")).status, 401);
console.log("Auth enrollment, cookie boundaries, policy enforcement, MFA, expiration, rotation, and logout verified.");
} finally {
await connection.close();
}It is a server-side test, not a real-browser or authenticator-app test.
How sessions behave over time
- Sessions are only created by successful Auth flows, never by a browser call.
- Each validated request updates the session's "last active" time, so an active user stays signed in up to the 24-hour absolute limit. Updating activity does not renew the browser cookie.
- The
/session/refreshroute rotates: it sets a new cookie and revokes the old session. Each rotated session gets a fresh absolute lifetime, so rotation is not a re-authentication. Add your own maximum login age if you need one. - An expired session requires a new sign-in.
- To sign a user out remotely, call
sessions.revoke(id).auth.signOutEverywhere(user.id)ends all of a user's sessions and pending MFA challenges; only call it with a server-verified user ID.
Passkeys, optional enrollment, and lost devices
- Optional MFA for already signed-in users uses
beginTotpEnrollment/verifyTotpEnrollment(with password confirmation). Reuse the server-HTML display approach from step 3; do not enable the stock secret-returning routes by accident. A user whose policy changed while signed in must sign out and in to get the enrollment challenge. - Passkeys (WebAuthn) are supported. Add
SimpleWebAuthnProviderto the MFA dependencies and configurewebAuthn: { rpId, rpName, origin }with your exact origin. The browser helpers from/auth/clientrun the ceremony while the server verifies it. Public WebAuthn options are not the server's challenge token: that token always stays in its HttpOnly cookie. See the MFA reference. - Lost everything? Recovery codes are single-use and stored hashed; regenerating them invalidates the old ones and requires the current password. There is no automatic bypass when every factor and code is lost. Design an explicit, verified support process; never turn off MFA because of an email.
Common mistakes and troubleshooting
Transaction numbers are only allowed on a replica set member or mongosor an error about disabled transactions: MongoDB runs as a standalone server. Start it with--replSetand runrs.initiate()(see Prerequisites).Missing server configuration: ...: a variable from.envis missing. Run the command from the project folder so Bun finds.env.- The browser warns about the certificate: run
mkcert -installonce and restart the browser. - Signed in, but the dashboard says 401: the account is still
mfa-pendingormfa-enrollment-pending. Only a fully authenticated session opens the dashboard; this is intended. - MFA cookie missing: you are using HTTP, or a proxy drops
Set-Cookieheaders. Do not disableSecureor move challenge tokens into JSON orlocalStorage. - Authenticator codes stopped working after a restart: the
AUTH_ENCRYPTION_KEY_HEXchanged. Restore the original key. When rotating keys, keep old keys inkeysunder their old ID. - TOTP rejected: check the phone's clock, use the default 6-digit / 30-second settings, and wait for a new code — a code cannot be used twice.
- 403 on a form post: the
Origin(scheme, host and port) does not exactly matchorigin. Fix the configuration; do not setallowMissingOriginto silence it. - The company field is not saved at registration: registration only accepts
email and password. Save extra fields through an authenticated server route
like
/profile. - Passkey or password-reset buttons appear: this app only enables password, TOTP and recovery codes. Do not show UI for endpoints you have not configured.
Next steps
- Use the same setup in a framework: TanStack Start or Next.js.
- Add account lifecycle delivery with a real email provider before requiring verified email; keep that policy aligned across managers.
- Require recent server-enforced step-up for destructive actions; it rotates the session and is not only a UI prompt.
- Learn more about adapters and apply resource-level authorization in the Storage tutorial.
- Keep private routes noindex and out of the public SEO publication sitemap.
Practical Puzzle Tutorials
Set up a theme with local fonts, build a searchable publication, persist a notebook, and protect an MFA-enabled application using Puzzle APIs.
Add Puzzle Auth to Next.js
Step-by-step guide to registration, sessions, authenticator-app MFA, recovery codes, and MongoDB storage with Puzzle Auth in a Next.js App Router app.