SPB Git

Repository Public

http.ts 3.4 KB 60 lines typescript

1import { env } from "../lib/env";2import { log } from "./log";34/** A refusal with an HTTP status, a stable machine code and a French message fit to be shown to an editor. */5export class ApiError extends Error {6  constructor(public status: number, public code: string, message?: string, public extra?: Record<string, unknown>) { super(message ?? code); }7}89const PRIVATE = { "Cache-Control": "private, no-store", "X-Robots-Tag": "noindex, nofollow, noarchive" };10export const json = (body: unknown, init?: ResponseInit) => Response.json(body, { ...init, headers: { ...PRIVATE, ...(init?.headers ?? {}) } });1112/** The gateway sets X-Forwarded-For; the node itself is not reachable from the Internet. */13export function clientIp(req: Request): string {14  return (req.headers.get("x-forwarded-for") ?? "").split(",")[0]!.trim() || "local";15}1617/** CSRF, first line: a state-changing request must come from the studio's own origin. */18export function assertSameOrigin(req: Request): void {19  const origin = req.headers.get("origin");20  if (origin && origin !== env.studioOrigin) throw new ApiError(403, "bad_origin", "Requête d'une autre origine refusée.");21  const site = req.headers.get("sec-fetch-site");22  if (site && site !== "same-origin" && site !== "none") throw new ApiError(403, "bad_origin", "Requête intersites refusée.");23}2425/** Wraps a handler: typed refusals become JSON answers, anything else a bare 500 (no internals leaked). */26export function route<A extends unknown[]>(fn: (req: Request, ...a: A) => Promise<Response> | Response) {27  return async (req: Request, ...a: A): Promise<Response> => {28    try { return await fn(req, ...a); }29    catch (e) {30      if (e instanceof ApiError) {31        const headers: Record<string, string> = {};32        if (e.status === 429 && typeof e.extra?.retryAfterSeconds === "number") headers["Retry-After"] = String(e.extra.retryAfterSeconds);33        return json({ error: { code: e.code, message: e.message, ...e.extra } }, { status: e.status, headers });34      }35      log("error", "api.unhandled", { method: req.method, path: new URL(req.url).pathname, error: e });36      return json({ error: { code: "internal", message: "Erreur interne." } }, { status: 500 });37    }38  };39}4041export async function readJson<T = unknown>(req: Request, maxBytes = 2_000_000): Promise<T> {42  const raw = await req.text();43  if (Buffer.byteLength(raw) > maxBytes) throw new ApiError(413, "too_large", "Corps de requête trop volumineux.");44  try { return JSON.parse(raw) as T; } catch { throw new ApiError(400, "bad_json", "JSON invalide."); }45}4647type Bucket = { n: number; reset: number };48const g = globalThis as typeof globalThis & { __atlasRl?: Map<string, Bucket> };49const buckets = (g.__atlasRl ??= new Map());5051/** Fixed-window limiter kept in memory (one server process). Throws 429 with Retry-After when exceeded. */52export function rateLimit(scope: string, key: string, max: number, windowSec: number): void {53  const k = `${scope}:${key}`, t = Date.now();54  let b = buckets.get(k);55  if (!b || b.reset <= t) { b = { n: 0, reset: t + windowSec * 1000 }; buckets.set(k, b); }56  if (++b.n > max) throw new ApiError(429, "rate_limited", "Trop de requêtes. Réessayez dans un instant.", { retryAfterSeconds: Math.ceil((b.reset - t) / 1000) });57  if (buckets.size > 20_000) for (const [bk, bv] of buckets) if (bv.reset <= t) buckets.delete(bk);58}59export const resetRateLimits = () => buckets.clear();60
Files main
Menu

Theme