Leaf and Kettle keeps its sessions in the browser. The session cookie holds who's signed in and a signature proving the shop wrote it: two parts joined by a dot, <payload>.<signature>. The payload is the JSON of { userId, role, expiresAt } in base64url, where role is customer or staff and expiresAt is a time in milliseconds, as Date.now() gives. The signature is the HMAC-SHA256 of the payload part, as 64 lowercase hex digits, made with SESSION_SECRET from @/lib/env. Sign-in makes the cookie with signSession(payload) from @/lib/session. Write the other half in app/lib/dal.ts, the data access layer that pages, Server Actions, and Route Handlers ask.
getSession() returns { userId, role }, and nothing else, for a good cookie. Everything else gets null: no cookie or an empty one; a value that isn't exactly two parts; a signature that isn't the one hmacSha256Hex(SESSION_SECRET, payload) from @/lib/signing gives (compare them with its safeEqual); a payload that isn't base64url of a JSON object (fromBase64Url from @/lib/session throws for text that isn't base64url, and JSON.parse for text that isn't JSON); a userId that isn't a non-empty string; a role that isn't one of the two; and an expiresAt that isn't a number later than Date.now().
Check the signature before you decode anything: until it matches, the payload is text anyone could have written. And never throw: a broken cookie is a guest, not a server error on every page they open.
verifySession() returns the same { userId, role }, or redirects to /sign-in when there's no good session. Pages that need someone signed in call it, like app/account/page.tsx; the header's menu, which shows guests a Sign in link, calls getSession(). Both are wrapped in React's cache already, so however many components ask during one request, the cookie is checked once.
session=eyJ1c2VySWQiOiJ1X2FuYSIsInJvbGUiOiJjdXN0b21lciIsImV4cGlyZXNBdCI6MTc5NTAwMDAwMDAwMH0.8483bfeb…e3e22a
(the payload is {"userId":"u_ana","role":"customer","expiresAt":1795000000000})
getSession() → { userId: "u_ana", role: "customer" }
the payload changed to say "staff", the signature kept
getSession() → null
verifySession() → redirect("/sign-in")
lib/signing.ts, read-only. Import it as @/lib/signing.
// HMAC-SHA256 in plain TypeScript, so it runs everywhere the tests do. It gives the same answer as
// Web Crypto's crypto.subtle.sign("HMAC", ...) and Node.js's createHmac("sha256", ...), which a
// real app would use.
const encoder = new TextEncoder();
// SHA-256's constants: the first 32 bits of the fractional parts of the cube roots (K) and the
// square roots (H) of the first 64 and 8 primes.
const primes: number[] = [];
for (let n = 2; primes.length < 64; n++) if (primes.every((p) => n % p !== 0)) primes.push(n);
const fraction = (x: number) => ((x - Math.floor(x)) * 2 ** 32) >>> 0;
const K = primes.map((p) => fraction(Math.cbrt(p)));
const H = primes.slice(0, 8).map((p) => fraction(Math.sqrt(p)));
function sha256(data: Uint8Array): Uint8Array {
const blocks = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
blocks.set(data);
blocks[data.length] = 0x80;
const view = new DataView(blocks.buffer);
view.setUint32(blocks.length - 8, Math.floor(data.length / 2 ** 29));
view.setUint32(blocks.length - 4, (data.length * 8) >>> 0);
const hash = H.slice();
const w = new Uint32Array(64);
const rotate = (x: number, n: number) => (x >>> n) | (x << (32 - n));
for (let offset = 0; offset < blocks.length; offset += 64) {
for (let i = 0; i < 64; i++) {
w[i] = i < 16 ? view.getUint32(offset + i * 4) : w[i - 16] + (rotate(w[i - 15], 7) ^ rotate(w[i - 15], 18) ^ (w[i - 15] >>> 3)) + w[i - 7] + (rotate(w[i - 2], 17) ^ rotate(w[i - 2], 19) ^ (w[i - 2] >>> 10));
}
let [a, b, c, d, e, f, g, h] = hash;
for (let i = 0; i < 64; i++) {
const t1 = (h + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
const t2 = ((rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
[h, g, f, e, d, c, b, a] = [g, f, e, (d + t1) | 0, c, b, a, (t1 + t2) | 0];
}
[a, b, c, d, e, f, g, h].forEach((value, i) => (hash[i] = (hash[i] + value) | 0));
}
const digest = new Uint8Array(32);
hash.forEach((value, i) => new DataView(digest.buffer).setUint32(i * 4, value >>> 0));
return digest;
}
/** The HMAC-SHA256 of `message` with `secret`, as 64 lowercase hex digits. Async, like Web Crypto's. */
export async function hmacSha256Hex(secret: string, message: string): Promise<string> {
let key: Uint8Array = encoder.encode(secret);
if (key.length > 64) key = sha256(key);
const pad = (byte: number) => Uint8Array.from({ length: 64 }, (_, i) => (key[i] ?? 0) ^ byte);
const join = (first: Uint8Array, second: Uint8Array) => {
const both = new Uint8Array(first.length + second.length);
both.set(first);
both.set(second, first.length);
return both;
};
const mac = sha256(join(pad(0x5c), sha256(join(pad(0x36), encoder.encode(message)))));
return Array.from(mac, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
/** Whether `a` and `b` are the same text, in the same time wherever they differ. */
export function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let difference = 0;
for (let i = 0; i < a.length; i++) difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
return difference === 0;
}
lib/env.ts, read-only. Import it as @/lib/env.
import "server-only";
/**
* The secret that signs session cookies. A real app reads it from process.env.SESSION_SECRET, set on
* the server only: a NEXT_PUBLIC_ name would put it into the browser's JavaScript at build time.
*/
export const SESSION_SECRET = "leaf-and-kettle-session-7c2e9a41f0b3";
lib/session.ts, read-only. Import it as @/lib/session.
import { SESSION_SECRET } from "@/lib/env";
import { hmacSha256Hex } from "@/lib/signing";
export type SessionPayload = { userId: string; role: "customer" | "staff"; expiresAt: number };
/** Text as base64url: its UTF-8 bytes in base64, with - and _ for + and /, and no = at the end. */
export function toBase64Url(text: string): string {
let binary = "";
for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
/** The text a base64url string holds. Throws for anything that isn't base64url. */
export function fromBase64Url(encoded: string): string {
if (!/^[A-Za-z0-9_-]*$/.test(encoded)) throw new Error("Not base64url: " + encoded);
const base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
}
/** The session cookie's value, as sign-in sets it: <payload>.<signature>. */
export async function signSession(payload: SessionPayload): Promise<string> {
const encoded = toBase64Url(JSON.stringify(payload));
return encoded + "." + (await hmacSha256Hex(SESSION_SECRET, encoded));
}
app/account/page.tsx, read-only. Import it as @/app/account/page.
import { verifySession } from "@/app/lib/dal";
export default async function AccountPage() {
const session = await verifySession();
return (
<main>
<h1>Your account</h1>
<p>Signed in as {session.userId}</p>
{session.role === "staff" && <a href="/admin">Staff tools</a>}
</main>
);
}
app/components/account-menu.tsx, read-only. Import it as @/app/components/account-menu.
import { getSession } from "@/app/lib/dal";
export default async function AccountMenu() {
const session = await getSession();
return <nav>{session ? <a href="/account">Your account</a> : <a href="/sign-in">Sign in</a>}</nav>;
}
const HOUR = 60 * 60 * 1000;
const as = (cookie, work) => withRequest({ cookies: cookie === null ? {} : { session: cookie } }, work);
/** A cookie value for this payload (an object, or text as it is), signed with this secret. */
const forge = async (payload, secret = SESSION_SECRET) => {
const encoded = toBase64Url(typeof payload === "string" ? payload : JSON.stringify(payload));
return encoded + "." + (await hmacSha256Hex(secret, encoded));
};
useFakeTimers();
const ana = await signSession({ userId: "u_ana", role: "customer", expiresAt: Date.now() + HOUR });
expect(await as(ana, () => getSession())).toEqual({ userId: "u_ana", role: "customer" });
expect(await as(ana, () => verifySession())).toEqual({ userId: "u_ana", role: "customer" });
const sam = await signSession({ userId: "u_sam", role: "staff", expiresAt: Date.now() + HOUR });
expect(await as(sam, () => getSession())).toEqual({ userId: "u_sam", role: "staff" });
const HOUR = 60 * 60 * 1000;
const as = (cookie, work) => withRequest({ cookies: cookie === null ? {} : { session: cookie } }, work);
/** A cookie value for this payload (an object, or text as it is), signed with this secret. */
const forge = async (payload, secret = SESSION_SECRET) => {
const encoded = toBase64Url(typeof payload === "string" ? payload : JSON.stringify(payload));
return encoded + "." + (await hmacSha256Hex(secret, encoded));
};
expect(await as(null, () => getSession())).toBeNull();
expect(await as("", () => getSession())).toBeNull();
expect((await redirectOf(() => as(null, () => verifySession()))).url).toBe("/sign-in");
const HOUR = 60 * 60 * 1000;
const as = (cookie, work) => withRequest({ cookies: cookie === null ? {} : { session: cookie } }, work);
/** A cookie value for this payload (an object, or text as it is), signed with this secret. */
const forge = async (payload, secret = SESSION_SECRET) => {
const encoded = toBase64Url(typeof payload === "string" ? payload : JSON.stringify(payload));
return encoded + "." + (await hmacSha256Hex(secret, encoded));
};
useFakeTimers();
const later = Date.now() + HOUR;
const [payload, signature] = (await signSession({ userId: "u_ana", role: "customer", expiresAt: later })).split(".");
const promoted = toBase64Url(JSON.stringify({ userId: "u_ana", role: "staff", expiresAt: later }));
const flipped = signature.slice(0, -1) + (signature.endsWith("0") ? "1" : "0");
const guessedSecret = await forge({ userId: "u_ana", role: "staff", expiresAt: later }, "leaf-and-kettle");
for (const cookie of [promoted + "." + signature, payload + "." + flipped, payload + "." + signature.toUpperCase(), payload + ".", payload, guessedSecret]) {
expect(await as(cookie, () => getSession())).toBeNull();
expect((await redirectOf(() => as(cookie, () => verifySession()))).url).toBe("/sign-in");
}
const HOUR = 60 * 60 * 1000;
const as = (cookie, work) => withRequest({ cookies: cookie === null ? {} : { session: cookie } }, work);
/** A cookie value for this payload (an object, or text as it is), signed with this secret. */
const forge = async (payload, secret = SESSION_SECRET) => {
const encoded = toBase64Url(typeof payload === "string" ? payload : JSON.stringify(payload));
return encoded + "." + (await hmacSha256Hex(secret, encoded));
};
const clock = useFakeTimers();
const cookie = await signSession({ userId: "u_ben", role: "customer", expiresAt: Date.now() + HOUR });
await clock.advance(HOUR - 1);
expect(await as(cookie, () => getSession())).toEqual({ userId: "u_ben", role: "customer" });
await clock.advance(1);
expect(await as(cookie, () => getSession())).toBeNull();
expect((await redirectOf(() => as(cookie, () => verifySession()))).url).toBe("/sign-in");
const HOUR = 60 * 60 * 1000;
const as = (cookie, work) => withRequest({ cookies: cookie === null ? {} : { session: cookie } }, work);
/** A cookie value for this payload (an object, or text as it is), signed with this secret. */
const forge = async (payload, secret = SESSION_SECRET) => {
const encoded = toBase64Url(typeof payload === "string" ? payload : JSON.stringify(payload));
return encoded + "." + (await hmacSha256Hex(secret, encoded));
};
useFakeTimers();
const later = Date.now() + HOUR;
const junk = "%%%";
const broken = [
"x",
".",
"a.b.c",
"!!!.abc",
junk + "." + (await hmacSha256Hex(SESSION_SECRET, junk)),
await forge("not json"),
await forge("null"),
await forge("[]"),
await forge("42"),
await forge('"u_ana"'),
await forge({ role: "customer", expiresAt: later }),
await forge({ userId: "", role: "customer", expiresAt: later }),
await forge({ userId: 7, role: "customer", expiresAt: later }),
await forge({ userId: "u_ana", role: "admin", expiresAt: later }),
await forge({ userId: "u_ana", role: "customer" }),
await forge({ userId: "u_ana", role: "customer", expiresAt: String(later) }),
(await forge({ userId: "u_ana", role: "customer", expiresAt: later })) + ".extra",
];
for (const cookie of broken) {
expect(await as(cookie, () => getSession())).toBeNull();
}
const HOUR = 60 * 60 * 1000;
const as = (cookie, work) => withRequest({ cookies: cookie === null ? {} : { session: cookie } }, work);
/** A cookie value for this payload (an object, or text as it is), signed with this secret. */
const forge = async (payload, secret = SESSION_SECRET) => {
const encoded = toBase64Url(typeof payload === "string" ? payload : JSON.stringify(payload));
return encoded + "." + (await hmacSha256Hex(secret, encoded));
};
useFakeTimers();
const sam = await signSession({ userId: "u_sam", role: "staff", expiresAt: Date.now() + HOUR });
await as(sam, () =>
renderServer(
<>
<AccountMenu />
<Page />
</>,
),
);
expect(screen.getByRole("link", { name: "Your account" })).toBeInTheDocument();
expect(screen.getByText("Signed in as u_sam")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Staff tools" })).toBeInTheDocument();
cleanup();
await as(null, () => renderServer(<AccountMenu />));
expect(screen.getByRole("link", { name: "Sign in" })).toBeInTheDocument();
expect((await redirectOf(() => as(null, () => renderServer(<Page />)))).url).toBe("/sign-in");
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Verify a signed session in the data access layer. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.