SPB Git

Repository Public

adminapi.ts 18.4 KB 272 lines typescript

1// Administration de l'API : clés, usage, approbations d'envois externes, liste d'autorisation interne des webhooks,2// messages programmés, métriques de remise, partages de boîtes. Session + rôle admin ; les mutations sensibles exigent une réauthentification.3import type { FastifyInstance } from "fastify"4import { z } from "zod"5import { syncAddresses } from "./addresses.js"6import { sql } from "./db.js"7import { createKey, mintExplorerToken, presentKey, SCOPES, validateKeyInput, type KeyRow } from "./keys.js"8import { jmapOk, mailboxById } from "./mailjmap.js"9import { cancelOutbound, outboundById, presentOutbound, submitOutbound, type OutboundRow } from "./outbound.js"10import { requireAdminReauth } from "./reauth.js"11import { requireAdmin } from "./session.js"12import { audit, bad, parse, zUuid } from "./util.js"13import { retention } from "./workers/maintenance.js"1415const zScopes = z.array(z.enum(SCOPES)).min(1).max(SCOPES.length)16const zKeyBody = z.object({17  name: z.string().trim().min(1).max(80), description: z.string().max(500).default(""), scopes: zScopes,18  address_ids: z.array(zUuid).max(500).default([]), all_addresses: z.boolean().default(false),19  rate_per_minute: z.number().int().min(1).max(6000).default(60), daily_send_limit: z.number().int().min(0).max(100000).default(200),20  external_send_policy: z.enum(["allow", "approval", "deny"]).default("approval"),21  allowed_recipient_domains: z.array(z.string().trim().toLowerCase().regex(/^[a-z0-9.-]{3,253}$/)).max(100).default([]),22  expires_at: z.string().refine((s) => !Number.isNaN(Date.parse(s)), "invalid date").nullable().default(null),23}).strict()24const zId = z.object({ id: zUuid })2526async function keyById(id: string): Promise<KeyRow> {27  const [k] = await sql`select * from api_keys where id = ${id}`28  if (!k) throw bad("not_found", 404)29  return k as KeyRow30}3132export function adminApiRoutes(app: FastifyInstance) {33  // ---------------------------------------------------------------- clés d'API34  app.get("/api/admin/api-keys", async (req) => {35    await requireAdmin(req)36    return ((await sql`select * from api_keys order by created_at desc`) as unknown as KeyRow[]).map(presentKey)37  })38  app.get("/api/admin/api-keys/:id", async (req) => {39    await requireAdmin(req)40    return presentKey(await keyById(parse(zId, req.params).id))41  })42  // Le jeton complet n'apparaît que dans cette réponse.43  app.post("/api/admin/api-keys", async (req, reply) => {44    const a = await requireAdminReauth(req)45    const b = parse(zKeyBody, req.body)46    const { row, token } = await createKey(b, a.userId)47    await audit(req, a.userId, "apikey.create", row.id, { name: row.name, scopes: row.scopes, addresses: row.address_ids.length, all_addresses: row.all_addresses })48    return reply.status(201).send({ key: presentKey(row), token })49  })50  app.patch("/api/admin/api-keys/:id", async (req) => {51    const a = await requireAdminReauth(req)52    const k = await keyById(parse(zId, req.params).id)53    const b = parse(zKeyBody.partial().strict(), req.body)54    // zod applique les valeurs par défaut même en mode partiel : seuls les champs réellement envoyés comptent.55    for (const f of Object.keys(b) as (keyof typeof b)[]) if (!(f in (req.body as object))) delete b[f]56    const merged = { scopes: b.scopes ?? k.scopes, all_addresses: b.all_addresses ?? k.all_addresses, address_ids: b.address_ids }57    await validateKeyInput(merged)58    const cols: Record<string, unknown> = { updated_at: new Date() }59    for (const f of ["name", "description", "scopes", "address_ids", "all_addresses", "rate_per_minute", "daily_send_limit", "external_send_policy", "allowed_recipient_domains"] as const) if (b[f] !== undefined) cols[f] = b[f]60    if (b.expires_at !== undefined) cols.expires_at = b.expires_at ? new Date(b.expires_at) : null61    const [row] = await sql`update api_keys set ${sql(cols as never)} where id = ${k.id} returning *`62    await audit(req, a.userId, "apikey.update", k.id, { fields: Object.keys(cols).filter((x) => x !== "updated_at") })63    return presentKey(row as KeyRow)64  })65  // Rotation : nouvelle clé (mêmes droits) dont le secret est rendu une fois ; l'ancienne est révoquée tout de suite ou après un délai de grâce.66  app.post("/api/admin/api-keys/:id/rotate", async (req, reply) => {67    const a = await requireAdminReauth(req)68    const k = await keyById(parse(zId, req.params).id)69    const { grace_seconds } = parse(z.object({ grace_seconds: z.number().int().min(0).max(7 * 86400).default(0) }).strict(), req.body ?? {})70    if (k.revoked_at && new Date(k.revoked_at).getTime() <= Date.now()) throw bad("key_revoked", 409, "A revoked key cannot be rotated")71    const { row, token } = await createKey({72      name: k.name, description: k.description, scopes: k.scopes, address_ids: k.address_ids, all_addresses: k.all_addresses, rate_per_minute: k.rate_per_minute,73      daily_send_limit: k.daily_send_limit, external_send_policy: k.external_send_policy, allowed_recipient_domains: k.allowed_recipient_domains,74      expires_at: k.expires_at ? new Date(k.expires_at).toISOString() : null,75    }, a.userId, k.id)76    await sql`update api_keys set revoked_at = now() + make_interval(secs => ${grace_seconds}), updated_at = now() where id = ${k.id}`77    await sql`update webhooks set key_id = ${row.id} where key_id = ${k.id}` // les webhooks de la clé suivent la rotation78    await audit(req, a.userId, "apikey.rotate", k.id, { new_key: row.id, grace_seconds })79    return reply.status(201).send({ key: presentKey(row), token, previous: presentKey(await keyById(k.id)) })80  })81  // Révocation immédiate : réduit des droits, donc sans réauthentification (doit rester possible en urgence).82  app.delete("/api/admin/api-keys/:id", async (req) => {83    const a = await requireAdmin(req)84    const k = await keyById(parse(zId, req.params).id)85    await sql`update api_keys set revoked_at = now(), updated_at = now() where id = ${k.id}`86    await sql`delete from explorer_tokens where key_id = ${k.id}`87    await audit(req, a.userId, "apikey.revoke", k.id, { name: k.name })88    return { ok: true, key: presentKey(await keyById(k.id)) }89  })90  app.get("/api/admin/api-keys/:id/usage", async (req) => {91    await requireAdmin(req)92    const k = await keyById(parse(zId, req.params).id)93    const { days } = parse(z.object({ days: z.coerce.number().int().min(1).max(90).default(7) }), req.query)94    const [byDay, byRoute, recent, sends] = await Promise.all([95      sql`select to_char(date_trunc('day', at at time zone 'utc'), 'YYYY-MM-DD') as day, count(*)::int as requests, count(*) filter (where status >= 400)::int as errors,96            count(*) filter (where explorer)::int as explorer from api_usage where key_id = ${k.id} and at > now() - make_interval(days => ${days}) group by 1 order by 1 desc`,97      sql`select method, route, count(*)::int as requests, count(*) filter (where status >= 400)::int as errors, round(avg(duration_ms))::int as avg_ms98            from api_usage where key_id = ${k.id} and at > now() - make_interval(days => ${days}) group by 1, 2 order by requests desc limit 50`,99      sql`select at, method, route, status, duration_ms, ip, error_code, explorer from api_usage where key_id = ${k.id} order by id desc limit 200`,100      sql`select status, count(*)::int as n from outbound_messages where key_id = ${k.id} and created_at > now() - make_interval(days => ${days}) group by 1`,101    ])102    return { key: presentKey(k), days, by_day: byDay, by_route: byRoute, sends: Object.fromEntries(sends.map((s) => [s.status, s.n])), recent }103  })104  // Jeton d'exploration : 10 minutes, exactement les droits de la clé, marqué « explorer » dans le journal d'usage.105  app.post("/api/admin/api-keys/:id/explorer-token", async (req, reply) => {106    const a = await requireAdmin(req)107    const k = await keyById(parse(zId, req.params).id)108    if (presentKey(k).state !== "active") throw bad("key_inactive", 409, "This key is revoked or expired")109    const t = await mintExplorerToken(k.id, a.userId)110    await audit(req, a.userId, "apikey.explorer-token", k.id)111    return reply.status(201).send({ ...t, key_id: k.id, purpose: "explorer" })112  })113114  // ---------------------------------------------------------------- approbations d'envois externes115  app.get("/api/admin/approvals", async (req) => {116    await requireAdmin(req)117    const { status } = parse(z.object({ status: z.enum(["pending", "approved", "rejected", "expired"]).default("pending") }), req.query)118    const rows = await sql`select a.*, k.name as key_name, o.from_address, o.mailbox_id, o.email_id, o.recipients, o.send_at, o.status as outbound_status119      from send_approvals a join outbound_messages o on o.id = a.outbound_id left join api_keys k on k.id = a.key_id where a.status = ${status} and (${status} <> 'pending' or a.expires_at > now()) order by a.created_at desc limit 200`120    return Promise.all(rows.map(async (r) => {121      // L'administrateur doit voir ce qu'il approuve : sujet et aperçu sont lus en direct dans le brouillon, jamais copiés en base.122      let subject: string | null = null, preview: string | null = null123      if (r.status === "pending") {124        const mb = await mailboxById(r.mailbox_id)125        const g = mb ? await jmapOk(mb, [["Email/get", { ids: [r.email_id], properties: ["subject", "preview"] }]]).catch(() => null) : null126        subject = g?.[0]?.list?.[0]?.subject ?? null127        preview = g?.[0]?.list?.[0]?.preview ?? null128      }129      return {130        id: r.id, status: r.status, outbound_id: r.outbound_id, outbound_status: r.outbound_status, key_id: r.key_id, key_name: r.key_name, from: r.from_address,131        recipients: (r.recipients as { address: string }[]).map((x) => x.address), external_recipients: r.external_recipients, subject, preview,132        send_at: r.send_at, created_at: r.created_at, expires_at: r.expires_at, decided_at: r.decided_at,133      }134    }))135  })136  const decide = async (id: string, userId: string, status: "approved" | "rejected") => {137    const [a] = await sql`update send_approvals set status = ${status}, decided_by = ${userId}, decided_at = now() where id = ${id} and status = 'pending' and expires_at > now() returning outbound_id`138    if (!a) throw bad("not_pending", 409, "This approval is no longer pending")139    const o = await outboundById(a.outbound_id)140    if (!o) throw bad("not_found", 404)141    return o142  }143  app.post("/api/admin/approvals/:id/approve", async (req) => {144    const a = await requireAdminReauth(req)145    const { id } = parse(zId, req.params)146    let o = await decide(id, a.userId, "approved")147    const later = o.send_at && new Date(o.send_at).getTime() > Date.now() + 1000148    const [row] = await sql`update outbound_messages set status = ${later ? "scheduled" : "queued"}, next_check_at = ${later ? o.send_at : new Date()}, updated_at = now(),149      locked_until = ${later ? null : new Date(Date.now() + 120_000)},150      recipients = (select coalesce(jsonb_agg(jsonb_set(x, '{status}', to_jsonb(${later ? "scheduled" : "queued"}::text))), '[]'::jsonb) from jsonb_array_elements(recipients) x)151      where id = ${o.id} and status = 'pending_approval' returning *`152    if (!row) throw bad("not_pending", 409, "This message is no longer pending")153    o = row as unknown as OutboundRow154    if (!later) o = await submitOutbound(o) // l'envoi approuvé part tout de suite ; le message sortant porte le lien155    await audit(req, a.userId, "approval.approve", id, { outbound: o.id })156    return { ok: true, approval_id: id, outbound: presentOutbound(o) }157  })158  app.post("/api/admin/approvals/:id/reject", async (req) => {159    const a = await requireAdmin(req)160    const { id } = parse(zId, req.params)161    const o = await decide(id, a.userId, "rejected")162    const c = await cancelOutbound(o, "rejected by an administrator")163    await audit(req, a.userId, "approval.reject", id, { outbound: o.id })164    return { ok: true, approval_id: id, outbound: presentOutbound(c) }165  })166167  // ---------------------------------------------------------------- destinations internes permises aux webhooks168  app.get("/api/admin/webhook-allowlist", async (req) => {169    await requireAdmin(req)170    return sql`select host_port, note, created_at from webhook_internal_allowlist order by created_at`171  })172  app.post("/api/admin/webhook-allowlist", async (req, reply) => {173    const a = await requireAdminReauth(req)174    const b = parse(z.object({ host_port: z.string().trim().toLowerCase().regex(/^(\[[0-9a-f:]+\]|[a-z0-9.-]{1,253}):\d{1,5}$/), note: z.string().max(200).default("") }).strict(), req.body)175    const hp = b.host_port.replace(/^\[|\](?=:\d+$)/g, "")176    await sql`insert into webhook_internal_allowlist (host_port, note, created_by) values (${hp}, ${b.note}, ${a.userId}) on conflict (host_port) do update set note = excluded.note`177    await audit(req, a.userId, "webhook.allowlist.add", hp)178    return reply.status(201).send({ ok: true, host_port: hp })179  })180  app.delete("/api/admin/webhook-allowlist", async (req) => {181    const a = await requireAdminReauth(req)182    const { host_port } = parse(z.object({ host_port: z.string().max(300) }), req.query)183    const r = await sql`delete from webhook_internal_allowlist where host_port = ${host_port.toLowerCase()} returning 1`184    if (!r.length) throw bad("not_found", 404)185    await audit(req, a.userId, "webhook.allowlist.remove", host_port)186    return { ok: true }187  })188189  // ---------------------------------------------------------------- messages programmés190  app.get("/api/admin/scheduled", async (req) => {191    await requireAdmin(req)192    return ((await sql`select * from outbound_messages where status = 'scheduled' order by send_at limit 500`) as unknown as OutboundRow[]).map((o) => presentOutbound(o, { key_id: o.key_id }))193  })194  app.delete("/api/admin/scheduled/:id", async (req) => {195    const a = await requireAdmin(req)196    const { id } = parse(z.object({ id: z.string().regex(/^msg_out_[A-Za-z0-9_-]{10,40}$/) }), req.params)197    const o = await outboundById(id)198    if (!o) throw bad("not_found", 404)199    if (o.status !== "scheduled") throw bad("not_cancellable", 409)200    const c = await cancelOutbound(o, "cancelled by an administrator")201    await audit(req, a.userId, "scheduled.cancel", id)202    return { ok: true, outbound: presentOutbound(c) }203  })204205  // ---------------------------------------------------------------- métriques de remise206  app.get("/api/admin/metrics", async (req) => {207    await requireAdmin(req)208    const { days } = parse(z.object({ days: z.coerce.number().int().min(1).max(90).default(14) }), req.query)209    const [byDay, byAddress, queue, hooks, approvals] = await Promise.all([210      sql`select to_char(date_trunc('day', created_at at time zone 'utc'), 'YYYY-MM-DD') as day, status, count(*)::int as n from outbound_messages211            where created_at > now() - make_interval(days => ${days}) group by 1, 2 order by 1 desc, 2`,212      sql`select from_address as address, status, count(*)::int as n from outbound_messages where created_at > now() - make_interval(days => ${days}) group by 1, 2 order by 1, 2`,213      sql`select status, count(*)::int as n, min(created_at) as oldest from outbound_messages where status in ('queued','scheduled','pending_approval','sent','deferred') group by 1`,214      sql`select status, count(*)::int as n, min(created_at) as oldest from webhook_deliveries where status in ('pending','retrying') or (status = 'failed' and created_at > now() - interval '7 days') group by 1`,215      sql`select count(*)::int as n from send_approvals where status = 'pending' and expires_at > now()`,216    ])217    const fold = (rows: Record<string, any>[], k: string) => {218      const out: Record<string, Record<string, number>> = {}219      for (const r of rows) (out[r[k]] ??= {})[r.status] = r.n220      return Object.entries(out).map(([key, statuses]) => ({ [k]: key, ...statuses }))221    }222    return {223      days, by_day: fold(byDay, "day"), by_address: fold(byAddress, "address"),224      queue_depth: Object.fromEntries(queue.map((q) => [q.status, { count: q.n, oldest: q.oldest }])),225      webhook_backlog: Object.fromEntries(hooks.map((h) => [h.status, { count: h.n, oldest: h.oldest }])),226      pending_approvals: approvals[0].n,227    }228  })229230  // ---------------------------------------------------------------- boîtes partagées231  app.get("/api/admin/mailboxes/:id/grants", async (req) => {232    await requireAdmin(req)233    const { id } = parse(zId, req.params)234    return sql`select g.user_id, u.handle, g.can_read, g.can_send, g.created_at from mailbox_grants g join users u on u.id = g.user_id where g.mailbox_id = ${id} order by u.handle`235  })236  app.put("/api/admin/mailboxes/:id/grants", async (req) => {237    const a = await requireAdminReauth(req)238    const { id } = parse(zId, req.params)239    const { grants } = parse(z.object({ grants: z.array(z.object({ user_id: zUuid, can_read: z.boolean().default(true), can_send: z.boolean().default(false) }).strict()).max(100) }).strict(), req.body)240    const [mb] = await sql`select user_id, address from mailboxes where id = ${id}`241    if (!mb) throw bad("not_found", 404)242    const wanted = grants.filter((g) => g.user_id !== mb.user_id && (g.can_read || g.can_send))243    if (wanted.length) {244      const found = await sql`select id from users where id = any(${wanted.map((g) => g.user_id)}::uuid[])`245      if (found.length !== new Set(wanted.map((g) => g.user_id)).size) throw bad("unknown_user", 400)246    }247    await sql.begin(async (tx) => {248      await tx`delete from mailbox_grants where mailbox_id = ${id}`249      for (const g of wanted) await tx`insert into mailbox_grants (user_id, mailbox_id, can_read, can_send) values (${g.user_id}, ${id}, ${g.can_read}, ${g.can_send})`250      // Une boîte partagée est étiquetée « shared » ; elle redevient « mailbox » quand plus personne ne la partage.251      await tx`update addresses set kind = ${wanted.length ? "shared" : "mailbox"}, updated_at = now() where address = ${mb.address} and kind in ('mailbox','shared')`252    })253    await audit(req, a.userId, "mailbox.grants", mb.address, { users: wanted.length })254    return { ok: true, grants: wanted }255  })256257  // Passage immédiat de la conservation (sinon une fois par 24 h) ; ne touche que les boîtes qui ont une durée définie.258  app.post("/api/admin/retention/run", async (req) => {259    const a = await requireAdminReauth(req)260    const report = await retention(true)261    await audit(req, a.userId, "retention.run-now", null, { mailboxes: report.length })262    return { ok: true, report }263  })264265  app.post("/api/admin/addresses/sync", async (req) => {266    const a = await requireAdmin(req)267    const r = await syncAddresses()268    await audit(req, a.userId, "addresses.sync", null, { created: r.created.length })269    return r270  })271}272
Files main
Menu

Theme