SPB Git

Repository Public

core.ts 3.8 KB 60 lines typescript

1import { z } from "zod";2import { checkSession, COOKIE } from "../auth";3import { env } from "../env";45export class HttpError extends Error { constructor(public status: number, message: string, public extra?: Record<string, unknown>) { super(message); } }6export interface Ctx { req: Request; url: URL; params: string[]; ip: string; session: { id: string } | null; cookies: Map<string, string>; setCookies: string[]; body: <T extends z.ZodType>(schema: T) => Promise<z.infer<T>> }7export type Handler = (c: Ctx) => unknown | Promise<unknown>;8interface Route { method: string; re: RegExp; handler: Handler; public: boolean }910const routes: Route[] = [];11/** Register a route. `path` uses `:x` for one segment. Routes are private unless `{ public: true }`. */12export function route(method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", path: string, handler: Handler, opts: { public?: boolean } = {}) {13  routes.push({ method, re: new RegExp("^" + path.replace(/:[a-z]+/gi, "([^/]+)") + "$"), handler, public: !!opts.public });14}1516export function clientIp(req: Request): string {17  // The gateway (Caddy on the tunnel) appends the real client address; the last entry is the only one it vouches for.18  const xff = req.headers.get("x-forwarded-for");19  return xff?.split(",").pop()?.trim() || "local";20}21export function cookie(name: string, value: string, maxAge: number, opts: { path?: string } = {}) {22  return `${name}=${value}; Path=${opts.path ?? "/"}; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${env.prod ? "; Secure" : ""}`;23}2425export async function dispatch(req: Request): Promise<Response> {26  const url = new URL(req.url);27  const path = url.pathname.replace(/^\/api/, "") || "/";28  const headers = new Headers({ "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });29  const reply = (status: number, data: unknown, setCookies: string[] = []) => { for (const c of setCookies) headers.append("set-cookie", c); return new Response(JSON.stringify(data), { status, headers }); };30  try {31    let match: RegExpExecArray | null = null;32    const r = routes.find((x) => x.method === req.method && (match = x.re.exec(path)));33    if (!r || !match) throw new HttpError(404, "Route inconnue");34    // State-changing requests must come from our own pages (defence in depth on top of SameSite cookies).35    if (req.method !== "GET") {36      const origin = req.headers.get("origin");37      if (origin ? origin !== env.appUrl : req.headers.get("sec-fetch-site") !== "same-origin" && env.prod) throw new HttpError(403, "Origine refusée");38    }39    const cookies = new Map((req.headers.get("cookie") ?? "").split(/;\s*/).filter(Boolean).map((p) => { const i = p.indexOf("="); return [p.slice(0, i), p.slice(i + 1)] as [string, string]; }));40    const session = checkSession(cookies.get(COOKIE));41    if (!r.public && !session) throw new HttpError(401, "Authentification requise");42    const ctx: Ctx = {43      req, url, params: (match as RegExpExecArray).slice(1).map(decodeURIComponent), ip: clientIp(req), session, cookies, setCookies: [],44      body: async (schema) => {45        let raw: unknown; try { raw = await req.json(); } catch { throw new HttpError(400, "Corps JSON invalide"); }46        const p = schema.safeParse(raw);47        if (!p.success) throw new HttpError(400, "Requête invalide", { issues: p.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`) });48        return p.data;49      },50    };51    const data = await r.handler(ctx);52    if (data instanceof Response) return data; // binary answers (media files, playlists, subtitles, thumbnails)53    return reply(200, data ?? { ok: true }, ctx.setCookies);54  } catch (e) {55    if (e instanceof HttpError) return reply(e.status, { error: e.message, ...e.extra });56    console.error(`${new Date().toISOString()} ERROR [api] ${req.method} ${path}`, e);57    return reply(500, { error: "Erreur interne" });58  }59}60
Files main
Menu

Theme