Leaf and Kettle's account page changes a customer's email by posting JSON to POST /api/account/email, and the session cookie says who's signed in. Write the handler in app/api/account/email/route.ts so that only the shop's own pages can use it.
A Server Action gets this protection from Next.js, which compares the request's Origin header with the host the request was sent to and refuses a mismatch. A Route Handler gets no such check. The session cookie is sameSite: "lax", which keeps it off posts that other sites start, but the shop's blog at blog.leafandkettle.com runs on a third-party platform, and to the browser that counts as the same site. A script there could post here with the customer's cookie, change the email, and take the account over with a password reset.
The host the request was sent to is the first value of X-Forwarded-Host, which the shop's load balancer sets and which can hold a list like leafandkettle.com, edge.internal, or, without that header, Host. Don't use request.nextUrl for it: behind the load balancer, next start builds the request's URL from its own address.
When the request has an Origin header, its host (new URL(origin).host, which keeps any port) must be that host or one of TRUSTED_HOSTS from @/lib/config. Anything else, Origin: null and a value that isn't a URL included, gets status 403 with { error: "Cross-site request refused" }. A request without an Origin header goes on: browsers send one with every POST, so it comes from a program, which can't borrow a customer's cookie. Next.js lets those through for Server Actions too.
Check the origin first. Then the session, with getViewer() from @/lib/session: without one, answer 401 with { error: "Sign in to change your email" }. Then the body: a JSON object whose email, trimmed and lowercased, is some text, an @, more text, a dot, and more text, with no spaces; otherwise answer 400 with { error: "Enter a valid email" }. Save it with setEmail(viewer.id, email) from @/lib/users and answer 200 with { email }.
POST /api/account/email Host: leafandkettle.com Origin: https://leafandkettle.com
Cookie: session=token-ana { "email": "Ana.Lima@Example.com" }
→ 200 { email: "ana.lima@example.com" }
POST /api/account/email Host: leafandkettle.com Origin: https://blog.leafandkettle.com
→ 403 { error: "Cross-site request refused" }
lib/session.ts, read-only. Import it as @/lib/session.
import { cookies } from "next/headers";
export type Viewer = { id: string; role: "customer" | "staff" };
/** Live sessions: the token in the `session` cookie, and whose it is. */
const sessions = new Map<string, Viewer>([
["token-ana", { id: "u_ana", role: "customer" }],
["token-ben", { id: "u_ben", role: "customer" }],
["token-sam", { id: "u_sam", role: "staff" }],
]);
/** Who sent this request, from the `session` cookie, or null for a guest. */
export async function getViewer(): Promise<Viewer | null> {
const token = (await cookies()).get("session")?.value;
const viewer = token ? sessions.get(token) : undefined;
return viewer ? { ...viewer } : null;
}
lib/users.ts, read-only. Import it as @/lib/users.
/** Each account's email, by user id: a stand-in for the shop's database. */
export const emails: Record<string, string> = {
u_ana: "ana@example.com",
u_ben: "ben@example.com",
u_sam: "sam@leafandkettle.example",
};
export async function setEmail(userId: string, email: string) {
emails[userId] = email;
}
lib/config.ts, read-only. Import it as @/lib/config.
/**
* Hosts other than the shop's own whose pages may post to its API, written like Next.js's
* serverActions.allowedOrigins: the help centre embeds the account settings form.
*/
export const TRUSTED_HOSTS = ["help.leafandkettle.com"];
const post = (headers, body = JSON.stringify({ email: "ana.lima@example.com" })) =>
POST(request("/api/account/email", { method: "POST", headers: { "content-type": "application/json", cookie: "session=token-ana", ...headers }, body }));
const refused = async (response) => {
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ error: "Cross-site request refused" });
};
const response = await post({ host: "leafandkettle.com", origin: "https://leafandkettle.com" }, JSON.stringify({ email: " Ana.Lima@Example.com " }));
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ email: "ana.lima@example.com" });
expect(emails.u_ana).toBe("ana.lima@example.com");
const post = (headers, body = JSON.stringify({ email: "ana.lima@example.com" })) =>
POST(request("/api/account/email", { method: "POST", headers: { "content-type": "application/json", cookie: "session=token-ana", ...headers }, body }));
const refused = async (response) => {
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ error: "Cross-site request refused" });
};
for (const type of ["application/json", "text/plain"]) {
await refused(await post({ host: "leafandkettle.com", origin: "https://evil.example", "content-type": type }));
}
expect(emails.u_ana).toBe("ana@example.com");
const post = (headers, body = JSON.stringify({ email: "ana.lima@example.com" })) =>
POST(request("/api/account/email", { method: "POST", headers: { "content-type": "application/json", cookie: "session=token-ana", ...headers }, body }));
const refused = async (response) => {
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ error: "Cross-site request refused" });
};
for (const origin of ["null", "https://blog.leafandkettle.com", "https://leafandkettle.com.evil.example", "https://evil-leafandkettle.com", "https://leafandkettle.com:8443", "not a url", ""]) {
await refused(await post({ host: "leafandkettle.com", origin }));
}
expect(emails.u_ana).toBe("ana@example.com");
const post = (headers, body = JSON.stringify({ email: "ana.lima@example.com" })) =>
POST(request("/api/account/email", { method: "POST", headers: { "content-type": "application/json", cookie: "session=token-ana", ...headers }, body }));
const refused = async (response) => {
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ error: "Cross-site request refused" });
};
const internal = { host: "10.0.3.7:3000", "x-forwarded-host": "leafandkettle.com" };
expect((await post({ ...internal, origin: "https://leafandkettle.com" })).status).toBe(200);
await refused(await post({ ...internal, origin: "http://10.0.3.7:3000" }));
const chained = { host: "10.0.3.7:3000", "x-forwarded-host": "leafandkettle.com, edge.internal" };
expect((await post({ ...chained, origin: "https://leafandkettle.com" })).status).toBe(200);
await refused(await post({ ...chained, origin: "https://edge.internal" }));
const post = (headers, body = JSON.stringify({ email: "ana.lima@example.com" })) =>
POST(request("/api/account/email", { method: "POST", headers: { "content-type": "application/json", cookie: "session=token-ana", ...headers }, body }));
const refused = async (response) => {
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ error: "Cross-site request refused" });
};
expect((await post({ host: "leafandkettle.com", origin: "https://help.leafandkettle.com" })).status).toBe(200);
const fromAProgram = await post({ host: "leafandkettle.com" }, JSON.stringify({ email: "ana@leaf.example" }));
expect(fromAProgram.status).toBe(200);
expect(emails.u_ana).toBe("ana@leaf.example");
const post = (headers, body = JSON.stringify({ email: "ana.lima@example.com" })) =>
POST(request("/api/account/email", { method: "POST", headers: { "content-type": "application/json", cookie: "session=token-ana", ...headers }, body }));
const refused = async (response) => {
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ error: "Cross-site request refused" });
};
await refused(await post({ host: "leafandkettle.com", origin: "https://evil.example", cookie: "" }, "not json"));
const guest = await post({ host: "leafandkettle.com", origin: "https://leafandkettle.com", cookie: "" });
expect(guest.status).toBe(401);
expect(await guest.json()).toEqual({ error: "Sign in to change your email" });
for (const body of ["not json", JSON.stringify({ email: "ana" }), JSON.stringify({ email: "ana @example.com" }), JSON.stringify({ email: 42 }), JSON.stringify(["ana@example.com"])]) {
const response = await post({ host: "leafandkettle.com", origin: "https://leafandkettle.com" }, body);
expect(response.status).toBe(400);
expect(await response.json()).toEqual({ error: "Enter a valid email" });
}
expect(emails.u_ana).toBe("ana@example.com");
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 An email change API that refuses other sites. 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.