Repository Public
1// Événements et webhooks : file de livraison persistante (PostgreSQL), signature HMAC, garde SSRF revérifiée à chaque livraison.2import crypto from "node:crypto"3import dns from "node:dns/promises"4import http from "node:http"5import https from "node:https"6import net from "node:net"7import { config } from "./config.js"8import { sql } from "./db.js"9import { isPrivate } from "./images.js"10import { seal, unseal } from "./stalwart.js"11import { bad } from "./util.js"1213export const EVENT_TYPES = [14 "message.received", "message.sent", "message.delivered", "message.deferred", "message.bounced", "message.failed", "message.read", "message.deleted",15 "draft.created", "address.created", "address.suspended", "rule.matched",16] as const17export type EventType = (typeof EVENT_TYPES)[number]1819export const newWebhookSecret = () => `whsec_${crypto.randomBytes(32).toString("base64url")}`20export const sealSecret = (s: string) => seal(s)2122/** En-tête `SPMail-Signature: t=<unix>,v1=<hex hmac-sha256(secret, t + "." + corps brut)>`. */23export function signPayload(secret: string, body: string, t = Math.floor(Date.now() / 1000)): string {24 return `t=${t},v1=${crypto.createHmac("sha256", secret).update(`${t}.${body}`).digest("hex")}`25}26/** Vérification côté récepteur (référence, utilisée par les tests) : signature exacte et horodatage dans la fenêtre de 5 minutes. */27export function verifySignature(secret: string, header: string, body: string, toleranceSec = 300, now = Math.floor(Date.now() / 1000)): boolean {28 const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header)29 if (!m) return false30 if (Math.abs(now - Number(m[1])) > toleranceSec) return false31 const expected = crypto.createHmac("sha256", secret).update(`${m[1]}.${body}`).digest()32 const given = Buffer.from(m[2], "hex")33 return given.length === expected.length && crypto.timingSafeEqual(given, expected)34}3536// ------------------------------------------------------------------ garde SSRF37export type Destination = { url: URL; address: string; family: number; allowlisted: boolean }38/**39 * Destination d'un webhook : https public (port 443) dont TOUTES les adresses résolues sont publiques, ou hôte:port explicitement40 * permis par un administrateur. L'adresse rendue est celle à laquelle la connexion sera épinglée (pas de seconde résolution DNS).41 */42export async function checkWebhookUrl(raw: string): Promise<Destination> {43 let u: URL44 try { u = new URL(raw) } catch { throw bad("invalid_url", 400, "Invalid webhook URL") }45 if (u.protocol !== "https:" && u.protocol !== "http:") throw bad("invalid_url", 400, "Webhook URLs must use https")46 if (u.username || u.password) throw bad("invalid_url", 400, "Credentials in webhook URLs are not allowed")47 if (/sp[mx]_[a-z0-9]/i.test(raw)) throw bad("invalid_url", 400, "API tokens must never be placed in a URL")48 const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase()49 const port = u.port || (u.protocol === "https:" ? "443" : "80")50 const [allowed] = await sql`select 1 from webhook_internal_allowlist where host_port = ${`${host}:${port}`}`51 const addrs = net.isIP(host) ? [{ address: host, family: net.isIP(host) }] : await dns.lookup(host, { all: true }).catch(() => [])52 if (!addrs.length) throw bad("forbidden_destination", 403, "The webhook host does not resolve")53 if (allowed) return { url: u, address: addrs[0].address, family: addrs[0].family, allowlisted: true }54 if (u.protocol !== "https:" || port !== "443") throw bad("forbidden_destination", 403, "Webhook URLs must be https on port 443 (or an allowlisted internal host:port)")55 if (addrs.some((a) => isPrivate(a.address))) throw bad("forbidden_destination", 403, "The webhook host resolves to a private or local address")56 return { url: u, address: addrs[0].address, family: addrs[0].family, allowlisted: false }57}5859export type HttpResult = { status: number; error?: string }60/** POST sans suivi de redirection, connexion épinglée à l'adresse vérifiée, délai 10 s, corps de réponse ignoré (lecture plafonnée). */61export function postPinned(dest: Destination, body: string, headers: Record<string, string>, timeoutMs = 10_000): Promise<HttpResult> {62 return new Promise((resolve) => {63 const lib = dest.url.protocol === "https:" ? https : http64 let done = false65 const finish = (r: HttpResult) => { if (!done) { done = true; resolve(r) } }66 const req = lib.request({67 agent: false, method: "POST", host: dest.url.hostname.replace(/^\[|\]$/g, ""), port: dest.url.port || (dest.url.protocol === "https:" ? 443 : 80),68 path: dest.url.pathname + dest.url.search, headers: { ...headers, connection: "close", "content-length": Buffer.byteLength(body).toString() }, timeout: timeoutMs,69 servername: net.isIP(dest.url.hostname) ? undefined : dest.url.hostname,70 lookup: ((_h: string, opts: { all?: boolean }, cb: (...a: unknown[]) => void) =>71 opts?.all ? cb(null, [{ address: dest.address, family: dest.family }]) : cb(null, dest.address, dest.family)) as never,72 }, (res) => {73 let read = 074 res.on("data", (c: Buffer) => { read += c.length; if (read > 65536) res.destroy() })75 res.on("end", () => finish({ status: res.statusCode ?? 0 }))76 res.on("close", () => finish({ status: res.statusCode ?? 0 }))77 res.on("error", () => finish({ status: res.statusCode ?? 0 }))78 })79 req.on("timeout", () => { req.destroy(); finish({ status: 0, error: "timeout" }) })80 req.on("error", (e) => finish({ status: 0, error: String((e as NodeJS.ErrnoException).code ?? e.message).slice(0, 120) }))81 req.end(body)82 })83}8485// ------------------------------------------------------------------ émission86export type EventInput = { type: EventType | "webhook.test"; addressId?: string | null; address?: string | null; mailboxId?: string | null; data: Record<string, unknown>; content?: Record<string, unknown> | null }87type Q = typeof sql8889/** Une clé ne reçoit que les événements des adresses qu'elle peut voir : adresse dans sa liste, ou adresse principale de la boîte dans sa liste. */90function keyMaySee(k: { scopes: string[]; address_ids: string[]; all_addresses: boolean; revoked_at: Date | null; expires_at: Date | null }, addressId: string | null, primaryId: string | null): boolean {91 if (k.revoked_at && new Date(k.revoked_at).getTime() <= Date.now()) return false92 if (k.expires_at && new Date(k.expires_at).getTime() <= Date.now()) return false93 if (k.all_addresses && k.scopes.includes("mail.admin")) return true94 return (!!addressId && k.address_ids.includes(addressId)) || (!!primaryId && k.address_ids.includes(primaryId))95}9697/** Enregistre un événement et crée une livraison par webhook actif concerné. À appeler dans la même transaction que le changement d'état. */98export async function emitEvent(e: EventInput, q: Q = sql, onlyWebhookId?: string): Promise<string> {99 const id = `evt_${crypto.randomBytes(12).toString("base64url")}`100 let addressId = e.addressId ?? null101 let mailboxId = e.mailboxId ?? null102 if (!addressId && e.address) {103 const [a] = await q`select id, mailbox_id from addresses where address = ${e.address.toLowerCase()}`104 if (a) { addressId = a.id; mailboxId = mailboxId ?? a.mailbox_id }105 }106 let primaryId: string | null = null107 let mailboxAddress: string | null = null108 if (mailboxId) {109 const [m] = await q`select m.address, a.id from mailboxes m left join addresses a on a.address = m.address where m.id = ${mailboxId}`110 primaryId = m?.id ?? null111 mailboxAddress = m?.address ?? null112 }113 const payload = { id, type: e.type, occurred_at: new Date().toISOString(), address: e.address ?? null, mailbox: mailboxAddress, data: e.data }114 await q`insert into webhook_events (id, type, address_id, address, mailbox_id, payload, content)115 values (${id}, ${e.type}, ${addressId}, ${e.address ?? null}, ${mailboxId}, ${q.json(payload as never)}, ${e.content ? q.json(e.content as never) : null})`116 const hooks = onlyWebhookId117 ? await q`select w.id, w.key_id, w.address_ids from webhooks w where w.id = ${onlyWebhookId}`118 : await q`select w.id, w.key_id, w.address_ids from webhooks w where w.active and ${e.type} = any(w.events)`119 for (const w of hooks) {120 if (!onlyWebhookId) {121 if (w.address_ids.length && !(addressId && w.address_ids.includes(addressId))) continue122 if (w.key_id) {123 const [k] = await q`select scopes, address_ids, all_addresses, revoked_at, expires_at from api_keys where id = ${w.key_id}`124 if (!k || !keyMaySee(k as never, addressId, primaryId)) continue125 }126 }127 await q`insert into webhook_deliveries (event_id, webhook_id, status, next_attempt_at) values (${id}, ${w.id}, 'pending', now())`128 }129 return id130}131132// ------------------------------------------------------------------ livraison133/** Tente une livraison. Rend l'état final de la tentative ; la ligne est mise à jour (succès, nouvelle tentative planifiée, ou échec définitif). */134export async function attemptDelivery(deliveryId: string): Promise<{ status: string; http_status: number | null; error: string | null; attempt: number }> {135 const [d] = await sql`select d.id, d.attempt, d.event_id, w.id as webhook_id, w.url, w.secret_enc, w.include_content, e.payload, e.content, e.type136 from webhook_deliveries d join webhooks w on w.id = d.webhook_id join webhook_events e on e.id = d.event_id where d.id = ${deliveryId}`137 if (!d) throw bad("not_found", 404)138 const attempt = Number(d.attempt) + 1139 const payload = { ...(d.payload as Record<string, unknown>) }140 if (d.include_content && d.content) payload.data = { ...(payload.data as object), ...(d.content as object) }141 const body = JSON.stringify(payload)142 let result: HttpResult143 try {144 const dest = await checkWebhookUrl(d.url) // revérifié à chaque tentative (le DNS a pu changer)145 result = await postPinned(dest, body, {146 "content-type": "application/json", "user-agent": "SPMail-Webhooks/1", "spmail-signature": signPayload(unseal(Buffer.from(d.secret_enc)), body),147 "spmail-event-id": d.event_id, "spmail-event-type": d.type, "spmail-delivery-attempt": String(attempt),148 })149 } catch (e) {150 result = { status: 0, error: String((e as { code?: string }).code ?? (e as Error).message).slice(0, 120) }151 }152 const ok = result.status >= 200 && result.status < 300153 const error = ok ? null : result.error ?? (result.status >= 300 && result.status < 400 ? "redirect_not_followed" : `http_${result.status}`)154 if (ok) {155 await sql`update webhook_deliveries set attempt = ${attempt}, status = 'delivered', last_status = ${result.status}, last_error = null, delivered_at = now(), next_attempt_at = null, locked_until = null where id = ${d.id}`156 return { status: "delivered", http_status: result.status, error: null, attempt }157 }158 const delay = config.webhookBackoff[attempt - 1]159 if (delay === undefined) {160 await sql`update webhook_deliveries set attempt = ${attempt}, status = 'failed', last_status = ${result.status || null}, last_error = ${error}, next_attempt_at = null, locked_until = null where id = ${d.id}`161 return { status: "failed", http_status: result.status || null, error, attempt }162 }163 await sql`update webhook_deliveries set attempt = ${attempt}, status = 'retrying', last_status = ${result.status || null}, last_error = ${error},164 next_attempt_at = now() + make_interval(secs => ${delay}), locked_until = null where id = ${d.id}`165 return { status: "retrying", http_status: result.status || null, error, attempt }166}167