Repository Public
1import { z } from "zod";2import { ApiError, body, clientIp } from "../http";3import { rateLimit } from "../ratelimit";4import { safeEqual } from "../crypto";5import {6 assertSameOrigin, authenticationOptions, clearSessionCookie, currentUser, decideDeviceLink, deviceLinkInfo, loginWithRecoveryCode, pollDeviceLink,7 registrationOptions, revokeSession, setupTokenInfo, startDeviceLink, verifyAuthentication, verifyRegistration, type UserContext,8} from "../auth";9import { audit } from "../audit";10import type { RouteDef } from "./router";1112const anyJson = z.record(z.string(), z.unknown());13const csrfOk = (req: Request, u: UserContext) => { if (!safeEqual(req.headers.get("x-csrf-token") ?? "", u.csrfToken)) throw new ApiError(403, "csrf", "Invalid CSRF token"); };1415/** Public surface: everything a signed-out browser may call. Each route is rate-limited per client address. */16export const authRoutes: RouteDef<{ ip: string }>[] = [17 ["GET", "session", async () => {18 const u = await currentUser();19 return u ? { authenticated: true, csrfToken: u.csrfToken, user: { id: u.userId, email: u.email, displayName: u.displayName, role: u.role, isOwner: u.isOwner, locale: u.locale, accent: u.accent } } : { authenticated: false };20 }],21 ["POST", "setup/info", async ({ req, ctx }) => {22 assertSameOrigin(req); await rateLimit(`auth:${ctx.ip}`, 30, 600);23 const b = await body(req, z.object({ setupToken: z.string().min(20).max(200) }));24 return setupTokenInfo(b.setupToken);25 }],26 ["POST", "register/options", async ({ req, ctx }) => {27 assertSameOrigin(req); await rateLimit(`auth:${ctx.ip}`, 30, 600);28 const b = await body(req, z.object({ setupToken: z.string().max(200).optional() }));29 const user = b.setupToken ? null : await currentUser();30 if (user) csrfOk(req, user);31 return registrationOptions({ setupToken: b.setupToken, user });32 }],33 ["POST", "register/verify", async ({ req, ctx }) => {34 assertSameOrigin(req); await rateLimit(`auth:${ctx.ip}`, 30, 600);35 const b = await body(req, z.object({ challengeId: z.string().uuid(), response: anyJson, name: z.string().max(60).optional(), setupToken: z.string().max(200).optional() }));36 const user = b.setupToken ? null : await currentUser();37 if (user) csrfOk(req, user);38 return verifyRegistration({ challengeId: b.challengeId, response: b.response as never, name: b.name, setupToken: b.setupToken, user }, req);39 }],40 ["POST", "login/options", async ({ req, ctx }) => { assertSameOrigin(req); await rateLimit(`auth:${ctx.ip}`, 30, 600); return authenticationOptions(); }],41 ["POST", "login/verify", async ({ req, ctx }) => {42 assertSameOrigin(req); await rateLimit(`auth:${ctx.ip}`, 30, 600);43 const b = await body(req, z.object({ challengeId: z.string().uuid(), response: anyJson }));44 return verifyAuthentication({ challengeId: b.challengeId, response: b.response as never }, req);45 }],46 ["POST", "recovery", async ({ req, ctx }) => {47 assertSameOrigin(req); await rateLimit(`recovery:${ctx.ip}`, 5, 900);48 const b = await body(req, z.object({ code: z.string().min(8).max(40) }));49 return loginWithRecoveryCode(b.code, req);50 }],51 // Device linking for native apps (see src/lib/auth.ts). start/poll are called by the app, info/decide by a signed-in browser.52 ["POST", "device/start", async ({ req, ctx }) => {53 assertSameOrigin(req); await rateLimit(`device:${ctx.ip}`, 10, 600);54 const b = await body(req, z.object({ deviceName: z.string().max(80).optional() }).strict());55 return startDeviceLink(b.deviceName ?? "", req);56 }],57 ["POST", "device/poll", async ({ req, ctx }) => {58 assertSameOrigin(req); await rateLimit(`devicepoll:${ctx.ip}`, 600, 600);59 const b = await body(req, z.object({ deviceCode: z.string().min(20).max(200) }).strict());60 return pollDeviceLink(b.deviceCode, req);61 }],62 ["POST", "device/info", async ({ req }) => {63 assertSameOrigin(req);64 const u = await currentUser();65 if (!u) throw new ApiError(401, "unauthenticated", "Sign in required");66 csrfOk(req, u); await rateLimit(`devicecode:${u.userId}`, 30, 600); // also bounds guessing of someone else's code67 const b = await body(req, z.object({ userCode: z.string().min(8).max(20) }).strict());68 return deviceLinkInfo(b.userCode);69 }],70 ["POST", "device/decide", async ({ req }) => {71 assertSameOrigin(req);72 const u = await currentUser();73 if (!u) throw new ApiError(401, "unauthenticated", "Sign in required");74 csrfOk(req, u); await rateLimit(`devicecode:${u.userId}`, 30, 600);75 const b = await body(req, z.object({ userCode: z.string().min(8).max(20), approve: z.boolean() }).strict());76 return decideDeviceLink(u, b.userCode, b.approve, req);77 }],78 ["POST", "logout", async ({ req }) => {79 assertSameOrigin(req);80 const u = await currentUser();81 if (u) { csrfOk(req, u); await revokeSession(u.sessionId, u.userId); await audit({ userId: u.userId, actor: u.role, action: "logout", ip: clientIp(req) }); }82 await clearSessionCookie();83 return { ok: true };84 }],85];86