SPB Git

Repository Public

webhooks.ts 12.7 KB 167 lines typescript

1// /api/v1 — webhooks (CRUD, livraisons, test, rejeu) et événements récents.2import { z } from "zod"3import { sql } from "../db.js"4import { hasScope, type Principal } from "../keys.js"5import { requireReauth } from "../reauth.js"6import { attemptDelivery, checkWebhookUrl, emitEvent, EVENT_TYPES, newWebhookSecret, sealSecret } from "../webhooks.js"7import { bad } from "../util.js"8import { accessMap } from "./context.js"9import { decodeCursor, encodeCursor } from "./ids.js"10import { zOk } from "./messages.js"11import { route } from "./registry.js"1213const zEvents = z.array(z.enum(EVENT_TYPES)).min(1).max(EVENT_TYPES.length)14const zWebhook = z.object({15  id: z.string(), name: z.string(), url: z.string(), events: z.array(z.string()), address_ids: z.array(z.string()), include_content: z.boolean(), active: z.boolean(),16  owner: z.enum(["key", "admin"]), key_id: z.string().nullable(), created_at: z.string(), updated_at: z.string(), secret: z.string().optional().describe("Only present at creation and after a secret rotation; never shown again"),17})18const zDelivery = z.object({19  id: z.string(), webhook_id: z.string(), event_id: z.string(), event_type: z.string(), status: z.enum(["pending", "retrying", "delivered", "failed"]), attempt: z.number(),20  next_attempt_at: z.string().nullable(), last_status: z.number().nullable(), last_error: z.string().nullable(), delivered_at: z.string().nullable(), created_at: z.string(),21})22type W = Record<string, any>23const iso = (d: Date | null | undefined) => (d ? new Date(d).toISOString() : null)24const present = (w: W, secret?: string) => ({25  id: w.id, name: w.name, url: w.url, events: w.events, address_ids: w.address_ids, include_content: w.include_content, active: w.active,26  owner: w.key_id ? ("key" as const) : ("admin" as const), key_id: w.key_id ?? null, created_at: iso(w.created_at)!, updated_at: iso(w.updated_at)!, ...(secret ? { secret } : {}),27})28const presentDelivery = (d: W) => ({29  id: d.id, webhook_id: d.webhook_id, event_id: d.event_id, event_type: d.type, status: d.status, attempt: d.attempt, next_attempt_at: iso(d.next_attempt_at),30  last_status: d.last_status ?? null, last_error: d.last_error ?? null, delivered_at: iso(d.delivered_at), created_at: iso(d.created_at)!,31})3233function assertManager(p: Principal) {34  if (p.type === "user" && p.role !== "admin") throw bad("admin_required", 403, "Webhooks are managed by administrators or by keys holding mail.webhooks.manage")35}36/** Une clé ne voit que ses propres webhooks ; une session d'administrateur les voit tous. */37async function owned(p: Principal, id: string): Promise<W> {38  assertManager(p)39  if (!/^[0-9a-f-]{36}$/.test(id)) throw bad("not_found", 404, "Unknown webhook")40  const [w] = p.type === "key" ? await sql`select * from webhooks where id = ${id} and key_id = ${p.keyId}` : await sql`select * from webhooks where id = ${id}`41  if (!w) throw bad("not_found", 404, "Unknown webhook")42  return w43}44async function checkFilter(p: Principal, ids: string[] | undefined, includeContent: boolean | undefined) {45  if (includeContent && !hasScope(p, "mail.read")) throw bad("insufficient_scope", 403, "include_content requires the mail.read scope")46  if (!ids?.length) return47  if (p.type === "key" && !(p.allAddresses && p.scopes.has("mail.admin"))) {48    const mine = new Set([...(await accessMap(p)).values()].flatMap((a) => a.addresses.map((x) => x.id)))49    if (ids.some((i) => !mine.has(i))) throw bad("address_not_allowed", 403, "address_ids contains an address outside this key's allowlist")50  } else {51    const found = await sql`select id from addresses where id = any(${ids}::uuid[])`52    if (found.length !== new Set(ids).size) throw bad("unknown_address", 400, "address_ids contains an unknown address")53  }54}55const zUrl = z.string().max(2000)56const zCreate = z.object({ name: z.string().trim().min(1).max(80), url: zUrl, events: zEvents, address_ids: z.array(z.string().uuid()).max(200).default([]), include_content: z.boolean().default(false), active: z.boolean().default(true) }).strict()57const zIdP = z.object({ id: z.string().max(60) })5859route({60  method: "GET", path: "/webhooks", tag: "Webhooks", summary: "List webhooks", scopes: ["mail.webhooks.manage"], response: z.object({ data: z.array(zWebhook) }),61  handler: async ({ principal }) => {62    assertManager(principal)63    const rows = principal.type === "key" ? await sql`select * from webhooks where key_id = ${principal.keyId} order by created_at` : await sql`select * from webhooks order by created_at`64    return { data: rows.map((w) => present(w)) }65  },66})67route({68  method: "POST", path: "/webhooks", tag: "Webhooks", summary: "Create a webhook (the signing secret is returned once)", scopes: ["mail.webhooks.manage"], idempotent: true, status: 201,69  description: "The URL must be https on port 443 and resolve only to public addresses, unless its host:port is in the administrator-managed internal allowlist. Redirects are never followed. A key-owned webhook only receives events for addresses the key can see.",70  body: zCreate, response: zWebhook,71  handler: async ({ principal, body }) => {72    assertManager(principal)73    await checkWebhookUrl(body.url)74    await checkFilter(principal, body.address_ids, body.include_content)75    const secret = newWebhookSecret()76    const [w] = await sql`insert into webhooks (name, key_id, user_id, url, secret_enc, events, address_ids, include_content, active)77      values (${body.name}, ${principal.type === "key" ? principal.keyId : null}, ${principal.type === "user" ? principal.userId : principal.createdBy}, ${body.url}, ${sealSecret(secret)},78        ${body.events}, ${body.address_ids}::uuid[], ${body.include_content}, ${body.active}) returning *`79    return present(w, secret)80  },81})82route({ method: "GET", path: "/webhooks/{id}", tag: "Webhooks", summary: "Read a webhook", scopes: ["mail.webhooks.manage"], params: zIdP, response: zWebhook, handler: async ({ principal, params }) => present(await owned(principal, params.id)) })83route({84  method: "PATCH", path: "/webhooks/{id}", tag: "Webhooks", summary: "Update a webhook, or rotate its secret", scopes: ["mail.webhooks.manage"],85  description: "`rotate_secret: true` returns a new secret once (sessions need a recent re-authentication).",86  params: zIdP, body: zCreate.partial().extend({ rotate_secret: z.boolean().optional() }).strict(), response: zWebhook,87  handler: async ({ principal, params, body }) => {88    const w = await owned(principal, params.id)89    if (body.url !== undefined) await checkWebhookUrl(body.url)90    await checkFilter(principal, body.address_ids, body.include_content)91    let secret: string | undefined92    const cols: Record<string, unknown> = { updated_at: new Date() }93    for (const k of ["name", "url", "events", "address_ids", "include_content", "active"] as const) if (body[k] !== undefined) cols[k] = body[k]94    if (body.rotate_secret) {95      if (principal.type === "user") await requireReauth(principal.auth)96      secret = newWebhookSecret()97      cols.secret_enc = sealSecret(secret)98    }99    const [row] = await sql`update webhooks set ${sql(cols as never)} where id = ${w.id} returning *`100    return present(row, secret)101  },102})103route({ method: "DELETE", path: "/webhooks/{id}", tag: "Webhooks", summary: "Delete a webhook and its delivery history", scopes: ["mail.webhooks.manage"], params: zIdP, response: zOk, handler: async ({ principal, params }) => { const w = await owned(principal, params.id); await sql`delete from webhooks where id = ${w.id}`; return { ok: true as const } } })104105route({106  method: "GET", path: "/webhooks/{id}/deliveries", tag: "Webhooks", summary: "Delivery attempts of a webhook, newest first", scopes: ["mail.webhooks.manage"], params: zIdP,107  query: z.object({ status: z.enum(["pending", "retrying", "delivered", "failed"]).optional(), limit: z.coerce.number().int().min(1).max(100).default(25), cursor: z.string().max(2000).optional() }),108  response: z.object({ data: z.array(zDelivery), next_cursor: z.string().nullable(), has_more: z.boolean() }),109  handler: async ({ principal, params, query }) => {110    const w = await owned(principal, params.id)111    const c = decodeCursor<{ t: string; i: string }>(query.cursor, (x) => typeof x.t === "string" && typeof x.i === "string")112    const rows = await sql`select d.*, e.type from webhook_deliveries d join webhook_events e on e.id = d.event_id where d.webhook_id = ${w.id}113      ${query.status ? sql`and d.status = ${query.status}` : sql``} ${c ? sql`and (date_trunc('milliseconds', d.created_at), d.id) < (${new Date(c.t)}, ${c.i}::uuid)` : sql``}114      order by date_trunc('milliseconds', d.created_at) desc, d.id desc limit ${query.limit + 1}`115    const page = rows.slice(0, query.limit)116    const more = rows.length > query.limit117    return { data: page.map(presentDelivery), next_cursor: more ? encodeCursor({ t: iso(page[page.length - 1].created_at), i: page[page.length - 1].id }) : null, has_more: more }118  },119})120const zAttempt = z.object({ delivery: zDelivery, http_status: z.number().nullable(), error: z.string().nullable() })121route({122  method: "POST", path: "/webhooks/{id}/test", tag: "Webhooks", summary: "Send a signed `webhook.test` event to this webhook now", scopes: ["mail.webhooks.manage"], params: zIdP, response: zAttempt,123  handler: async ({ principal, params }) => {124    const w = await owned(principal, params.id)125    const eventId = await emitEvent({ type: "webhook.test", data: { webhook_id: w.id, message: "Test event from SP Mail" } }, sql, w.id)126    const [d] = await sql`select id from webhook_deliveries where event_id = ${eventId} and webhook_id = ${w.id}`127    await sql`update webhook_deliveries set locked_until = now() + interval '30 seconds' where id = ${d.id}`128    const r = await attemptDelivery(d.id)129    const [row] = await sql`select d.*, e.type from webhook_deliveries d join webhook_events e on e.id = d.event_id where d.id = ${d.id}`130    return { delivery: presentDelivery(row), http_status: r.http_status, error: r.error }131  },132})133route({134  method: "POST", path: "/webhook-deliveries/{id}/replay", tag: "Webhooks", summary: "Replay a delivery (same event id, new signature and timestamp)", scopes: ["mail.webhooks.manage"], params: zIdP, response: zDelivery,135  description: "Queues the delivery again with the attempt counter reset; the normal backoff applies if the receiver fails again.",136  handler: async ({ principal, params }) => {137    if (!/^[0-9a-f-]{36}$/.test(params.id)) throw bad("not_found", 404, "Unknown delivery")138    const [d] = await sql`select webhook_id from webhook_deliveries where id = ${params.id}`139    if (!d) throw bad("not_found", 404, "Unknown delivery")140    await owned(principal, d.webhook_id)141    await sql`update webhook_deliveries set status = 'pending', attempt = 0, next_attempt_at = now(), locked_until = null, last_error = null, delivered_at = null where id = ${params.id}`142    const [row] = await sql`select d.*, e.type from webhook_deliveries d join webhook_events e on e.id = d.event_id where d.id = ${params.id}`143    return presentDelivery(row)144  },145})146147const zEvent = z.object({ id: z.string(), type: z.string(), occurred_at: z.string(), address: z.string().nullable(), mailbox: z.string().nullable(), data: z.record(z.string(), z.unknown()) })148route({149  method: "GET", path: "/events", tag: "Webhooks", summary: "Recent events visible to the caller (metadata only, newest first)", scopes: ["mail.read", "mail.webhooks.manage", "mail.send"],150  description: "Events are kept 30 days. Content fields (subject, preview) are never returned here.",151  query: z.object({ type: z.enum(EVENT_TYPES).optional(), limit: z.coerce.number().int().min(1).max(100).default(25), cursor: z.string().max(2000).optional() }),152  response: z.object({ data: z.array(zEvent), next_cursor: z.string().nullable(), has_more: z.boolean() }),153  handler: async ({ principal, query }) => {154    const c = decodeCursor<{ s: number }>(query.cursor, (x) => Number.isInteger(x.s))155    const all = (principal.type === "user" && principal.role === "admin") || (principal.type === "key" && principal.allAddresses && principal.scopes.has("mail.admin"))156    const acc = [...(await accessMap(principal)).values()]157    const addressIds = acc.flatMap((a) => a.addresses.map((x) => x.id))158    const fullBoxes = acc.filter((a) => a.read === "full").map((a) => a.mailbox.id)159    const rows = await sql`select seq, payload from webhook_events where type <> 'webhook.test'160      ${all ? sql`` : sql`and (address_id = any(${addressIds}::uuid[]) or mailbox_id = any(${fullBoxes}::uuid[]))`}161      ${query.type ? sql`and type = ${query.type}` : sql``} ${c ? sql`and seq < ${c.s}` : sql``} order by seq desc limit ${query.limit + 1}`162    const page = rows.slice(0, query.limit)163    const more = rows.length > query.limit164    return { data: page.map((r) => r.payload), next_cursor: more ? encodeCursor({ s: page[page.length - 1].seq }) : null, has_more: more }165  },166})167
Files main
Menu

Theme