import { randomUUID } from "node:crypto"; import { Hono, type Context, type Next } from "hono"; import { cors } from "hono/cors"; import type { SessionUser } from "../models/types.js"; import type { Config } from "../config/appConfig.js"; import type { Db } from "../config/db.js"; import { AppError, toSafeError } from "./errors.js"; export interface Logger { level: Config["LOG_LEVEL"]; info: (message: string, fields?: Record) => void; warn: (message: string, fields?: Record) => void; error: (message: string, fields?: Record) => void; debug: (message: string, fields?: Record) => void; } const ORDER: Record = { silent: 0, error: 1, warn: 2, info: 3, debug: 4, }; export const createLogger = (level: Config["LOG_LEVEL"], service: string): Logger => { const emit = (name: keyof typeof ORDER, message: string, fields?: Record) => { if (ORDER[name] > ORDER[level]) return; const line = JSON.stringify({ ts: new Date().toISOString(), level: name, service, msg: message, ...fields, }); if (name === "error") console.error(line); else console.log(line); }; return { level, info: (message, fields) => emit("info", message, fields), warn: (message, fields) => emit("warn", message, fields), error: (message, fields) => emit("error", message, fields), debug: (message, fields) => emit("debug", message, fields), }; }; export interface AppEnv { Variables: { requestId: string; user?: SessionUser; token?: string; }; } export type App = Hono; export const clientIp = (context: Context, trustProxy: boolean): string | null => { if (trustProxy) { const forwarded = context.req.header("x-forwarded-for"); const first = forwarded?.split(",")[0]?.trim(); if (first) return first.slice(0, 45); } const env = context.env as | { incoming?: { socket?: { remoteAddress?: string } } } | undefined; const address = env?.incoming?.socket?.remoteAddress; return address ? address.slice(0, 45) : null; }; export const JSON_BODY_MAX_BYTES = 1024 * 1024; export const readBodyCapped = async (context: Context, maxBytes: number): Promise => { const declared = Number(context.req.header("content-length") ?? ""); if (Number.isFinite(declared) && declared > maxBytes) { throw AppError.payloadTooLarge("Corps de requete trop volumineux."); } const body = context.req.raw.body; if (body === null) return Buffer.alloc(0); const chunks: Uint8Array[] = []; let received = 0; const reader = body.getReader(); try { for (;;) { const { done, value } = await reader.read(); if (done) break; received += value.byteLength; if (received > maxBytes) { await reader.cancel().catch(() => undefined); throw AppError.payloadTooLarge("Corps de requete trop volumineux."); } chunks.push(value); } } finally { reader.releaseLock(); } return Buffer.concat(chunks); }; export const readJson = async ( context: Context, maxBytes = JSON_BODY_MAX_BYTES, ): Promise => { const buffer = await readBodyCapped(context, maxBytes); if (buffer.byteLength === 0) return null; try { return JSON.parse(buffer.toString("utf8")) as unknown; } catch { return null; } }; export interface RouteDeps { db: Db; config: Config; logger: Logger; } export interface AppOptions { service: string; config: Config; db: Db; logger: Logger; routes: (app: App, deps: RouteDeps) => void; probeDb?: boolean; } export const createApp = ({ service, config, db, logger, routes, probeDb = true }: AppOptions): App => { const app = new Hono(); app.use("*", async (context: Context, next: Next) => { const requestId = context.req.header("x-request-id") ?? randomUUID(); context.set("requestId", requestId); context.res.headers.set("x-request-id", requestId); context.res.headers.set("x-content-type-options", "nosniff"); context.res.headers.set("referrer-policy", "same-origin"); context.res.headers.set("x-frame-options", "DENY"); const started = performance.now(); await next(); const duration = Math.round(performance.now() - started); if (context.req.method !== "OPTIONS") { logger.debug("requete", { requestId, method: context.req.method, path: new URL(context.req.url).pathname, status: context.res.status, durationMs: duration, }); } }); if (config.CORS_ORIGIN) { app.use( "*", cors({ origin: config.CORS_ORIGIN.split(",").map((value) => value.trim()), credentials: true, maxAge: 600, }), ); } app.get("/healthz", async (context) => { if (!probeDb) return context.json({ status: "ok", service }, 200); const started = performance.now(); try { await db.query("SELECT 1"); return context.json( { status: "ok", service, db: "up", latencyMs: Math.round(performance.now() - started) }, 200, ); } catch (error) { logger.error("sante base en echec", { error: String(error) }); return context.json({ status: "degraded", service, db: "down" }, 503); } }); routes(app, { db, config, logger }); app.notFound((context) => context.json({ error: { status: 404, code: "NOT_FOUND", message: "Route introuvable." } }, 404), ); app.onError((error, context) => { const safe = toSafeError(error); const requestId = context.get("requestId"); if (safe.status >= 500) { logger.error("erreur non geree", { requestId, code: safe.code, message: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, }); } else { logger.debug("refus", { requestId, code: safe.code, status: safe.status }); } return context.json({ error: { ...safe, requestId } }, safe.status as 500); }); return app; }; export { AppError };