Repository Public
1// /api/v1 — introspection : appelant, santé, spécification OpenAPI.2import { z } from "zod"3import { presentAddress } from "../addresses.js"4import { config } from "../config.js"5import { sql } from "../db.js"6import { SCOPES } from "../keys.js"7import { sentToday } from "../outbound.js"8import { accessMap } from "./context.js"9import { buildOpenApi, respond, route, toYaml } from "./registry.js"1011route({12 method: "GET", path: "/health", tag: "Introspection", summary: "Liveness of the API, database and mail server", auth: "public",13 response: z.object({ ok: z.boolean(), version: z.string(), database: z.enum(["ok", "down"]), mail_server: z.enum(["reachable", "unreachable"]), workers: z.enum(["on", "off"]) }),14 otherStatuses: { 503: "Database or mail server unreachable (same body)" },15 handler: async () => {16 const db = await sql`select 1`.then(() => "ok" as const, () => "down" as const)17 const r = await fetch(`${config.stalwartUrl}/jmap/session`, { signal: AbortSignal.timeout(4000) }).catch(() => null)18 const body = { ok: db === "ok" && !!r, version: config.version, database: db, mail_server: r ? ("reachable" as const) : ("unreachable" as const), workers: config.workers ? ("on" as const) : ("off" as const) }19 return body.ok ? body : respond(503, body)20 },21})2223route({24 method: "GET", path: "/me", tag: "Introspection", summary: "Who am I: scopes, allowed addresses, limits, usage today",25 response: z.object({26 type: z.enum(["key", "user"]), id: z.string(), name: z.string(), explorer: z.boolean(), scopes: z.array(z.string()), all_addresses: z.boolean(),27 addresses: z.array(z.object({ id: z.string(), address: z.string(), kind: z.string(), mailbox: z.string(), status: z.string(), can_send: z.boolean(), can_receive: z.boolean(), read: z.enum(["full", "restricted", "none"]) })),28 limits: z.object({ rate_per_minute: z.number().nullable(), daily_send_limit: z.number().nullable(), external_send_policy: z.string(), allowed_recipient_domains: z.array(z.string()) }),29 usage_today: z.object({ sent: z.number(), requests: z.number() }), version: z.string(),30 }),31 handler: async ({ principal: p }) => {32 const acc = [...(await accessMap(p)).values()]33 const addresses = acc.flatMap((a) => a.addresses.map((x) => {34 const v = presentAddress(x, a.mailbox.address)35 return { id: v.id, address: v.address, kind: v.kind, mailbox: a.mailbox.address, status: v.expired ? "suspended" : v.status, can_send: v.can_send && a.canSend, can_receive: v.can_receive, read: a.read === "full" ? ("full" as const) : a.read === "none" ? ("none" as const) : x.address === a.mailbox.address ? ("full" as const) : ("restricted" as const) }36 })).sort((x, y) => x.address.localeCompare(y.address))37 if (p.type === "key") {38 const [u] = await sql`select count(*)::int as n from api_usage where key_id = ${p.keyId} and at >= date_trunc('day', now() at time zone 'utc') at time zone 'utc'`39 return {40 type: "key" as const, id: p.keyId, name: p.name, explorer: p.explorer, scopes: [...p.scopes].sort(), all_addresses: p.allAddresses, addresses,41 limits: { rate_per_minute: p.ratePerMinute, daily_send_limit: p.dailySendLimit, external_send_policy: p.externalPolicy, allowed_recipient_domains: p.allowedDomains },42 usage_today: { sent: await sentToday(p.keyId), requests: u.n }, version: config.version,43 }44 }45 const [u] = await sql`select handle from users where id = ${p.userId}`46 const [s] = await sql`select count(*)::int as n from outbound_messages where user_id = ${p.userId} and created_at >= date_trunc('day', now() at time zone 'utc') at time zone 'utc'`47 return {48 type: "user" as const, id: p.userId, name: u.handle, explorer: false, scopes: SCOPES.filter((x) => x !== "mail.admin" || p.role === "admin"), all_addresses: false, addresses,49 limits: { rate_per_minute: null, daily_send_limit: null, external_send_policy: "allow", allowed_recipient_domains: [] }, usage_today: { sent: s.n, requests: 0 }, version: config.version,50 }51 },52})5354route({ method: "GET", path: "/openapi.json", tag: "Introspection", summary: "OpenAPI 3.1 description (JSON), generated from the route registry", auth: "public", response: z.record(z.string(), z.unknown()), handler: async () => buildOpenApi() })55route({56 method: "GET", path: "/openapi.yaml", tag: "Introspection", summary: "OpenAPI 3.1 description (YAML)", auth: "public", response: null,57 handler: async ({ reply }) => { reply.type("application/yaml; charset=utf-8").send(`${toYaml(buildOpenApi())}\n`); return undefined },58})59