SPB Git

Repository Public

_lib.ts 1.9 KB 33 lines typescript

1import { z } from "zod";2import { apiError, clientCtx, originAllowed, type ClientCtx } from "@/lib/auth";3import { log } from "@/lib/log";4import { rateLimit } from "@/lib/ratelimit";5import { AuthError } from "@/lib/webauthn";67/** Réponse WebAuthn du navigateur : la structure fine est validée par @simplewebauthn/server. */8export const credentialSchema = z.object({ id: z.string().min(1).max(1024), rawId: z.string().max(1024), type: z.literal("public-key"), response: z.record(z.string(), z.unknown()) }).passthrough();910/** Contrôle d'origine + limite de débit par IP hachée pour les routes de cérémonie. */11export async function gate(req: Request, scope: string, perMinute: number): Promise<{ ctx: ClientCtx; error?: undefined } | { error: Response; ctx?: undefined }> {12  if (!originAllowed(req)) return { error: apiError(403, "bad_origin", "Origine de la requête refusée.") };13  const ctx = clientCtx(req);14  if (!(await rateLimit(`auth:${scope}:${ctx.ipHash}`, perMinute, 60))) return { error: apiError(429, "rate_limited", "Trop de tentatives. Réessayez dans une minute.") };15  return { ctx };16}17export async function readBody<T extends z.ZodType>(req: Request, schema: T): Promise<z.infer<T>> {18  let raw: unknown;19  try { raw = JSON.parse((await req.text()) || "{}"); } catch { throw new AuthError(400, "bad_request", "Corps JSON invalide."); }20  const r = schema.safeParse(raw);21  if (!r.success) throw new AuthError(400, "bad_request", "Requête invalide.");22  return r.data;23}24/** Convertit les AuthError en JSON ; toute autre erreur devient un 500 sans détail. */25export async function handle(fn: () => Promise<Response>): Promise<Response> {26  try { return await fn(); }27  catch (e) {28    if (e instanceof AuthError) return apiError(e.status, e.code, e.message);29    log("error", "auth.route", { error: e });30    return apiError(500, "server_error", "Erreur interne.");31  }32}33
Files main
Menu

Theme