SPB Git

Repository Public

registry.ts 14.4 KB 240 lines typescript

1// Registre des routes /api/v1 : UNE définition par route (schémas zod + métadonnées) sert à la fois à valider les requêtes2// et à produire la spécification OpenAPI 3.1. Une route absente du registre n'existe pas ; une route du registre est dans la spécification.3import crypto from "node:crypto"4import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"5import { z } from "zod"6import { config } from "../config.js"7import { sql } from "../db.js"8import { keyRate, principalId, principalOf, requireScope, type Principal, type Scope } from "../keys.js"9import { HttpError, bad } from "../util.js"1011export type Ctx<P = any, Q = any, B = any> = { req: FastifyRequest; reply: FastifyReply; principal: Principal; params: P; query: Q; body: B }12export type Method = "GET" | "POST" | "PATCH" | "PUT" | "DELETE"13export type RouteDef = {14  method: Method; path: string; tag: string; summary: string; description?: string15  /** "public" : aucune authentification. Sinon clé d'API ou session. */16  auth?: "public"17  /** L'un de ces scopes est exigé (vide = tout appelant authentifié). Les contrôles par adresse sont faits par le gestionnaire. */18  scopes?: Scope[]19  params?: z.ZodObject<any>; query?: z.ZodObject<any>; body?: z.ZodTypeAny20  /** Corps binaire brut (téléversement) : le flux est remis tel quel au gestionnaire. */21  binaryBody?: boolean; bodyLimit?: number22  /** Schéma de la réponse de succès ; null = contenu binaire. */23  response: z.ZodTypeAny | null24  status?: number; otherStatuses?: Record<number, string>25  /** Accepte l'en-tête Idempotency-Key. */26  idempotent?: boolean27  handler: (ctx: Ctx) => Promise<unknown>28}29/** JSON à clés triées : deux corps identiques au sens JSON donnent la même empreinte, quel que soit l'ordre des clés du client. */30export function canonicalJson(v: unknown): string {31  if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`32  if (v && typeof v === "object") return `{${Object.keys(v as object).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson((v as Record<string, unknown>)[k])}`).join(",")}}`33  return JSON.stringify(v) ?? "null"34}35export const routes: RouteDef[] = []36export function route(def: RouteDef) {37  if (routes.some((r) => r.method === def.method && r.path === def.path)) throw new Error(`duplicate route ${def.method} ${def.path}`)38  routes.push(def)39}40/** Réponse avec un statut autre que celui de la définition (ex. 202 pour une approbation en attente). */41export class Reply { constructor(public status: number, public body: unknown) {} }42export const respond = (status: number, body: unknown) => new Reply(status, body)4344export const zErrorEnvelope = z.object({ error: z.object({ code: z.string(), message: z.string(), details: z.unknown().optional() }) })45export const errorBody = (code: string, message: string, details?: unknown) => ({ error: { code, message, ...(details === undefined ? {} : { details }) } })4647function validate<T extends z.ZodTypeAny>(schema: T, data: unknown, where: string): z.infer<T> {48  const r = schema.safeParse(data)49  if (!r.success) throw bad("invalid_request", 400, `Invalid ${where}: ${r.error.issues.map((i) => `${i.path.join(".") || where}: ${i.message}`).join("; ")}`.slice(0, 800), { issues: r.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })).slice(0, 20) })50  return r.data51}5253declare module "fastify" {54  interface FastifyRequest { v1?: { principal?: Principal; errorCode?: string; started: number } }55}5657function logUsage(req: FastifyRequest, def: RouteDef, status: number) {58  const p = req.v1?.principal59  if (!p || p.type !== "key") return60  void sql`insert into api_usage (key_id, method, route, status, duration_ms, ip, error_code, explorer)61    values (${p.keyId}, ${def.method}, ${`/api/v1${def.path}`}, ${status}, ${Date.now() - (req.v1?.started ?? Date.now())}, ${req.ip}, ${req.v1?.errorCode ?? null}, ${p.explorer})`.catch(() => {})62}6364async function run(def: RouteDef, req: FastifyRequest, reply: FastifyReply): Promise<Reply> {65  if (/[?&][^=]*=sp[mx]_[A-Za-z0-9]/.test(req.url)) throw bad("token_in_url", 400, "API tokens must be sent in the Authorization header, never in the URL")66  let principal: Principal | undefined67  if (def.auth !== "public") {68    principal = await principalOf(req)69    req.v1!.principal = principal70    if (principal.type === "key") {71      const r = keyRate(principal)72      reply.header("x-ratelimit-limit", r.limit).header("x-ratelimit-remaining", r.remaining).header("x-ratelimit-reset", r.reset)73      if (r.exceeded) {74        reply.header("retry-after", Math.max(1, r.reset - Math.floor(Date.now() / 1000)))75        throw bad("rate_limited", 429, `Rate limit of ${r.limit} requests per minute exceeded`)76      }77    }78    if (def.scopes?.length) requireScope(principal, ...def.scopes)79  }80  const params = def.params ? validate(def.params, req.params, "path") : {}81  const query = def.query ? validate(def.query, req.query ?? {}, "query") : {}82  const body = def.binaryBody ? req.body : def.body ? validate(def.body, req.body ?? {}, "body") : undefined83  const ctx: Ctx = { req, reply, principal: principal as Principal, params, query, body }8485  // Idempotence : même clé + même charge → même réponse (24 h) ; même clé + charge différente → 409.86  const idem = def.idempotent && principal ? req.headers["idempotency-key"] : undefined87  if (idem !== undefined) {88    if (typeof idem !== "string" || !/^[\x21-\x7e]{1,200}$/.test(idem)) throw bad("invalid_idempotency_key", 400, "Idempotency-Key must be 1–200 printable ASCII characters")89    const who = principalId(principal!)90    const hash = crypto.createHash("sha256").update(canonicalJson([def.method, def.path, params, query, def.binaryBody ? null : (req.body ?? null)])).digest()91    const ins = await sql`insert into idempotency_keys (principal, idem_key, payload_hash) values (${who}, ${idem}, ${hash}) on conflict do nothing returning 1`92    if (!ins.length) {93      const [row] = await sql`select payload_hash, status, response, created_at from idempotency_keys where principal = ${who} and idem_key = ${idem}`94      if (row && Date.now() - new Date(row.created_at).getTime() > 24 * 3600_000) {95        await sql`delete from idempotency_keys where principal = ${who} and idem_key = ${idem}`96        throw bad("idempotency_key_expired", 409, "This Idempotency-Key has expired; retry with a new key")97      }98      if (!row || !Buffer.from(row.payload_hash).equals(hash)) throw bad("idempotency_conflict", 409, "This Idempotency-Key was already used with a different request")99      if (row.status === null) throw bad("idempotency_in_progress", 409, "A request with this Idempotency-Key is still being processed")100      reply.header("idempotency-replayed", "true")101      return new Reply(row.status, row.response)102    }103    try {104      const out = await def.handler(ctx)105      const res = out instanceof Reply ? out : new Reply(def.status ?? 200, out)106      await sql`update idempotency_keys set status = ${res.status}, response = ${sql.json(res.body as never)} where principal = ${who} and idem_key = ${idem}`107      return res108    } catch (e) {109      // Un refus déterministe (4xx) est rejoué tel quel ; une panne (5xx) libère la clé pour une nouvelle tentative.110      if (e instanceof HttpError && e.status < 500 && e.status !== 429)111        await sql`update idempotency_keys set status = ${e.status}, response = ${sql.json(errorBody(e.code, e.message, e.details) as never)} where principal = ${who} and idem_key = ${idem}`112      else await sql`delete from idempotency_keys where principal = ${who} and idem_key = ${idem}`113      throw e114    }115  }116  const out = await def.handler(ctx)117  return out instanceof Reply ? out : new Reply(def.status ?? 200, out)118}119120export function registerV1(app: FastifyInstance) {121  app.register(async (v1) => {122    v1.addHook("onRequest", async (req, reply) => {123      req.v1 = { started: Date.now() }124      reply.header("x-request-id", req.id)125    })126    for (const def of routes) {127      const url = def.path.replace(/\{(\w+)\}/g, ":$1")128      const handler = async (req: FastifyRequest, reply: FastifyReply) => {129        try {130          const res = await run(def, req, reply)131          if (reply.sent || res.body === undefined) { logUsage(req, def, reply.statusCode); return reply }132          if (config.validateResponses && def.response && res.status < 300 && !reply.getHeader("idempotency-replayed")) {133            const check = def.response.safeParse(res.body)134            if (!check.success) throw new Error(`response of ${def.method} ${def.path} does not match its schema: ${check.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ").slice(0, 500)}`)135          }136          logUsage(req, def, res.status)137          return reply.status(res.status).send(res.body)138        } catch (e) {139          if (e instanceof HttpError) {140            req.v1!.errorCode = e.code141            logUsage(req, def, e.status)142            return reply.status(e.status).send(errorBody(e.code, e.message, e.details))143          }144          req.v1!.errorCode = "internal"145          logUsage(req, def, 500)146          req.log.error({ err: { message: (e as Error).message, stack: (e as Error).stack } }, "unhandled error")147          return reply.status(500).send(errorBody("internal", "Internal error"))148        }149      }150      if (def.binaryBody) {151        v1.register(async (raw) => {152          raw.removeAllContentTypeParsers()153          raw.addContentTypeParser("*", (_req, payload, done) => done(null, payload))154          raw.route({ method: def.method, url, bodyLimit: def.bodyLimit ?? 50 * 1024 * 1024, handler })155        })156      } else v1.route({ method: def.method, url, ...(def.bodyLimit ? { bodyLimit: def.bodyLimit } : {}), handler })157    }158  }, { prefix: "/api/v1" })159}160161// ------------------------------------------------------------------ OpenAPI 3.1, dérivée des mêmes définitions162const jsonSchema = (s: z.ZodTypeAny, io: "input" | "output") => {163  const j = z.toJSONSchema(s, { io, unrepresentable: "any", target: "draft-2020-12" }) as Record<string, unknown>164  delete j.$schema165  return j166}167export function buildOpenApi(): Record<string, any> {168  const paths: Record<string, any> = {}169  for (const def of [...routes].sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method))) {170    const parameters: any[] = []171    for (const [where, schema] of [["path", def.params], ["query", def.query]] as const) {172      if (!schema) continue173      const js = jsonSchema(schema, "input") as { properties?: Record<string, any>; required?: string[] }174      for (const [name, prop] of Object.entries(js.properties ?? {})) {175        const { description, ...rest } = prop176        parameters.push({ name, in: where, required: where === "path" || (js.required ?? []).includes(name), ...(description ? { description } : {}), schema: rest })177      }178    }179    if (def.idempotent) parameters.push({ name: "Idempotency-Key", in: "header", required: false, description: "Replays the stored response for 24 h; a different payload with the same key answers 409.", schema: { type: "string", maxLength: 200 } })180    const ok = String(def.status ?? 200)181    const responses: Record<string, any> = {182      [ok]: def.response183        ? { description: "Success", content: { "application/json": { schema: jsonSchema(def.response, "output") } } }184        : { description: "Binary content", content: { "application/octet-stream": { schema: { type: "string", format: "binary" } } } },185    }186    for (const [code, description] of Object.entries(def.otherStatuses ?? {})) responses[code] = { description }187    responses.default = { description: "Error", content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } }188    const op: Record<string, any> = {189      operationId: `${def.method.toLowerCase()}${def.path.replace(/[{}]/g, "").split(/[/-]/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("")}`,190      tags: [def.tag], summary: def.summary, ...(def.description ? { description: def.description } : {}),191      ...(parameters.length ? { parameters } : {}),192      ...(def.binaryBody ? { requestBody: { required: true, content: { "application/octet-stream": { schema: { type: "string", format: "binary" } } } } }193        : def.body ? { requestBody: { required: true, content: { "application/json": { schema: jsonSchema(def.body, "input") } } } } : {}),194      responses,195      security: def.auth === "public" ? [] : [{ apiKey: [] }, { session: [] }],196      "x-required-scopes": def.scopes ?? [],197    }198    ;(paths[def.path] ??= {})[def.method.toLowerCase()] = op199  }200  return {201    openapi: "3.1.0",202    info: { title: "SP Mail API", version: "1.0.0", description: "Universal REST API of SP Mail. Human contract: docs/API.md. Generated from the route registry that validates requests." },203    servers: [{ url: `${config.origin}/api/v1` }],204    tags: [...new Set(routes.map((r) => r.tag))].map((name) => ({ name })),205    paths,206    components: {207      securitySchemes: {208        apiKey: { type: "http", scheme: "bearer", description: "API key: Authorization: Bearer spm_<prefix>_<secret>" },209        session: { type: "apiKey", in: "cookie", name: "__Host-spmail_session", description: "Web session (or native bearer session token) of the owner" },210      },211      schemas: { Error: jsonSchema(zErrorEnvelope, "output") },212    },213  }214}215216/** Sérialisation YAML minimale (sans dépendance) d'un document JSON. */217export function toYaml(v: unknown, indent = 0): string {218  const pad = "  ".repeat(indent)219  const scalar = (x: unknown): string => {220    if (x === null || x === undefined) return "null"221    if (typeof x === "number" || typeof x === "boolean") return String(x)222    return JSON.stringify(String(x))223  }224  const key = (k: string) => (/^[A-Za-z_][A-Za-z0-9_-]*$/.test(k) ? k : JSON.stringify(k))225  if (Array.isArray(v)) {226    if (!v.length) return "[]"227    return v.map((x) => (x !== null && typeof x === "object" && Object.keys(x).length ? `${pad}-\n${toYaml(x, indent + 1)}` : `${pad}- ${Array.isArray(x) ? "[]" : x !== null && typeof x === "object" ? "{}" : scalar(x)}`)).join("\n")228  }229  if (v !== null && typeof v === "object") {230    const entries = Object.entries(v as Record<string, unknown>).filter(([, x]) => x !== undefined)231    if (!entries.length) return `${pad}{}`232    return entries.map(([k, x]) => {233      if (Array.isArray(x)) return x.length ? `${pad}${key(k)}:\n${toYaml(x, indent + 1)}` : `${pad}${key(k)}: []`234      if (x !== null && typeof x === "object") return Object.keys(x).length ? `${pad}${key(k)}:\n${toYaml(x, indent + 1)}` : `${pad}${key(k)}: {}`235      return `${pad}${key(k)}: ${scalar(x)}`236    }).join("\n")237  }238  return `${pad}${scalar(v)}`239}240
Files main
Menu

Theme