SPB Git

Repository Public

guard.ts 4.1 KB 80 lines typescript

1/**2 * The studio's gate, as seen from Next.js: the session cookie, and the checks that every private page and3 * every private API call goes through. Authorisation is decided here, on the server, for each request —4 * never by hiding a link or a button.5 *6 * The cookies are scoped to /admin: the browser does not even send them to the public pages, the public7 * site never reads or sets one, and a learner — who never opens /admin — never receives any.8 */9import "server-only";10import { cookies } from "next/headers";11import { notFound, redirect } from "next/navigation";12import {13  PREAUTH_COOKIE, SESSION_COOKIE, bindingOf, can, issueSession, revokeSession, sessionFromToken, type Editor, type Permission, type StudioSession,14} from "@/server/auth";15import { randomToken, safeEqual } from "@/server/crypto";16import { ApiError, assertSameOrigin, clientIp, rateLimit } from "@/server/http";17import { bootstrap } from "@/server/sync";18import { env } from "../env";1920export const STUDIO_PATH = "/admin";21const cookieBase = () => ({ httpOnly: true, secure: env.secureCookies, sameSite: "strict" as const });2223/** The studio is closed in the development preview mode (which never reads the studio database). */24export const studioEnabled = () => env.mode === "production";2526export async function currentSession(): Promise<StudioSession | null> {27  if (!studioEnabled()) return null;28  return sessionFromToken((await cookies()).get(SESSION_COOKIE)?.value);29}3031/** Guard of every private page: no session → the sign-in page; insufficient role → 404, as if the page did not exist. */32export async function requireEditorPage(permission: Permission = "edit"): Promise<StudioSession> {33  if (!studioEnabled()) notFound();34  const session = await currentSession();35  if (!session) redirect(`${STUDIO_PATH}/connexion`);36  if (!can(session.editor.role, permission)) notFound();37  await bootstrap(session.editor.id);38  return session;39}4041/**42 * Guard of every private API call: a live session, the permission the action needs, and for anything that43 * changes state a same-origin request carrying the session's CSRF token. Writes are rate limited per session.44 */45export async function requireEditor(req: Request, permission: Permission = "edit"): Promise<StudioSession> {46  if (!studioEnabled()) throw new ApiError(404, "not_found", "Introuvable.");47  const session = await currentSession();48  if (!session) throw new ApiError(401, "unauthenticated", "Connexion requise.");49  if (req.method !== "GET" && req.method !== "HEAD") {50    assertSameOrigin(req);51    if (!safeEqual(req.headers.get("x-csrf-token") ?? "", session.csrf)) throw new ApiError(403, "csrf", "Jeton CSRF absent ou invalide.");52    const chunk = req.method === "PUT" && /\/uploads\/[^/]+\/chunks\//.test(new URL(req.url).pathname);53    rateLimit(chunk ? "chunk" : "write", session.tokenHash, chunk ? 3000 : 240, 60);54  } else rateLimit("read", session.tokenHash, 1200, 60);55  if (!can(session.editor.role, permission)) throw new ApiError(403, "forbidden", "Votre rôle ne permet pas cette action.");56  await bootstrap(session.editor.id);57  return session;58}5960export async function startSession(editor: Editor, req: Request): Promise<void> {61  const jar = await cookies();62  const { token, expires } = issueSession(editor.id, { ip: clientIp(req), ua: req.headers.get("user-agent") ?? "", previous: jar.get(SESSION_COOKIE)?.value });63  jar.set(SESSION_COOKIE, token, { ...cookieBase(), path: STUDIO_PATH, expires });64  jar.set(PREAUTH_COOKIE, "", { ...cookieBase(), path: `${STUDIO_PATH}/api/auth`, maxAge: 0 });65}6667export async function endSession(): Promise<void> {68  const jar = await cookies();69  revokeSession(jar.get(SESSION_COOKIE)?.value);70  jar.set(SESSION_COOKIE, "", { ...cookieBase(), path: STUDIO_PATH, maxAge: 0 });71}7273/** Ties an anonymous WebAuthn ceremony to the browser that started it, through a short-lived HttpOnly cookie. */74export async function preauthBinding(create: boolean): Promise<string | null> {75  const jar = await cookies();76  let v = jar.get(PREAUTH_COOKIE)?.value;77  if (!v && create) { v = randomToken(24); jar.set(PREAUTH_COOKIE, v, { ...cookieBase(), path: `${STUDIO_PATH}/api/auth`, maxAge: 600 }); }78  return v ? bindingOf(v) : null;79}80
Files main
Menu

Theme