Outbound webhooks (1.48.0)

Site settings -> Webhooks: admins add https endpoints and choose event
types (registration created/paid/cancelled, payment received/refunded,
ticket checked in, account created, event published). Events are
noticed by a Prisma client extension so every write path is covered,
re-checked before sending, and delivered as signed JSON
(X-CrossEvents-Signature, HMAC-SHA256) with retries, a 30-day delivery
log, Send test and Resend. Public https addresses only; each endpoint
is added to the operator register; kids and volunteer tickets are never
sent. New `webhooks` job. Migration 20261028160000_webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 13:00:59 +02:00
co-authored by Claude Opus 5.5
parent 50e0cbe62d
commit 51dc908630
30 changed files with 1326 additions and 18 deletions
@@ -7,20 +7,21 @@ import Link from "next/link";
import { apiFetch, ApiError, API_BASE, resolveToApiOrigin } from "@/lib/api";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon } from "lucide-react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook } from "lucide-react";
import { ColorPickerField } from "@/components/admin/ColorPickerField";
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
import { BackupsTab } from "@/components/admin/BackupsTab";
import { JobsTab } from "@/components/admin/JobsTab";
import { PaymentsTab } from "@/components/admin/PaymentsTab";
import { LicenceTab } from "@/components/admin/LicenceTab";
import { WebhooksTab } from "@/components/admin/WebhooksTab";
import { CampusesTab } from "@/components/admin/CampusesTab";
import { extractDominantColors } from "@/lib/extractColors";
import { mapsSearchUrl } from "@/lib/maps";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "backups" | "jobs" | "licence";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence";
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "organisation", label: "Organisation", icon: Building2 },
@@ -31,6 +32,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "legal", label: "Legal", icon: Scale },
{ id: "whatsapp", label: "WhatsApp", icon: MessageCircle },
{ id: "payments", label: "Payments", icon: CreditCard },
{ id: "webhooks", label: "Webhooks", icon: Webhook },
{ id: "backups", label: "Backups", icon: DatabaseBackup },
{ id: "jobs", label: "Background jobs", icon: Timer },
{ id: "licence", label: "Licence", icon: KeyRound },
@@ -716,6 +718,7 @@ function SiteSettingsPageInner() {
{/* ── Backups ───────────────────────────────────────────────────────── */}
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
{activeTab === "campuses" && <CampusesTab active={activeTab === "campuses"} />}
@@ -23,6 +23,7 @@ const STATE: Record<string, string> = {
const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—");
function describeCron(cron: string): string {
if (cron === "* * * * *") return "Every minute";
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
if (m) return `Every ${m[1]} minutes`;
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
@@ -0,0 +1,249 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { Webhook, Send, RefreshCw, KeyRound, Trash2, Pencil, Copy, ChevronDown, ChevronRight, RotateCcw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
type EventType = { type: string; label: string; description: string };
type Endpoint = {
id: string; name: string; url: string; events: string[]; isActive: boolean;
lastSuccessAt: string | null; lastFailureAt: string | null; createdAt: string;
lastWeek?: Record<string, number>;
};
type Delivery = {
id: string; eventId: string; type: string; status: string; attempts: number; nextAttemptAt: string;
lastStatusCode: number | null; lastError: string | null; deliveredAt: string | null; createdAt: string; payload: unknown;
};
type ListResponse = { eventTypes: EventType[]; keepDays: number; endpoints: Endpoint[] };
type Draft = { id?: string; name: string; url: string; events: string[] };
const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—");
const STATUS: Record<string, string> = {
succeeded: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", retrying: "bg-amber-50 text-amber-800",
pending: "bg-gray-100 text-gray-600", sending: "bg-blue-50 text-blue-700",
};
/** Shown once after adding an endpoint or making a new secret. */
function SecretBox({ secret, onClose }: { secret: string; onClose: () => void }) {
const [copied, setCopied] = useState(false);
return (
<div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm space-y-2" data-testid="webhook-secret">
<p className="font-medium text-amber-900">Signing secret — copy it now, it won&apos;t be shown again</p>
<div className="flex items-center gap-2">
<code className="flex-1 break-all rounded bg-white border px-2 py-1 text-xs">{secret}</code>
<button type="button" className="inline-flex items-center gap-1 px-2 py-1 rounded border bg-white text-xs hover:bg-gray-50"
onClick={() => { navigator.clipboard?.writeText(secret).then(() => setCopied(true)).catch(() => {}); }}>
<Copy className="w-3.5 h-3.5" /> {copied ? "Copied" : "Copy"}
</button>
</div>
<p className="text-xs text-amber-900">
Each request has an <code>X-CrossEvents-Signature: t=…,v1=…</code> header: v1 is the HMAC-SHA256 (hex) of <code>&lt;t&gt;.&lt;body&gt;</code> with this secret. Check it, and that t is recent, before trusting a request.
</p>
<button type="button" className="text-xs underline text-amber-900" onClick={onClose}>I&apos;ve saved it</button>
</div>
);
}
function Deliveries({ endpointId, token }: { endpointId: string; token: string }) {
const [rows, setRows] = useState<Delivery[] | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const load = useCallback(async () => {
setRows(await apiFetch<Delivery[]>(`/api/outbound-webhooks/${endpointId}/deliveries`, { authToken: token }).catch(() => []));
}, [endpointId, token]);
useEffect(() => { load(); }, [load]);
const resend = async (id: string) => {
setBusy(id);
await apiFetch(`/api/outbound-webhooks/deliveries/${id}/resend`, { method: "POST", authToken: token }).catch(() => {});
setBusy(null);
load();
};
if (!rows) return <p className="text-xs text-gray-400">Loading…</p>;
if (!rows.length) return <p className="text-xs text-gray-500">Nothing sent yet.</p>;
return (
<div className="space-y-1" data-testid="webhook-deliveries">
<div className="flex justify-end"><button type="button" onClick={load} className="inline-flex items-center gap-1 text-xs text-gray-600 hover:text-gray-900"><RefreshCw className="w-3 h-3" /> Refresh</button></div>
<ul className="divide-y border rounded-lg bg-white">
{rows.map(d => (
<li key={d.id} className="text-xs" data-testid="webhook-delivery">
<div className="flex flex-wrap items-center gap-2 px-3 py-2">
<button type="button" onClick={() => setOpen(open === d.id ? null : d.id)} className="text-gray-500" aria-label="Show what was sent">
{open === d.id ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
</button>
<span className="text-gray-500 w-28">{when(d.createdAt)}</span>
<code className="font-medium">{d.type}</code>
<span className={`px-1.5 py-0.5 rounded ${STATUS[d.status] || "bg-gray-100"}`}>{d.status}</span>
<span className="text-gray-500">
{d.attempts} tr{d.attempts === 1 ? "y" : "ies"}{d.lastStatusCode ? ` · ${d.lastStatusCode}` : ""}{d.status === "retrying" ? ` · next ${when(d.nextAttemptAt)}` : ""}
</span>
{d.lastError && <span className="text-red-700 truncate max-w-[16rem]" title={d.lastError}>{d.lastError}</span>}
{d.status !== "sending" && (
<button type="button" disabled={busy === d.id} onClick={() => resend(d.id)} className="ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50">
<RotateCcw className="w-3 h-3" /> Resend
</button>
)}
</div>
{open === d.id && <pre className="mx-3 mb-2 max-h-64 overflow-auto rounded bg-gray-50 p-2 text-[11px]">{JSON.stringify(d.payload, null, 2)}</pre>}
</li>
))}
</ul>
</div>
);
}
// Settings → Webhooks: send what happens here (registrations, payments, check-ins…) to other systems.
export function WebhooksTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [data, setData] = useState<ListResponse | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [secret, setSecret] = useState<{ endpointId: string; value: string } | null>(null);
const [openLog, setOpenLog] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(async () => {
if (!token) return;
try { setData(await apiFetch<ListResponse>("/api/outbound-webhooks", { authToken: token })); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Couldn't load webhooks" }); }
}, [token]);
useEffect(() => { if (active) load(); }, [active, load]);
const run = async (fn: () => Promise<void>) => {
setBusy(true); setMsg(null);
try { await fn(); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Something went wrong" }); } finally { setBusy(false); }
};
const save = () => run(async () => {
if (!draft) return;
const body = { name: draft.name, url: draft.url, events: draft.events };
if (draft.id) {
await apiFetch(`/api/outbound-webhooks/${draft.id}`, { method: "PUT", authToken: token || undefined, body });
setMsg({ type: "ok", text: "Webhook saved." });
} else {
const made = await apiFetch<Endpoint & { secret: string }>("/api/outbound-webhooks", { method: "POST", authToken: token || undefined, body });
setSecret({ endpointId: made.id, value: made.secret });
setMsg({ type: "ok", text: `"${made.name}" added, and listed in the operator register (Admin → Privacy).` });
}
setDraft(null);
await load();
});
const toggle = (e: Endpoint) => run(async () => {
await apiFetch(`/api/outbound-webhooks/${e.id}`, { method: "PUT", authToken: token || undefined, body: { isActive: !e.isActive } });
await load();
});
const test = (e: Endpoint) => run(async () => {
const r = await apiFetch<{ status: string; statusCode: number | null; error: string | null }>(`/api/outbound-webhooks/${e.id}/test`, { method: "POST", authToken: token || undefined });
setMsg(r.status === "succeeded"
? { type: "ok", text: `Test delivered (answered ${r.statusCode}).` }
: { type: "err", text: `Test not delivered: ${r.error || "no answer"}. It will be retried; see the delivery log.` });
if (openLog === e.id) setOpenLog(null);
await load();
});
const rotate = (e: Endpoint) => run(async () => {
if (!confirm(`Make a new secret for "${e.name}"? The old one stops working at once, so update the receiving side straight away.`)) return;
const r = await apiFetch<{ secret: string }>(`/api/outbound-webhooks/${e.id}/rotate-secret`, { method: "POST", authToken: token || undefined });
setSecret({ endpointId: e.id, value: r.secret });
});
const remove = (e: Endpoint) => run(async () => {
if (!confirm(`Delete "${e.name}" and its delivery log?`)) return;
await apiFetch(`/api/outbound-webhooks/${e.id}`, { method: "DELETE", authToken: token || undefined });
setMsg({ type: "ok", text: "Webhook deleted. Its operator register entry is marked inactive." });
await load();
});
const toggleEvent = (type: string) => setDraft(d => d && ({ ...d, events: d.events.includes(type) ? d.events.filter(t => t !== type) : [...d.events, type] }));
if (!data) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-400">Loading…</p>;
const label = (type: string) => data.eventTypes.find(t => t.type === type)?.label || type;
return (
<div className="space-y-5">
<div className="flex items-start justify-between gap-3 flex-wrap">
<div>
<h2 className="text-lg font-semibold text-gray-900 flex items-center gap-2"><Webhook className="w-5 h-5" /> Webhooks</h2>
<p className="text-sm text-gray-500 max-w-2xl">
Send what happens here — registrations, payments, check-ins, new accounts — to another system as it happens (e.g. ChurchSuite or Planning Center through Zapier or Make).
</p>
</div>
{!draft && <button type="button" onClick={() => { setMsg(null); setDraft({ name: "", url: "", events: [] }); }} className="px-4 py-2 text-sm rounded-lg bg-brand-600 text-white hover:bg-brand-700 font-medium">+ Add webhook</button>}
</div>
<p className="text-xs text-gray-600 bg-gray-50 border rounded-lg p-3">
Webhooks send personal information (names, email addresses, phone numbers) to the service you choose, so each one is added to your operator register. Make sure you have an agreement with that service. What was sent is kept {data.keepDays} days for the delivery log. Children&apos;s details from kids check-in are never sent.
</p>
{msg && <div className={`p-3 border rounded text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`} role="status">{msg.text}</div>}
{secret && <SecretBox secret={secret.value} onClose={() => setSecret(null)} />}
{draft && (
<div className="border rounded-xl p-4 space-y-3 bg-white" data-testid="webhook-form">
<div className="grid sm:grid-cols-2 gap-3">
<div>
<label className="block text-xs text-gray-600 mb-1" htmlFor="webhook-name">Name</label>
<input id="webhook-name" className="w-full border rounded px-3 py-2 text-sm" value={draft.name} onChange={e => setDraft({ ...draft, name: e.target.value })} placeholder="e.g. ChurchSuite sync" />
</div>
<div>
<label className="block text-xs text-gray-600 mb-1" htmlFor="webhook-url">Address (https)</label>
<input id="webhook-url" className="w-full border rounded px-3 py-2 text-sm" value={draft.url} onChange={e => setDraft({ ...draft, url: e.target.value })} placeholder="https://…" />
</div>
</div>
<div>
<div className="text-xs text-gray-600 mb-1">Send when</div>
<div className="grid sm:grid-cols-2 gap-2">
{data.eventTypes.map(t => (
<label key={t.type} className="flex items-start gap-2 text-sm border rounded-lg p-2 cursor-pointer hover:bg-gray-50">
<input type="checkbox" className="mt-1" checked={draft.events.includes(t.type)} onChange={() => toggleEvent(t.type)} />
<span><span className="font-medium">{t.label}</span> <code className="text-[10px] text-gray-500">{t.type}</code><span className="block text-xs text-gray-500">{t.description}</span></span>
</label>
))}
</div>
</div>
<div className="flex gap-2">
<button type="button" disabled={busy || !draft.name.trim() || !draft.url.trim() || !draft.events.length} onClick={save} className="px-4 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50 font-medium">
{busy ? "Saving…" : draft.id ? "Save webhook" : "Add webhook"}
</button>
<button type="button" onClick={() => setDraft(null)} className="px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50">Cancel</button>
</div>
</div>
)}
{data.endpoints.length === 0 && !draft ? (
<p className="text-sm text-gray-500 border rounded-xl p-4">No webhooks yet.</p>
) : (
<ul className="space-y-3">
{data.endpoints.map(e => (
<li key={e.id} className="border rounded-xl p-4 bg-white space-y-2" data-testid="webhook-endpoint">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<div className="font-medium text-gray-900 flex items-center gap-2">
{e.name}
{!e.isActive && <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">Off</span>}
</div>
<div className="text-xs text-gray-500 break-all">{e.url}</div>
<div className="mt-1 flex flex-wrap gap-1">{e.events.map(t => <span key={t} className="text-[10px] px-1.5 py-0.5 rounded bg-brand-50 text-brand-700">{label(t)}</span>)}</div>
<div className="mt-1 text-xs text-gray-500">
Last delivered {when(e.lastSuccessAt)}{e.lastFailureAt && <> · last failure {when(e.lastFailureAt)}</>}
{e.lastWeek && Object.keys(e.lastWeek).length > 0 && <> · this week: {Object.entries(e.lastWeek).map(([s, n]) => `${n} ${s}`).join(", ")}</>}
</div>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" disabled={busy} onClick={() => test(e)} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50"><Send className="w-3.5 h-3.5" /> Send test</button>
<button type="button" onClick={() => { setMsg(null); setDraft({ id: e.id, name: e.name, url: e.url, events: e.events }); }} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50"><Pencil className="w-3.5 h-3.5" /> Edit</button>
<button type="button" disabled={busy} onClick={() => toggle(e)} className="text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50">{e.isActive ? "Switch off" : "Switch on"}</button>
<button type="button" disabled={busy} onClick={() => rotate(e)} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50 disabled:opacity-50"><KeyRound className="w-3.5 h-3.5" /> New secret</button>
<button type="button" disabled={busy} onClick={() => remove(e)} className="inline-flex items-center gap-1 text-xs px-2.5 py-1.5 rounded bg-red-50 text-red-700 border border-red-200 disabled:opacity-50"><Trash2 className="w-3.5 h-3.5" /> Delete</button>
</div>
</div>
<button type="button" onClick={() => setOpenLog(openLog === e.id ? null : e.id)} className="inline-flex items-center gap-1 text-xs text-brand-700 hover:underline">
{openLog === e.id ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />} Delivery log
</button>
{openLog === e.id && token && <Deliveries endpointId={e.id} token={token} />}
</li>
))}
</ul>
)}
</div>
);
}
@@ -1,5 +1,5 @@
import React from "react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone } from "lucide-react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone, Webhook, Send } from "lucide-react";
import { GuideItem } from "@/components/shared/GuideItem";
import type { HelpContent } from "./types";
@@ -147,6 +147,27 @@ export const siteSettingsHelpContent: HelpContent = {
</div>
),
},
{
key: "webhooks",
label: "Webhooks",
icon: Webhook,
content: (
<div className="space-y-4">
<p>Send what happens here to another system as it happens — for example to ChurchSuite, Planning Center or a Google Sheet through Zapier or Make.</p>
<div className="space-y-4">
<GuideItem icon={Webhook} title="Add a webhook" tone="brand">
&quot;+ Add webhook&quot;: a name, the https address the other system gave you, and what to send — registrations made, paid or cancelled, payments and refunds, check-ins, new accounts, published events. Copy the signing secret it shows (once) into the other system so it can check requests really come from you.
</GuideItem>
<GuideItem icon={Send} title="Test and delivery log" tone="green">
&quot;Send test&quot; sends a test message straight away. The delivery log shows everything sent in the last 30 days, what came back, and the full message. Anything that fails is tried again after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours; &quot;Resend&quot; tries again now.
</GuideItem>
<GuideItem icon={Scale} title="Privacy" tone="amber">
Webhooks send names, email addresses and phone numbers, so each webhook is added to your operator register (Admin → Privacy) — have an agreement with the service. Children&apos;s details from kids check-in are never sent. Switch a webhook off or delete it at any time.
</GuideItem>
</div>
</div>
),
},
{
key: "jobs",
label: "Background jobs",