Repository Public
1// Administration : boîtes, alias, santé du serveur de courrier, DNS, file d'attente, audit. Réservé au rôle admin.2import type { FastifyInstance } from "fastify"3import dns from "node:dns/promises"4import fs from "node:fs"5import { z } from "zod"6import { config } from "./config.js"7import { sql } from "./db.js"8import { requireAdmin, requireUser } from "./session.js"9import { adminCall, createAccount, destroyAccount, getAll, listDomains, rotateSecret, seal, setAliases } from "./stalwart.js"10import { audit, bad, parse, zUuid } from "./util.js"11import { reconcileMailbox, syncAddresses } from "./addresses.js"1213const zAddress = z.string().trim().toLowerCase().regex(/^[a-z0-9][a-z0-9._+-]{0,63}@[a-z0-9.-]{3,253}$/)1415async function txt(name: string): Promise<string[]> {16 return (await dns.resolveTxt(name).catch(() => [])).map((c) => c.join(""))17}18/** État DNS réel d'un domaine, lu en direct (aucune valeur supposée). */19export async function dnsReport(domain: string) {20 const [mx, spf, dmarc, mxA, ptr] = await Promise.all([21 dns.resolveMx(domain).catch(() => []),22 txt(domain).then((t) => t.filter((x) => x.toLowerCase().startsWith("v=spf1"))),23 txt(`_dmarc.${domain}`),24 dns.resolve4(config.mxHost).catch((): string[] => []),25 dns.reverse(config.mxIp).catch((): string[] => []),26 ])27 const sigs = (await getAll("DkimSignature").catch(() => [])) as { selector?: string; domainId?: string }[]28 const doms = await listDomains().catch(() => [])29 const dom = doms.find((d) => d.name === domain)30 const dkim = await Promise.all(31 sigs.filter((s) => s.domainId === dom?.id && s.selector).map(async (s) => ({ selector: s.selector!, published: (await txt(`${s.selector}._domainkey.${domain}`)).some((t) => t.includes("v=DKIM1")) })),32 )33 const mxOk = mx.some((m) => m.exchange.toLowerCase() === config.mxHost)34 return {35 domain,36 mx: { records: mx.map((m) => `${m.priority} ${m.exchange}`), ok: mxOk },37 spf: { records: spf, ok: spf.length === 1 && (spf[0].includes(config.mxIp) || /\bmx\b/.test(spf[0])) },38 dkim: { selectors: dkim, ok: dkim.length > 0 && dkim.every((d) => d.published) },39 dmarc: { records: dmarc, ok: dmarc.some((d) => d.startsWith("v=DMARC1")) },40 mxHost: { host: config.mxHost, a: mxA, ok: mxA.includes(config.mxIp) },41 ptr: { ip: config.mxIp, names: ptr, ok: ptr.some((p) => p.toLowerCase() === config.mxHost) },42 }43}4445export function adminRoutes(app: FastifyInstance) {46 app.get("/api/admin/overview", async (req) => {47 await requireAdmin(req)48 const t0 = Date.now()49 let server: Record<string, unknown> = { reachable: false }50 let domains: { id: string; name: string; enable: boolean }[] = []51 let accounts: Record<string, any>[] = []52 let queue: Record<string, any>[] = []53 let certs: Record<string, any>[] = []54 try {55 domains = await listDomains()56 server = { reachable: true, latency_ms: Date.now() - t0 }57 ;[accounts, queue, certs] = await Promise.all([58 getAll("Account", ["name", "emailAddress", "usedDiskQuota", "aliases", "description", "createdAt"]),59 getAll("QueuedMessage").catch(() => []),60 getAll("Certificate", ["subjectAlternativeNames", "notValidAfter", "issuer"]).catch(() => []),61 ])62 } catch (e) {63 server = { reachable: false, error: (e as Error).message }64 }65 let backup: unknown = null66 if (config.backupStatusFile) backup = await fs.promises.readFile(config.backupStatusFile, "utf8").then(JSON.parse).catch(() => null)67 const [counts] = await sql`select (select count(*)::int from users) as users, (select count(*)::int from mailboxes) as mailboxes, (select count(*)::int from sessions where revoked_at is null and expires_at > now()) as sessions`68 return {69 server, domains, counts, backup, certificates: certs,70 accounts: accounts.map((a) => ({ id: a.id, address: a.emailAddress, description: a.description, used_bytes: a.usedDiskQuota, aliases: Object.values(a.aliases ?? {}) })),71 // File d'attente : enveloppes seulement (expéditeur, destinataires, état), jamais le contenu.72 queue: queue.map((q) => ({ id: q.id, from: q.returnPath ?? q.from, recipients: q.recipients, created: q.createdAt ?? q.created, next_retry: q.nextRetry, size: q.size })).slice(0, 200),73 }74 })7576 app.get("/api/admin/dns", async (req) => {77 await requireAdmin(req)78 const domains = await listDomains()79 return Promise.all(domains.map((d) => dnsReport(d.name)))80 })8182 app.get("/api/usage", async (req) => {83 // Espace utilisé par les boîtes de l'utilisateur courant (lu côté gestion : Quota/get est vide sans quota défini).84 const a = await requireUser(req)85 const boxes = await sql`select id, address, stalwart_id from mailboxes where user_id = ${a.userId}`86 const accts = await getAll("Account", ["usedDiskQuota"]).catch(() => [])87 return boxes.map((b) => ({ id: b.id, address: b.address, used_bytes: accts.find((x) => x.id === b.stalwart_id)?.usedDiskQuota ?? null }))88 })8990 app.get("/api/admin/users", async (req) => {91 await requireAdmin(req)92 const users = await sql`select u.id, u.handle, u.display_name, u.role, u.status, u.created_at,93 (select count(*)::int from passkeys p where p.user_id = u.id) as passkeys from users u order by u.created_at`94 const boxes = await sql`select id, user_id, address, display_name, stalwart_id, created_at from mailboxes order by position, created_at`95 return users.map((u) => ({ ...u, mailboxes: boxes.filter((b) => b.user_id === u.id) }))96 })9798 // Crée la boîte dans Stalwart (refus si l'adresse existe déjà) et la rattache à un utilisateur SP Mail.99 app.post("/api/admin/mailboxes", async (req) => {100 const a = await requireAdmin(req)101 const b = parse(z.object({ address: zAddress, display_name: z.string().trim().max(80).default(""), user_id: zUuid.optional() }), req.body)102 const userId = b.user_id ?? a.userId103 const [dup] = await sql`select 1 from mailboxes where address = ${b.address}`104 if (dup) throw bad("address_taken", 409)105 const acct = await createAccount(b.address, b.display_name || b.address)106 try {107 const [{ n }] = await sql`select count(*)::int as n from mailboxes where user_id = ${userId}`108 const [row] = await sql`insert into mailboxes (user_id, address, display_name, stalwart_id, secret_enc, position)109 values (${userId}, ${b.address}, ${b.display_name}, ${acct.id}, ${seal(acct.secret)}, ${n}) returning id`110 await syncAddresses(row.id) // l'adresse de première classe correspondante111 await audit(req, a.userId, "mailbox.create", b.address, { user: userId })112 return { id: row.id, address: b.address }113 } catch (e) {114 await destroyAccount(acct.id).catch(() => {}) // pas de compte orphelin si l'enregistrement échoue115 throw e116 }117 })118119 // Adopte un compte Stalwart existant (créé hors SP Mail) : son mot de passe est remplacé par un secret connu de SP Mail seul.120 app.post("/api/admin/mailboxes/adopt", async (req) => {121 const a = await requireAdmin(req)122 const b = parse(z.object({ address: zAddress, display_name: z.string().trim().max(80).default(""), user_id: zUuid.optional() }), req.body)123 const acct = (await getAll("Account", ["emailAddress"])).find((x) => x.emailAddress === b.address)124 if (!acct) throw bad("not_found", 404)125 const secret = await rotateSecret(acct.id)126 const userId = b.user_id ?? a.userId127 const [row] = await sql`insert into mailboxes (user_id, address, display_name, stalwart_id, secret_enc)128 values (${userId}, ${b.address}, ${b.display_name}, ${acct.id}, ${seal(secret)})129 on conflict (address) do update set secret_enc = excluded.secret_enc, user_id = excluded.user_id returning id`130 await syncAddresses(row.id)131 await audit(req, a.userId, "mailbox.adopt", b.address, { user: userId })132 return { id: row.id, address: b.address }133 })134135 app.put("/api/admin/mailboxes/:id/aliases", async (req) => {136 const a = await requireAdmin(req)137 const { id } = parse(z.object({ id: zUuid }), req.params)138 const { aliases } = parse(z.object({ aliases: z.array(zAddress).max(50) }), req.body)139 const [mb] = await sql`select address, stalwart_id from mailboxes where id = ${id}`140 if (!mb) throw bad("not_found", 404)141 // Un alias protégé (postmaster, abuse…) ne peut pas être retiré, par aucune API.142 const [gone] = await sql`select address from addresses where mailbox_id = ${id} and protected and address <> ${mb.address} and not (address = any(${aliases}))`143 if (gone) throw bad("protected_address", 403, `${gone.address} is protected and cannot be removed`)144 await setAliases(mb.stalwart_id, aliases)145 // La table des adresses suit : alias retirés supprimés, nouveaux alias ajoutés, puis les états (suspension…) réappliqués.146 await sql`delete from addresses where mailbox_id = ${id} and address <> ${mb.address} and kind not in ('mailbox','shared') and stalwart_list_id is null and not (address = any(${aliases}))`147 await syncAddresses(id)148 await reconcileMailbox(id)149 await audit(req, a.userId, "mailbox.aliases", mb.address, { aliases })150 return { ok: true }151 })152153 // Détache la boîte de SP Mail. Le compte Stalwart et son courrier ne sont supprimés que sur demande explicite.154 app.delete("/api/admin/mailboxes/:id", async (req) => {155 const a = await requireAdmin(req)156 const { id } = parse(z.object({ id: zUuid }), req.params)157 const { purge } = parse(z.object({ purge: z.literal("delete-all-mail").optional() }), req.query)158 const [mb] = await sql`select address, stalwart_id from mailboxes where id = ${id}`159 if (!mb) throw bad("not_found", 404)160 const [prot] = await sql`select address from addresses where mailbox_id = ${id} and protected limit 1`161 if (prot) throw bad("protected_address", 403, `${prot.address} is protected: this mailbox cannot be deleted`)162 const lists = purge ? await sql`select stalwart_list_id from addresses where mailbox_id = ${id} and stalwart_list_id is not null` : []163 for (const l of lists) await adminCall([["x:MailingList/set", { destroy: [l.stalwart_list_id] }, "d"]]).catch(() => {})164 // Le compte de courrier est détruit AVANT le détachement : si le serveur de courrier est injoignable, rien n'est perdu de vue.165 if (purge) await destroyAccount(mb.stalwart_id)166 await sql`delete from mailboxes where id = ${id}`167 await audit(req, a.userId, purge ? "mailbox.purge" : "mailbox.detach", mb.address)168 return { ok: true, purged: !!purge }169 })170171 app.post("/api/admin/queue/:id/retry", async (req) => {172 const a = await requireAdmin(req)173 const { id } = req.params as { id: string }174 await adminCall([["x:QueuedMessage/set", { update: { [id]: { nextRetry: new Date().toISOString() } } }, "r"]]).catch(() => { throw bad("mail_server_error", 502) })175 await audit(req, a.userId, "queue.retry", id)176 return { ok: true }177 })178179 app.get("/api/admin/audit", async (req) => {180 await requireAdmin(req)181 return sql`select l.id, l.at, l.action, l.target, l.meta, l.ip, u.handle as actor from audit_log l left join users u on u.id = l.actor order by l.id desc limit 300`182 })183}184