Email for professionals and teams
feat(webhooks): management UI and delivery retry visibility
Oday Bakkour42cea463e04d
diff --git a/env.d.ts b/env.d.tsindex 47e9fe9..21b0a00 100644--- a/env.d.ts+++ b/env.d.ts@@ -3,7 +3,11 @@ interface CloudflareEnv {EMAIL: SendEmail;BUCKET: R2Bucket;INBOUND_QUEUE: Queue<import("./src/lib/email/inbound").InboundQueueMessage>;- OUTBOUND_QUEUE: Queue<import("./src/lib/email/send").OutboundQueueMessage>;+ // The outbound queue also carries webhook retries so that scheduled redelivery needs no extra binding.+ OUTBOUND_QUEUE: Queue<+ | import("./src/lib/email/send").OutboundQueueMessage+ | import("./src/lib/email/webhooks").WebhookRetryMessage+ >;ASSETS: Fetcher;IMAGES: ImagesBinding;WORKER_SELF_REFERENCE: Fetcher;diff --git a/src/app/(admin)/webhooks/deliveries.tsx b/src/app/(admin)/webhooks/deliveries.tsxnew file mode 100644index 0000000..c9a03d3--- /dev/null+++ b/src/app/(admin)/webhooks/deliveries.tsx@@ -0,0 +1,122 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { RotateCw } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import type { WebhookDelivery } from "./types";+import {+ DELIVERY_STATUS_LABELS,+ fetchDeliveries,+ formatDuration,+ formatTimestamp,+ isRetryable,+ retryDelivery,+} from "./utils";++const STATUS_STYLES: Record<WebhookDelivery["status"], string> = {+ delivered: "bg-green-600/10 text-green-700",+ failed: "bg-red-600/10 text-red-700",+ exhausted: "bg-red-600/10 text-red-700",+ retrying: "bg-amber-500/10 text-amber-700",+ pending: "bg-neutral-200 text-neutral-700",+};++export function WebhookDeliveries({ webhookId }: { webhookId: string }) {+ const qc = useQueryClient();+ const deliveries = useQuery({+ queryKey: ["webhook-deliveries", webhookId],+ queryFn: () => fetchDeliveries(webhookId),+ // Retries land asynchronously from the queue, so keep the table fresh while it is open.+ refetchInterval: 15_000,+ });++ const retry = useMutation({+ mutationFn: (deliveryId: string) => retryDelivery(webhookId, deliveryId),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ["webhook-deliveries", webhookId] });+ qc.invalidateQueries({ queryKey: ["webhooks"] });+ },+ });++ if (deliveries.isLoading) {+ return <p className="text-sm text-neutral-500">Loading deliveries…</p>;+ }++ if (!deliveries.data?.length) {+ return <p className="text-sm text-neutral-500">No deliveries recorded yet.</p>;+ }++ return (+ <div className="overflow-x-auto rounded-xl border border-neutral-200">+ <table className="w-full min-w-[820px] text-left text-sm">+ <thead className="bg-neutral-50 text-xs uppercase tracking-wide text-neutral-500">+ <tr>+ <th className="px-3 py-2 font-medium">Event</th>+ <th className="px-3 py-2 font-medium">Status</th>+ <th className="px-3 py-2 font-medium">Attempts</th>+ <th className="px-3 py-2 font-medium">Response</th>+ <th className="px-3 py-2 font-medium">Last attempt</th>+ <th className="px-3 py-2 font-medium">Next retry</th>+ <th className="px-3 py-2 font-medium" />+ </tr>+ </thead>+ <tbody>+ {deliveries.data.map((delivery) => (+ <tr key={delivery.id} className="border-t border-neutral-100 align-top">+ <td className="px-3 py-2">+ <span className="block">{delivery.eventType}</span>+ <span className="block text-xs text-neutral-400">+ {formatTimestamp(delivery.createdAt)}+ </span>+ </td>+ <td className="px-3 py-2">+ <Badge className={STATUS_STYLES[delivery.status]}>+ {DELIVERY_STATUS_LABELS[delivery.status] ?? delivery.status}+ </Badge>+ </td>+ <td className="px-3 py-2 whitespace-nowrap">+ {/* Manual retries can push attempts past the configured max, so never show "3 / 2". */}+ {delivery.attempts} / {Math.max(delivery.maxAttempts, delivery.attempts)}+ </td>+ <td className="px-3 py-2">+ <span className="block whitespace-nowrap">+ {delivery.responseStatus ?? "—"}+ {delivery.durationMs !== null && (+ // An explicit separator: "200" next to "6ms" otherwise reads as "2006ms".+ <span className="ml-1 text-xs text-neutral-400">+ · {formatDuration(delivery.durationMs)}+ </span>+ )}+ </span>+ {delivery.error && (+ <span className="mt-1 block max-w-xs truncate text-xs text-red-600" title={delivery.error}>+ {delivery.error}+ </span>+ )}+ </td>+ <td className="px-3 py-2 whitespace-nowrap text-neutral-600">+ {formatTimestamp(delivery.lastAttemptAt)}+ </td>+ <td className="px-3 py-2 whitespace-nowrap text-neutral-600">+ {formatTimestamp(delivery.nextRetryAt)}+ </td>+ <td className="px-3 py-2">+ {isRetryable(delivery) && (+ <Button+ variant="outline"+ size="sm"+ disabled={retry.isPending}+ onClick={() => retry.mutate(delivery.id)}+ >+ <RotateCw className="h-3 w-3" /> Retry+ </Button>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/src/app/(admin)/webhooks/page.tsx b/src/app/(admin)/webhooks/page.tsxindex 6739262..bd008f4 100644--- a/src/app/(admin)/webhooks/page.tsx+++ b/src/app/(admin)/webhooks/page.tsx@@ -1,81 +1,273 @@"use client";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Activity, Plus, RefreshCw, Send, Trash2 } from "lucide-react";+import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { authFetch } from "@/lib/auth/client";+import { Switch } from "@/components/ui/switch";+import { CardGridSkeleton } from "@/components/page-skeletons";+import type { Webhook, WebhookEvent } from "./types";+import {+ WEBHOOK_EVENTS,+ createWebhook,+ deleteWebhook,+ fetchWebhooks,+ testWebhook,+ updateWebhook,+} from "./utils";+import { WebhookDeliveries } from "./deliveries";export default function WebhooksPage() {const qc = useQueryClient();+ const [dialogOpen, setDialogOpen] = useState(false);const [url, setUrl] = useState("");+ const [description, setDescription] = useState("");+ const [maxAttempts, setMaxAttempts] = useState(5);+ const [events, setEvents] = useState<WebhookEvent[]>(WEBHOOK_EVENTS.map((e) => e.value));const [secret, setSecret] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [expanded, setExpanded] = useState<string | null>(null);+ const [testResult, setTestResult] = useState<Record<string, string>>({});- const { data } = useQuery({- queryKey: ["webhooks"],- queryFn: async () => {- const res = await authFetch("/api/webhooks");- return (await res.json()) as { webhooks: { id: string; url: string }[] };- },- });+ const webhooks = useQuery({ queryKey: ["webhooks"], queryFn: fetchWebhooks });+ const invalidate = () => qc.invalidateQueries({ queryKey: ["webhooks"] });const create = useMutation({- mutationFn: async () => {- const res = await authFetch("/api/webhooks", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- url,- events: ["message.inbound", "message.outbound", "message.failed"],- }),- });- const json = (await res.json()) as { secret?: string };- if (!res.ok) throw new Error("Failed");- setSecret(json.secret ?? null);+ mutationFn: () => createWebhook({ url, description: description || undefined, events, maxAttempts }),+ onSuccess: (result) => {+ setSecret(result.secret);setUrl("");+ setDescription("");+ setError(null);+ setDialogOpen(false);+ invalidate();},- onSuccess: () => qc.invalidateQueries({ queryKey: ["webhooks"] }),+ onError: (e: Error) => setError(e.message),});+ const toggle = useMutation({+ mutationFn: (hook: Webhook) => updateWebhook(hook.id, { enabled: !hook.enabled }),+ onSuccess: invalidate,+ });++ const remove = useMutation({ mutationFn: deleteWebhook, onSuccess: invalidate });++ const runTest = useMutation({+ mutationFn: testWebhook,+ onSuccess: (result, id) => {+ setTestResult((prev) => ({ ...prev, [id]: result.status }));+ invalidate();+ },+ onError: (e: Error, id) => setTestResult((prev) => ({ ...prev, [id]: e.message })),+ });++ function toggleEvent(event: WebhookEvent) {+ setEvents((prev) => (prev.includes(event) ? prev.filter((e) => e !== event) : [...prev, event]));+ }+return (- <div className="space-y-6 max-w-2xl">- <h1 className="text-2xl font-semibold">Webhooks</h1>+ <div className="space-y-6">+ <div className="flex flex-wrap items-end justify-between gap-4">+ <div>+ <h1 className="text-2xl font-semibold">Webhooks</h1>+ <p className="mt-1 text-sm text-neutral-500">+ Deliver message events to your own endpoints, with automatic retries.+ </p>+ </div>+ <Button+ onClick={() => {+ setError(null);+ setDialogOpen(true);+ }}+ >+ <Plus className="h-4 w-4" /> Add endpoint+ </Button>+ </div>+{secret && (<Card><CardContent className="pt-6 text-sm">- <p>Signing secret:</p>- <code className="block mt-1 text-xs break-all">{secret}</code>+ <p className="font-medium">Signing secret — shown once</p>+ <p className="mt-1 text-neutral-500">+ Verify the <code>X-Email-Platform-Signature</code> header (HMAC-SHA256 of the raw+ body) with this secret.+ </p>+ <code className="mt-2 block break-all rounded-lg bg-neutral-100 p-2 text-xs">+ {secret}+ </code>+ <Button variant="outline" size="sm" className="mt-3" onClick={() => setSecret(null)}>+ Dismiss+ </Button></CardContent></Card>)}- <Card>- <CardHeader>- <CardTitle>Add webhook</CardTitle>- </CardHeader>- <CardContent className="space-y-4">- <div className="space-y-2">- <Label>URL</Label>- <Input value={url} onChange={(e) => setUrl(e.target.value)} />- </div>- <Button onClick={() => create.mutate()} disabled={!url || create.isPending}>- Add- </Button>- </CardContent>- </Card>- <Card>- <CardHeader>- <CardTitle>Endpoints</CardTitle>- </CardHeader>- <CardContent className="text-sm no-font-mono space-y-1">- {(data?.webhooks ?? []).map((w) => (- <p key={w.id} className="truncate">- {w.url}- </p>++ {webhooks.isLoading ? (+ <CardGridSkeleton />+ ) : !webhooks.data?.length ? (+ <Card>+ <CardContent className="pt-6 text-sm text-neutral-500">+ No endpoints yet. Add one to start receiving events.+ </CardContent>+ </Card>+ ) : (+ <div className="space-y-4">+ {webhooks.data.map((hook) => (+ <Card key={hook.id}>+ <CardHeader className="flex flex-row flex-wrap items-start justify-between gap-3">+ <div className="min-w-0">+ <CardTitle className="truncate text-base">{hook.url}</CardTitle>+ {hook.description && (+ <p className="mt-1 text-sm text-neutral-500">{hook.description}</p>+ )}+ <div className="mt-2 flex flex-wrap gap-1">+ {hook.events.map((event) => (+ <Badge key={event} variant="secondary">+ {event}+ </Badge>+ ))}+ {!hook.enabled && <Badge variant="outline">Disabled</Badge>}+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Switch checked={hook.enabled} onCheckedChange={() => toggle.mutate(hook)} />+ <Button+ variant="outline"+ size="sm"+ onClick={() => runTest.mutate(hook.id)}+ disabled={runTest.isPending}+ >+ <Send className="h-4 w-4" /> Test+ </Button>+ <Button variant="ghost" size="sm" onClick={() => remove.mutate(hook.id)}>+ <Trash2 className="h-4 w-4 text-red-600" />+ </Button>+ </div>+ </CardHeader>+ <CardContent className="space-y-3">+ <div className="flex flex-wrap gap-4 text-sm text-neutral-600">+ <span>{hook.stats.total} deliveries</span>+ <span className="text-green-600">{hook.stats.delivered} delivered</span>+ <span className="text-amber-600">{hook.stats.pending} in flight</span>+ <span className="text-red-600">{hook.stats.failing} failed</span>+ <span className="text-neutral-400">up to {hook.maxAttempts} attempts</span>+ </div>++ {testResult[hook.id] && (+ <p className="text-sm text-neutral-600">+ Test delivery: <span className="font-medium">{testResult[hook.id]}</span>+ </p>+ )}++ <Button+ variant="outline"+ size="sm"+ onClick={() => setExpanded(expanded === hook.id ? null : hook.id)}+ >+ <Activity className="h-4 w-4" />+ {expanded === hook.id ? "Hide deliveries" : "View deliveries"}+ </Button>++ {expanded === hook.id && <WebhookDeliveries webhookId={hook.id} />}+ </CardContent>+ </Card>))}- </CardContent>- </Card>+ </div>+ )}++ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>+ <DialogContent className="max-h-[calc(100vh-4rem)] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>Add endpoint</DialogTitle>+ <DialogDescription>+ Failed deliveries retry automatically with exponential backoff.+ </DialogDescription>+ </DialogHeader>+ <form+ className="space-y-4"+ onSubmit={(e) => {+ e.preventDefault();+ create.mutate();+ }}+ >+ <div className="space-y-2">+ <Label htmlFor="hook-url">Endpoint URL</Label>+ <Input+ id="hook-url"+ type="url"+ required+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="hook-description">Description</Label>+ <Input+ id="hook-description"+ value={description}+ placeholder="Optional"+ onChange={(e) => setDescription(e.target.value)}+ />+ </div>+ <div className="space-y-2">+ <Label>Events</Label>+ {WEBHOOK_EVENTS.map((event) => (+ <label+ key={event.value}+ className="flex cursor-pointer items-center justify-between rounded-lg border border-neutral-200 px-3 py-2"+ >+ <span>+ <span className="block text-sm font-medium">{event.label}</span>+ <span className="block text-xs text-neutral-500">{event.hint}</span>+ </span>+ <input+ type="checkbox"+ className="h-4 w-4"+ checked={events.includes(event.value)}+ onChange={() => toggleEvent(event.value)}+ />+ </label>+ ))}+ </div>+ <div className="space-y-2">+ <Label htmlFor="hook-attempts">Max attempts</Label>+ <Input+ id="hook-attempts"+ type="number"+ min={1}+ max={10}+ value={maxAttempts}+ onChange={(e) => setMaxAttempts(Number(e.target.value))}+ />+ </div>++ {error && <p className="text-sm text-red-600">{error}</p>}++ <div className="flex justify-end gap-2">+ <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>+ Cancel+ </Button>+ <Button type="submit" disabled={create.isPending || events.length === 0}>+ <RefreshCw+ className={create.isPending ? "h-4 w-4 animate-spin" : "hidden"}+ />+ Create+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog></div>);}diff --git a/src/app/(admin)/webhooks/types.d.ts b/src/app/(admin)/webhooks/types.d.tsnew file mode 100644index 0000000..801a804--- /dev/null+++ b/src/app/(admin)/webhooks/types.d.ts@@ -0,0 +1,50 @@+export type WebhookEvent = "message.inbound" | "message.outbound" | "message.failed";++export type WebhookDeliveryStats = {+ total: number;+ delivered: number;+ failing: number;+ pending: number;+ lastAttemptAt: number | null;+};++export type Webhook = {+ id: string;+ url: string;+ description: string | null;+ events: WebhookEvent[];+ enabled: boolean;+ maxAttempts: number;+ createdAt: string | number;+ stats: WebhookDeliveryStats;+};++export type WebhookDelivery = {+ id: string;+ eventType: string;+ status: "pending" | "delivered" | "failed" | "retrying" | "exhausted";+ attempts: number;+ maxAttempts: number;+ responseStatus: number | null;+ error: string | null;+ durationMs: number | null;+ lastAttemptAt: string | number | null;+ nextRetryAt: string | number | null;+ createdAt: string | number;+ payload: string;+};++export type CreateWebhookInput = {+ url: string;+ description?: string;+ events: WebhookEvent[];+ maxAttempts: number;+};++export type UpdateWebhookInput = {+ url?: string;+ description?: string | null;+ events?: WebhookEvent[];+ enabled?: boolean;+ maxAttempts?: number;+};diff --git a/src/app/(admin)/webhooks/utils.ts b/src/app/(admin)/webhooks/utils.tsnew file mode 100644index 0000000..c125f6a--- /dev/null+++ b/src/app/(admin)/webhooks/utils.ts@@ -0,0 +1,98 @@+import { authFetch } from "@/lib/auth/client";+import type {+ CreateWebhookInput,+ UpdateWebhookInput,+ Webhook,+ WebhookDelivery,+ WebhookEvent,+} from "./types";++export const WEBHOOK_EVENTS: { value: WebhookEvent; label: string; hint: string }[] = [+ { value: "message.inbound", label: "Inbound message", hint: "A message was received and stored" },+ { value: "message.outbound", label: "Outbound message", hint: "A message was sent" },+ { value: "message.failed", label: "Delivery failure", hint: "An outbound message failed" },+];++export const DELIVERY_STATUS_LABELS = {+ pending: "Pending",+ delivered: "Delivered",+ failed: "Failed",+ retrying: "Retrying",+ exhausted: "Gave up",+} as const;++async function readJson<T>(res: Response): Promise<T> {+ const json = (await res.json()) as T & { error?: unknown };+ if (!res.ok) {+ throw new Error(typeof json.error === "string" ? json.error : "Request failed");+ }+ return json;+}++export async function fetchWebhooks(): Promise<Webhook[]> {+ const json = await readJson<{ webhooks: Webhook[] }>(await authFetch("/api/webhooks"));+ return json.webhooks ?? [];+}++export async function fetchDeliveries(webhookId: string): Promise<WebhookDelivery[]> {+ const json = await readJson<{ deliveries: WebhookDelivery[] }>(+ await authFetch(`/api/webhooks/${webhookId}/deliveries?limit=50`),+ );+ return json.deliveries ?? [];+}++export async function createWebhook(input: CreateWebhookInput) {+ return readJson<{ id: string; secret: string }>(+ await authFetch("/api/webhooks", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ }),+ );+}++export async function updateWebhook(id: string, input: UpdateWebhookInput) {+ return readJson(+ await authFetch(`/api/webhooks/${id}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ }),+ );+}++export async function deleteWebhook(id: string) {+ return readJson(await authFetch(`/api/webhooks/${id}`, { method: "DELETE" }));+}++export async function testWebhook(id: string) {+ return readJson<{ deliveryId: string; status: string }>(+ await authFetch(`/api/webhooks/${id}/test`, { method: "POST" }),+ );+}++export async function retryDelivery(webhookId: string, deliveryId: string) {+ return readJson<{ status: string }>(+ await authFetch(`/api/webhooks/${webhookId}/deliveries/${deliveryId}/retry`, {+ method: "POST",+ }),+ );+}++/** Drizzle timestamps arrive as epoch seconds when they bypass the column mapper. */+export function formatTimestamp(value: string | number | null | undefined): string {+ if (value === null || value === undefined) return "—";+ const numeric = typeof value === "number" ? value : Date.parse(String(value));+ if (!Number.isFinite(numeric)) return "—";+ const ms = numeric < 1e12 ? numeric * 1000 : numeric;+ return new Date(ms).toLocaleString();+}++export function formatDuration(ms: number | null): string {+ if (ms === null || ms === undefined) return "—";+ return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;+}++export function isRetryable(delivery: WebhookDelivery): boolean {+ return delivery.status !== "delivered";+}diff --git a/src/app/api/webhooks/[id]/deliveries/[deliveryId]/retry/route.ts b/src/app/api/webhooks/[id]/deliveries/[deliveryId]/retry/route.tsnew file mode 100644index 0000000..d5734ae--- /dev/null+++ b/src/app/api/webhooks/[id]/deliveries/[deliveryId]/retry/route.ts@@ -0,0 +1,17 @@+import { NextResponse } from "next/server";+import { runDelivery } from "@/lib/email/webhooks";+import { loadOwnedWebhook } from "../../../utils";+import type { WebhookDeliveryRouteParams } from "../../../types";++export async function POST(request: Request, { params }: WebhookDeliveryRouteParams) {+ const { id, deliveryId } = await params;+ const loaded = await loadOwnedWebhook(request, id);+ if (loaded.error) return loaded.error;++ const result = await runDelivery(loaded.env, deliveryId, { userId: loaded.user.id });+ if (!result) {+ return NextResponse.json({ error: "Delivery not found" }, { status: 404 });+ }++ return NextResponse.json({ status: result.status });+}diff --git a/src/app/api/webhooks/[id]/deliveries/route.ts b/src/app/api/webhooks/[id]/deliveries/route.tsnew file mode 100644index 0000000..33b5fdc--- /dev/null+++ b/src/app/api/webhooks/[id]/deliveries/route.ts@@ -0,0 +1,43 @@+import { desc, eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { webhookDeliveries } from "@/db/schema";+import { loadOwnedWebhook } from "../utils";+import type { WebhookRouteParams } from "../types";++const MAX_PAYLOAD_PREVIEW = 2000;++export async function GET(request: Request, { params }: WebhookRouteParams) {+ const { id } = await params;+ const loaded = await loadOwnedWebhook(request, id);+ if (loaded.error) return loaded.error;++ const url = new URL(request.url);+ const limit = Math.min(Number(url.searchParams.get("limit") ?? 25), 100);+ const status = url.searchParams.get("status");++ const rows = await loaded.db+ .select()+ .from(webhookDeliveries)+ .where(eq(webhookDeliveries.webhookId, id))+ .orderBy(desc(webhookDeliveries.createdAt))+ .limit(Number.isFinite(limit) && limit > 0 ? limit : 25);++ const filtered = status ? rows.filter((row) => row.status === status) : rows;++ return NextResponse.json({+ deliveries: filtered.map((row) => ({+ id: row.id,+ eventType: row.eventType,+ status: row.status,+ attempts: row.attempts,+ maxAttempts: loaded.hook.maxAttempts,+ responseStatus: row.responseStatus,+ error: row.error,+ durationMs: row.durationMs,+ lastAttemptAt: row.lastAttemptAt,+ nextRetryAt: row.nextRetryAt,+ createdAt: row.createdAt,+ payload: row.payload.slice(0, MAX_PAYLOAD_PREVIEW),+ })),+ });+}diff --git a/src/app/api/webhooks/[id]/route.ts b/src/app/api/webhooks/[id]/route.tsnew file mode 100644index 0000000..fba14bb--- /dev/null+++ b/src/app/api/webhooks/[id]/route.ts@@ -0,0 +1,61 @@+import { eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { webhooks } from "@/db/schema";+import { parseWebhookEvents } from "@/lib/email/webhooks";+import { webhookUpdateSchema } from "@/lib/validators";+import { loadOwnedWebhook } from "./utils";+import type { WebhookRouteParams } from "./types";++export async function GET(request: Request, { params }: WebhookRouteParams) {+ const { id } = await params;+ const loaded = await loadOwnedWebhook(request, id);+ if (loaded.error) return loaded.error;++ const { hook } = loaded;+ return NextResponse.json({+ webhook: {+ id: hook.id,+ url: hook.url,+ description: hook.description,+ events: parseWebhookEvents(hook.events),+ enabled: hook.enabled,+ maxAttempts: hook.maxAttempts,+ createdAt: hook.createdAt,+ },+ });+}++export async function PATCH(request: Request, { params }: WebhookRouteParams) {+ const { id } = await params;+ const loaded = await loadOwnedWebhook(request, id);+ if (loaded.error) return loaded.error;++ const parsed = webhookUpdateSchema.safeParse(await request.json());+ if (!parsed.success) {+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });+ }++ const updates: Partial<typeof webhooks.$inferInsert> = {};+ if (parsed.data.url !== undefined) updates.url = parsed.data.url;+ if (parsed.data.description !== undefined) updates.description = parsed.data.description?.trim() || null;+ if (parsed.data.events !== undefined) updates.events = JSON.stringify(parsed.data.events);+ if (parsed.data.enabled !== undefined) updates.enabled = parsed.data.enabled;+ if (parsed.data.maxAttempts !== undefined) updates.maxAttempts = parsed.data.maxAttempts;++ if (Object.keys(updates).length === 0) {+ return NextResponse.json({ error: "No changes provided" }, { status: 400 });+ }++ await loaded.db.update(webhooks).set(updates).where(eq(webhooks.id, id));+ return NextResponse.json({ ok: true });+}++export async function DELETE(request: Request, { params }: WebhookRouteParams) {+ const { id } = await params;+ const loaded = await loadOwnedWebhook(request, id);+ if (loaded.error) return loaded.error;++ // Deliveries cascade with the webhook row.+ await loaded.db.delete(webhooks).where(eq(webhooks.id, id));+ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/webhooks/[id]/test/route.ts b/src/app/api/webhooks/[id]/test/route.tsnew file mode 100644index 0000000..64250bb--- /dev/null+++ b/src/app/api/webhooks/[id]/test/route.ts@@ -0,0 +1,13 @@+import { NextResponse } from "next/server";+import { sendTestDelivery } from "@/lib/email/webhooks";+import { loadOwnedWebhook } from "../utils";+import type { WebhookRouteParams } from "../types";++export async function POST(request: Request, { params }: WebhookRouteParams) {+ const { id } = await params;+ const loaded = await loadOwnedWebhook(request, id);+ if (loaded.error) return loaded.error;++ const result = await sendTestDelivery(loaded.env, loaded.hook);+ return NextResponse.json(result);+}diff --git a/src/app/api/webhooks/[id]/types.d.ts b/src/app/api/webhooks/[id]/types.d.tsnew file mode 100644index 0000000..4fb37f5--- /dev/null+++ b/src/app/api/webhooks/[id]/types.d.ts@@ -0,0 +1,7 @@+export type WebhookRouteParams = {+ params: Promise<{ id: string }>;+};++export type WebhookDeliveryRouteParams = {+ params: Promise<{ id: string; deliveryId: string }>;+};diff --git a/src/app/api/webhooks/[id]/utils.ts b/src/app/api/webhooks/[id]/utils.tsnew file mode 100644index 0000000..c29efb4--- /dev/null+++ b/src/app/api/webhooks/[id]/utils.ts@@ -0,0 +1,25 @@+import { and, eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { webhooks } from "@/db/schema";+import { requireSessionUser } from "@/lib/api/auth";+import { getEnv } from "@/lib/cloudflare";++/** Loads a webhook owned by the caller, or the 404 response to return instead. */+export async function loadOwnedWebhook(request: Request, id: string) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return { error: auth.error } as const;+ const user = auth.user;+ const db = getDb(env);+ const [hook] = await db+ .select()+ .from(webhooks)+ .where(and(eq(webhooks.id, id), eq(webhooks.userId, user.id)))+ .limit(1);++ if (!hook) {+ return { error: NextResponse.json({ error: "Webhook not found" }, { status: 404 }) } as const;+ }+ return { env, db, user, hook, error: null } as const;+}diff --git a/src/app/api/webhooks/route.ts b/src/app/api/webhooks/route.tsindex bdfd890..8fbe60e 100644--- a/src/app/api/webhooks/route.ts+++ b/src/app/api/webhooks/route.ts@@ -1,9 +1,11 @@import { NextResponse } from "next/server";-import { eq } from "drizzle-orm";+import { count, desc, eq, max } from "drizzle-orm";import { getEnv } from "@/lib/cloudflare";import { getDb } from "@/db";-import { webhooks } from "@/db/schema";-import { requireUser } from "@/lib/auth/cookies";+import { webhookDeliveries, webhooks } from "@/db/schema";+import { parseWebhookEvents } from "@/lib/email/webhooks";+import { summariseDeliveryStats } from "./utils";+import { requireSessionUser } from "@/lib/api/auth";import { newId } from "@/lib/ids";import { webhookSchema } from "@/lib/validators";import { readJsonBody } from "@/lib/http/request";@@ -11,17 +13,46 @@ import { RequestBodyTooLargeError } from "@/lib/http/errors";export async function GET(request: Request) {const env = getEnv();- const user = await requireUser(env, request);+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ const user = auth.user;const db = getDb(env);- const rows = await db.select().from(webhooks).where(eq(webhooks.userId, user.id));+ const rows = await db+ .select()+ .from(webhooks)+ .where(eq(webhooks.userId, user.id))+ .orderBy(desc(webhooks.createdAt));++ // One grouped query gives every endpoint its delivery health without an N+1.+ const stats = await db+ .select({+ webhookId: webhookDeliveries.webhookId,+ status: webhookDeliveries.status,+ total: count(),+ lastAttemptAt: max(webhookDeliveries.lastAttemptAt),+ })+ .from(webhookDeliveries)+ .groupBy(webhookDeliveries.webhookId, webhookDeliveries.status);+return NextResponse.json({- webhooks: rows.map((w) => ({ id: w.id, url: w.url, events: w.events, enabled: w.enabled })),+ webhooks: rows.map((w) => ({+ id: w.id,+ url: w.url,+ description: w.description,+ events: parseWebhookEvents(w.events),+ enabled: w.enabled,+ maxAttempts: w.maxAttempts,+ createdAt: w.createdAt,+ stats: summariseDeliveryStats(stats, w.id),+ })),});}export async function POST(request: Request) {const env = getEnv();- const user = await requireUser(env, request);+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ const user = auth.user;let body: unknown;try {body = await readJsonBody(request, 16 * 1024);@@ -41,10 +72,13 @@ export async function POST(request: Request) {id,userId: user.id,url: parsed.data.url,+ description: parsed.data.description?.trim() || null,secret,events: JSON.stringify(parsed.data.events),enabled: true,+ maxAttempts: parsed.data.maxAttempts,});+ // The signing secret is shown once, at creation time, and never returned again.return NextResponse.json({ id, url: parsed.data.url, secret, events: parsed.data.events });}diff --git a/src/app/api/webhooks/utils.ts b/src/app/api/webhooks/utils.tsnew file mode 100644index 0000000..0c6e7da--- /dev/null+++ b/src/app/api/webhooks/utils.ts@@ -0,0 +1,47 @@+export type DeliveryStatRow = {+ webhookId: string;+ status: string;+ total: number;+ lastAttemptAt: Date | number | null;+};++export type WebhookDeliveryStats = {+ total: number;+ delivered: number;+ failing: number;+ pending: number;+ lastAttemptAt: number | null;+};++/**+ * Aggregate columns bypass Drizzle's timestamp mapper, so `max()` comes back as the raw+ * SQLite value — seconds, since the column uses `mode: "timestamp"`. Normalise to epoch ms.+ */+function toEpochMs(value: Date | number | null | undefined): number | null {+ if (value === null || value === undefined) return null;+ if (value instanceof Date) return value.getTime();+ const numeric = Number(value);+ if (!Number.isFinite(numeric) || numeric <= 0) return null;+ return numeric < 1e12 ? numeric * 1000 : numeric;+}++/** Folds the grouped delivery counts into per-endpoint health for the webhooks list. */+export function summariseDeliveryStats(rows: DeliveryStatRow[], webhookId: string): WebhookDeliveryStats {+ const own = rows.filter((row) => row.webhookId === webhookId);+ const byStatus = (status: string) =>+ own.filter((row) => row.status === status).reduce((sum, row) => sum + row.total, 0);++ const lastAttemptAt = own.reduce<number | null>((latest, row) => {+ const value = toEpochMs(row.lastAttemptAt);+ if (value === null) return latest;+ return latest === null || value > latest ? value : latest;+ }, null);++ return {+ total: own.reduce((sum, row) => sum + row.total, 0),+ delivered: byStatus("delivered"),+ failing: byStatus("failed") + byStatus("exhausted"),+ pending: byStatus("pending") + byStatus("retrying"),+ lastAttemptAt,+ };+}diff --git a/src/lib/email/webhooks.ts b/src/lib/email/webhooks.tsindex d2c0689..5bdd83a 100644--- a/src/lib/email/webhooks.ts+++ b/src/lib/email/webhooks.ts@@ -1,10 +1,45 @@import { eq } from "drizzle-orm";import { getDb } from "@/db";+import type { AppDatabase } from "@/db";import { webhookDeliveries, webhooks } from "@/db/schema";import { newId } from "@/lib/ids";export type WebhookEventType = "message.inbound" | "message.outbound" | "message.failed";+export const WEBHOOK_EVENT_TYPES: WebhookEventType[] = [+ "message.inbound",+ "message.outbound",+ "message.failed",+];++/** Retry work is carried on the existing outbound queue so no new binding is required. */+export type WebhookRetryMessage = {+ kind: "webhook.retry";+ deliveryId: string;+};++export type WebhookDeliveryStatus = "pending" | "delivered" | "failed" | "retrying" | "exhausted";++type WebhookRow = typeof webhooks.$inferSelect;+type DeliveryRow = typeof webhookDeliveries.$inferSelect;++const REQUEST_TIMEOUT_MS = 10_000;+const MAX_RESPONSE_SNIPPET = 500;++/** Exponential backoff, capped at one hour: 1m, 2m, 4m, 8m, 16m... */+export function getRetryDelaySeconds(attempt: number): number {+ return Math.min(60 * 2 ** Math.max(attempt - 1, 0), 3600);+}++export function parseWebhookEvents(events: string): string[] {+ try {+ const parsed = JSON.parse(events);+ return Array.isArray(parsed) ? parsed.filter((e): e is string => typeof e === "string") : [];+ } catch {+ return [];+ }+}+export async function dispatchWebhooks(env: CloudflareEnv,userId: string,@@ -16,48 +51,165 @@ export async function dispatchWebhooks(for (const hook of hooks) {if (!hook.enabled) continue;- let events: string[] = [];- try {- events = JSON.parse(hook.events) as string[];- } catch {- continue;- }- if (!events.includes(eventType)) continue;+ if (!parseWebhookEvents(hook.events).includes(eventType)) continue;- const deliveryId = newId();const body = JSON.stringify({ type: eventType, data: payload });- await db.insert(webhookDeliveries).values({- id: deliveryId,- webhookId: hook.id,- eventType,- payload: body,- status: "pending",- attempts: 0,- });+ const delivery = await createDelivery(db, hook.id, eventType, body);+ await attemptDelivery(env, db, hook, delivery);+ }+}++type PendingDelivery = Pick<DeliveryRow, "id" | "payload" | "eventType" | "attempts">;- try {- const signature = await signPayload(hook.secret, body);- const res = await fetch(hook.url, {- method: "POST",- redirect: "manual",- signal: AbortSignal.timeout(10_000),- headers: {- "Content-Type": "application/json",- "X-Email-Platform-Signature": signature,- "X-Email-Platform-Event": eventType,- },- body,- });- await db- .update(webhookDeliveries)- .set({ status: res.ok ? "delivered" : "failed", attempts: 1 })- .where(eq(webhookDeliveries.id, deliveryId));- } catch {- await db- .update(webhookDeliveries)- .set({ status: "failed", attempts: 1 })- .where(eq(webhookDeliveries.id, deliveryId));+async function createDelivery(+ db: AppDatabase,+ webhookId: string,+ eventType: string,+ payload: string,+): Promise<PendingDelivery> {+ const id = newId("whd");+ await db.insert(webhookDeliveries).values({+ id,+ webhookId,+ eventType,+ payload,+ status: "pending",+ attempts: 0,+ });+ return { id, payload, eventType, attempts: 0 };+}++/** Runs one delivery attempt and records the outcome, scheduling a retry when it fails. */+async function attemptDelivery(+ env: CloudflareEnv,+ db: AppDatabase,+ hook: WebhookRow,+ delivery: PendingDelivery,+): Promise<WebhookDeliveryStatus> {+ const attempts = delivery.attempts + 1;+ const startedAt = Date.now();+ const now = new Date();++ let responseStatus: number | null = null;+ let error: string | null = null;++ try {+ const signature = await signPayload(hook.secret, delivery.payload);+ const res = await fetch(hook.url, {+ method: "POST",+ redirect: "manual",+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ headers: {+ "Content-Type": "application/json",+ "X-Email-Platform-Signature": signature,+ "X-Email-Platform-Event": delivery.eventType,+ "X-Email-Platform-Delivery": delivery.id,+ "X-Email-Platform-Attempt": String(attempts),+ },+ body: delivery.payload,+ });+ responseStatus = res.status;+ if (!res.ok) {+ error = (await readResponseSnippet(res)) || `Endpoint responded with ${res.status}`;}+ } catch (err) {+ error = err instanceof Error ? err.message : "Request failed";+ }++ const durationMs = Date.now() - startedAt;+ const delivered = !error;+ const canRetry = !delivered && attempts < hook.maxAttempts;+ const status: WebhookDeliveryStatus = delivered ? "delivered" : canRetry ? "retrying" : "exhausted";+ const nextRetryAt = canRetry ? new Date(Date.now() + getRetryDelaySeconds(attempts) * 1000) : null;++ await db+ .update(webhookDeliveries)+ .set({+ status,+ attempts,+ responseStatus,+ error: error ? error.slice(0, MAX_RESPONSE_SNIPPET) : null,+ durationMs,+ lastAttemptAt: now,+ nextRetryAt,+ })+ .where(eq(webhookDeliveries.id, delivery.id));++ if (canRetry) {+ await scheduleRetry(env, delivery.id, getRetryDelaySeconds(attempts));+ }++ return status;+}++async function scheduleRetry(env: CloudflareEnv, deliveryId: string, delaySeconds: number): Promise<void> {+ const message: WebhookRetryMessage = { kind: "webhook.retry", deliveryId };+ try {+ await env.OUTBOUND_QUEUE.send(message, { delaySeconds });+ } catch (error) {+ console.error(`Failed to schedule webhook retry for ${deliveryId}`, error);+ }+}++/** Queue consumer entry point for scheduled retries. */+export async function processWebhookRetry(+ env: CloudflareEnv,+ message: WebhookRetryMessage,+): Promise<void> {+ await runDelivery(env, message.deliveryId);+}++/**+ * Runs (or re-runs) a delivery. Used by the retry queue and by the manual retry button.+ * Returns null when the delivery or its webhook no longer exists.+ */+export async function runDelivery(+ env: CloudflareEnv,+ deliveryId: string,+ options?: { userId?: string },+): Promise<{ status: WebhookDeliveryStatus } | null> {+ const db = getDb(env);+ const [delivery] = await db+ .select()+ .from(webhookDeliveries)+ .where(eq(webhookDeliveries.id, deliveryId))+ .limit(1);+ if (!delivery) return null;++ const [hook] = await db.select().from(webhooks).where(eq(webhooks.id, delivery.webhookId)).limit(1);+ if (!hook) return null;+ if (options?.userId && hook.userId !== options.userId) return null;++ return { status: await attemptDelivery(env, db, hook, delivery) };+}++/** Sends a synthetic event so an operator can verify an endpoint from the UI. */+export async function sendTestDelivery(+ env: CloudflareEnv,+ hook: WebhookRow,+): Promise<{ deliveryId: string; status: WebhookDeliveryStatus }> {+ const db = getDb(env);+ const body = JSON.stringify({+ type: "message.inbound",+ test: true,+ data: {+ messageId: "test",+ from: "[email protected]",+ to: "[email protected]",+ subject: "Mailflare test delivery",+ },+ });+ const delivery = await createDelivery(db, hook.id, "message.inbound", body);+ const status = await attemptDelivery(env, db, hook, delivery);+ return { deliveryId: delivery.id, status };+}++async function readResponseSnippet(res: Response): Promise<string> {+ try {+ const text = await res.text();+ return text.trim().slice(0, MAX_RESPONSE_SNIPPET);+ } catch {+ return "";}}diff --git a/worker-utils.ts b/worker-utils.tsindex 3499d8e..b598c94 100644--- a/worker-utils.ts+++ b/worker-utils.ts@@ -1,4 +1,5 @@import type { InboundQueueMessage } from "./src/lib/email/inbound";+import type { WebhookRetryMessage } from "./src/lib/email/webhooks";export function isInboundQueueMessage(payload: unknown): payload is InboundQueueMessage {return (@@ -9,3 +10,12 @@ export function isInboundQueueMessage(payload: unknown): payload is InboundQueue"to" in payload);}++export function isWebhookRetryMessage(payload: unknown): payload is WebhookRetryMessage {+ return (+ typeof payload === "object" &&+ payload !== null &&+ (payload as { kind?: unknown }).kind === "webhook.retry" &&+ typeof (payload as { deliveryId?: unknown }).deliveryId === "string"+ );+}