completefrontend

Write the codeHard

Write the callback Route Handler for "Sign in with Teapot ID", with its state and PKCE checks

Leaf and Kettle lets customers sign in with Teapot ID, an OAuth provider. The Sign in button links to /auth/start, a Route Handler that's already written: it keeps a random state and a PKCE verifier in two cookies and sends the browser to Teapot ID. Once the customer has signed in there, Teapot ID sends the browser back to /auth/callback?code=…&state=….

app/auth/start/route.ts
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
 
const base64url = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64url");
 
export async function GET() {
  const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
  const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
  const challenge = base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
 
  const cookieStore = await cookies();
  const options = { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 600 } as const;
  cookieStore.set("oauth_state", state, options);
  cookieStore.set("oauth_verifier", verifier, options);
 
  const authorize = new URL("https://id.teapot.example/authorize");
  authorize.search = new URLSearchParams({
    client_id: "leaf-and-kettle",
    redirect_uri: "https://leafandkettle.example/auth/callback",
    response_type: "code",
    state,
    code_challenge: challenge,
    code_challenge_method: "S256",
  }).toString();
  redirect(authorize.href);
}

Write GET in app/auth/callback/route.ts. Whatever happens, delete the oauth_state and oauth_verifier cookies: each sign-in uses them once.

The state in the URL must equal the oauth_state cookie exactly, and neither may be missing or empty. Otherwise answer 400 with { error: "This sign-in didn't start here. Try again." }, and don't use the code at all.

Trade the code for the customer's profile with exchangeCode(code, verifier) from @/lib/oauth, with the verifier from the cookie. When there's no code, or exchangeCode returns null, answer 400 with { error: "That sign-in expired. Try again." }.

Otherwise get the shop's user with findOrCreateUser(profile) from @/lib/users, start a session with createSession(user.id) from @/lib/sessions, put its token in a session cookie (httpOnly, secure, sameSite: "lax", path: "/", and a week's maxAge, in seconds), and redirect to /account.

Write this: app/auth/callback/route.ts
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import type { NextRequest } from "next/server";
import { exchangeCode } from "@/lib/oauth";
import { createSession } from "@/lib/sessions";
import { findOrCreateUser } from "@/lib/users";
 
export async function GET(request: NextRequest) {
  const cookieStore = await cookies();
  const code = request.nextUrl.searchParams.get("code") ?? "";
  const profile = await exchangeCode(code, cookieStore.get("oauth_verifier")?.value ?? "");
  if (!profile) return Response.json({ error: "That sign-in expired. Try again." }, { status: 400 });
 
  const user = await findOrCreateUser(profile);
  cookieStore.set("session", await createSession(user.id));
  redirect("/account");
}
lib/oauth.ts (read-only)
import "server-only";
 
export type Profile = { providerId: string; email: string; name: string };
 
/** Every code the app traded, with the verifier it sent: the provider's log. */
export const exchanges: { code: string; verifier: string }[] = [];
 
// The sign-ins people have just finished at the provider: each code, the verifier its
// sign-in started with (sent as a hash, the code challenge), and who signed in.
const grants = new Map<string, { verifier: string; profile: Profile }>([
  ["code-ana", { verifier: "verifier-ana", profile: { providerId: "tp-101", email: "ana@example.com", name: "Ana" } }],
  ["code-eve", { verifier: "verifier-eve", profile: { providerId: "tp-666", email: "eve@example.com", name: "Eve" } }],
]);
 
/**
 * Trades a code for the profile of whoever signed in at the provider, as its token endpoint
 * does, server to server, with the app's client secret. A code works once, and only with the
 * verifier its sign-in started with; otherwise this returns null.
 */
export async function exchangeCode(code: string, verifier: string): Promise<Profile | null> {
  exchanges.push({ code, verifier });
  const grant = grants.get(code);
  if (!grant || grant.verifier !== verifier) return null;
  grants.delete(code);
  return grant.profile;
}
lib/users.ts (read-only)
import "server-only";
import type { Profile } from "./oauth";
 
type User = { id: string; email: string; name: string };
 
// A stand-in for the users table, by the provider account each user signs in with.
export const users = new Map<string, User>([["tp-101", { id: "u_ana", email: "ana@example.com", name: "Ana" }]]);
 
/** The shop's user for this provider account, made on their first sign-in. */
export async function findOrCreateUser(profile: Profile): Promise<User> {
  let user = users.get(profile.providerId);
  if (!user) {
    user = { id: `u_${users.size + 1}`, email: profile.email, name: profile.name };
    users.set(profile.providerId, user);
  }
  return user;
}
lib/sessions.ts (read-only)
import "server-only";
 
// A stand-in for the sessions table. A real token is long and random.
export const sessions = new Map<string, { userId: string }>();
 
/** Starts a session for the user and returns its token, for the session cookie. */
export async function createSession(userId: string): Promise<string> {
  const token = `sess-${sessions.size + 1}`;
  sessions.set(token, { userId });
  return token;
}
The tests your code must pass
  • signs Ana in when the state is this browser's, and sends her to her account
  • refuses a sign-in this browser didn't start, without using the code
  • takes only a state that is there and exactly the cookie's
  • deletes the state and verifier cookies after every callback, whatever its answer
  • answers 400 for a missing, used, or stolen code
  • makes a new user on a first sign-in

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…