Repository Public
1import { NextResponse } from "next/server";2import { z } from "zod";34export class ApiError extends Error {5 constructor(public status: number, public code: string, message?: string, public details?: unknown) { super(message ?? code); }6}78export const ok = (data: unknown, init?: ResponseInit) => NextResponse.json(data, { ...init, headers: { "Cache-Control": "no-store", ...(init?.headers ?? {}) } });910export function fail(e: unknown): NextResponse {11 if (e instanceof ApiError) return NextResponse.json({ error: { code: e.code, message: e.message, details: e.details } }, { status: e.status, headers: { "Cache-Control": "no-store" } });12 if (e instanceof z.ZodError) return NextResponse.json({ error: { code: "invalid_input", message: "Invalid input", details: e.issues.map((i) => ({ path: i.path.join("."), message: i.message })) } }, { status: 400 });13 // Never leak internals; the log line carries no request body.14 console.error(JSON.stringify({ t: new Date().toISOString(), level: "error", msg: "api.unhandled", error: e instanceof Error ? e.name : "unknown", detail: (e instanceof Error ? e.message : String(e)).slice(0, 500) }));15 return NextResponse.json({ error: { code: "internal", message: "Internal error" } }, { status: 500 });16}1718type Ctx<P> = { params: Promise<P> };19export function route<P = Record<string, string>>(fn: (req: Request, params: P) => Promise<Response>) {20 return async (req: Request, ctx: Ctx<P>) => {21 try { return await fn(req, await ctx.params); } catch (e) { return fail(e); }22 };23}2425/** Reads a request body while counting it: the limit holds whatever the Content-Length header claims. */26export async function readBody(req: Request, maxBytes: number): Promise<Buffer> {27 if (Number(req.headers.get("content-length") ?? 0) > maxBytes) throw new ApiError(413, "payload_too_large", "The request body is too large");28 if (!req.body) return Buffer.alloc(0);29 const chunks: Buffer[] = []; let size = 0;30 const reader = req.body.getReader();31 for (;;) {32 const { done, value } = await reader.read();33 if (done) break;34 size += value.length;35 if (size > maxBytes) { await reader.cancel().catch(() => {}); throw new ApiError(413, "payload_too_large", "The request body is too large"); }36 chunks.push(Buffer.from(value));37 }38 return Buffer.concat(chunks);39}4041export async function body<T extends z.ZodType>(req: Request, schema: T, maxBytes = 2_000_000): Promise<z.infer<T>> {42 const text = (await readBody(req, maxBytes)).toString("utf8");43 let raw: unknown;44 try { raw = JSON.parse(text); } catch { throw new ApiError(400, "invalid_json", "Body must be JSON"); }45 return schema.parse(raw);46}4748/**49 * Address of the client as seen by our reverse proxy: the LAST value of X-Forwarded-For, the one the proxy itself50 * appended. Earlier values are whatever the client chose to send and are ignored. The application port must only be51 * reachable through the proxy (docs/DEPLOYMENT.md).52 */53export function clientIp(req: Request): string {54 const xff = req.headers.get("x-forwarded-for");55 return (xff ? xff.split(",").pop()!.trim() : "") || "local";56}5758export const uuid = z.string().uuid();59