From bfd39b6d8b5b8a0c68a8e09d4375229f8a77ed10 Mon Sep 17 00:00:00 2001 From: Georgy Butaev <41178744+g-but@users.noreply.github.com> Date: Thu, 4 Jun 2026 01:47:50 +0200 Subject: [PATCH] feat(settings): manual replay button for failed webhook deliveries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The deliveries drawer now shows operators a failed delivery + its payload + the receiver response (b6c3fe80), but offered no action — they'd have to flip a DB row by hand to retry. This commit closes the last natural follow-up on the webhook UI loop. Service: - enqueueDeliveryReplay(id) resets attempt_count=0, status='pending', response_status/body cleared, next_attempt_at=now. The exp-backoff schedule starts fresh — semantics match Stripe's manual-retry behaviour ("treat as a brand-new delivery for retry-budget"). - deliveryBelongsToEndpoint(deliveryId, endpointId) — fail-closed ownership check used by the route to avoid leaking deliveries across endpoint boundaries. Route POST /api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay: - Supabase session only (integration keys shouldn't be able to nudge their own delivery queue — same escalation argument as elsewhere) - Authorises via userOwnsEndpoint THEN deliveryBelongsToEndpoint - 404 on either mismatch (no probing the endpoint or delivery ID space) - 500 on service failure UI in WebhookDeliveriesDrawer: - Replay button rendered in the expanded section above Sent payload - Spinning RotateCcw icon during the request, disabled while replaying - On success, reloads the deliveries list — the worker may already have moved the row by the time the user looks again 47 suites · 610 tests · 0 failures. tsc + eslint clean. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../deliveries/[deliveryId]/replay/route.ts | 72 +++++++++++++++++++ .../settings/WebhookDeliveriesDrawer.tsx | 49 ++++++++++++- src/services/webhooks/deliveryService.ts | 61 ++++++++++++++++ 3 files changed, 181 insertions(+), 1 deletion(-) create mode 100644 src/app/api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay/route.ts diff --git a/src/app/api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay/route.ts b/src/app/api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay/route.ts new file mode 100644 index 000000000..2a43d6278 --- /dev/null +++ b/src/app/api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay/route.ts @@ -0,0 +1,72 @@ +/** + * POST /api/webhook-endpoints/[id]/deliveries/[deliveryId]/replay + * + * Operator-only manual replay of a single delivery. The /api/cron/ + * webhook-worker handles automatic retries with exp-backoff; this + * route is for when an operator looks at a failed delivery in the + * /settings/integrations drawer and wants to nudge it through after + * fixing the receiver. + * + * Auth: Supabase session only (an integration key shouldn't be able + * to influence its own delivery queue — same escalation argument as + * elsewhere). Returns 404 on endpoint OR delivery mismatch to avoid + * leaking either ID space to probers. + * + * Effect: resets attempt_count to 0, status to 'pending', + * next_attempt_at to now. The worker picks it up on the next minute. + * + * Created: 2026-06-04 + */ + +import { NextRequest } from 'next/server'; +import { createServerClient } from '@/lib/supabase/server'; +import { + apiSuccess, + apiUnauthorized, + apiNotFound, + apiError, + handleApiError, +} from '@/lib/api/standardResponse'; +import { userOwnsEndpoint } from '@/services/webhooks/webhookEndpointsService'; +import { + deliveryBelongsToEndpoint, + enqueueDeliveryReplay, +} from '@/services/webhooks/deliveryService'; + +export async function POST( + _req: NextRequest, + { params }: { params: Promise<{ id: string; deliveryId: string }> } +) { + try { + const supabase = await createServerClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) { + return apiUnauthorized(); + } + + const { id: endpointId, deliveryId } = await params; + + const owns = await userOwnsEndpoint(endpointId, user.id); + if (!owns) { + return apiNotFound('Webhook endpoint'); + } + + const belongs = await deliveryBelongsToEndpoint(deliveryId, endpointId); + if (!belongs) { + // Same 404 envelope so probers can't tell endpoint-mismatch from + // delivery-mismatch from never-existed. + return apiNotFound('Webhook delivery'); + } + + const replayed = await enqueueDeliveryReplay(deliveryId); + if (!replayed) { + return apiError('Replay failed', 'INTERNAL_ERROR', 500); + } + + return apiSuccess({ replayed: true }); + } catch (error) { + return handleApiError(error); + } +} diff --git a/src/components/settings/WebhookDeliveriesDrawer.tsx b/src/components/settings/WebhookDeliveriesDrawer.tsx index 5464ec12b..4b4bc0819 100644 --- a/src/components/settings/WebhookDeliveriesDrawer.tsx +++ b/src/components/settings/WebhookDeliveriesDrawer.tsx @@ -13,7 +13,15 @@ */ import { useCallback, useEffect, useRef, useState } from 'react'; -import { CheckCircle2, ChevronDown, ChevronRight, Clock, RefreshCw, XCircle } from 'lucide-react'; +import { + CheckCircle2, + ChevronDown, + ChevronRight, + Clock, + RefreshCw, + RotateCcw, + XCircle, +} from 'lucide-react'; import { logger } from '@/utils/logger'; interface DeliveryRow { @@ -80,6 +88,7 @@ export default function WebhookDeliveriesDrawer({ endpointId }: Props) { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [expandedId, setExpandedId] = useState(null); + const [replayingId, setReplayingId] = useState(null); const cancelRef = useRef(false); const load = useCallback(async () => { @@ -109,6 +118,31 @@ export default function WebhookDeliveriesDrawer({ endpointId }: Props) { } }, [endpointId]); + const handleReplay = useCallback( + async (deliveryId: string) => { + setReplayingId(deliveryId); + setError(null); + try { + const res = await fetch( + `/api/webhook-endpoints/${endpointId}/deliveries/${deliveryId}/replay`, + { method: 'POST', credentials: 'include' } + ); + if (!res.ok) { + const body = (await res.json().catch(() => null)) as { error?: string } | null; + throw new Error(body?.error || `Failed to replay (${res.status})`); + } + // Reload — the row's status, attempt_count, next_attempt_at all + // changed and the worker may already have moved it. + await load(); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to replay'); + } finally { + setReplayingId(null); + } + }, + [endpointId, load] + ); + useEffect(() => { load(); return () => { @@ -183,6 +217,19 @@ export default function WebhookDeliveriesDrawer({ endpointId }: Props) { {isExpanded && (
+
+ +
Sent payload diff --git a/src/services/webhooks/deliveryService.ts b/src/services/webhooks/deliveryService.ts index 76c6580bc..ad653967e 100644 --- a/src/services/webhooks/deliveryService.ts +++ b/src/services/webhooks/deliveryService.ts @@ -256,6 +256,67 @@ export async function pruneDeliveredWebhookDeliveries( return count ?? 0; } +/** + * Confirm a delivery row belongs to the given endpoint. Used by the + * replay route to avoid leaking deliveries across endpoint boundaries. + * Returns false on mismatch + on any DB error (fail-closed). + */ +export async function deliveryBelongsToEndpoint( + deliveryId: string, + endpointId: string +): Promise { + const admin = createAdminClient(); + const { data, error } = await admin + .from(DATABASE_TABLES.WEBHOOK_DELIVERIES) + .select('id') + .eq('id', deliveryId) + .eq('endpoint_id', endpointId) + .maybeSingle(); + if (error) { + logger.warn('deliveryBelongsToEndpoint: query failed', { error, deliveryId, endpointId }); + return false; + } + return !!data; +} + +/** + * Manually re-enqueue a delivery. Wipes response_status + response_body + * so the next worker run starts clean, resets attempt_count to 0 (the + * exp-backoff schedule starts fresh), flips status back to 'pending', + * and schedules next_attempt_at=now so the next /api/cron/webhook-worker + * tick (every minute) picks it up. + * + * The user-facing semantics are "treat this as a brand-new delivery + * for retry-budget purposes." That keeps the contract obvious in the + * UI ("Replay" button) and matches how Stripe + similar platforms + * surface manual retries. + * + * The caller MUST have already verified the delivery belongs to an + * endpoint the requesting user owns — this function trusts ownership. + */ +export async function enqueueDeliveryReplay(deliveryId: string): Promise { + const admin = createAdminClient(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const { data, error } = await (admin.from(DATABASE_TABLES.WEBHOOK_DELIVERIES) as any) + .update({ + status: 'pending', + attempt_count: 0, + response_status: null, + response_body: null, + last_attempt_at: null, + next_attempt_at: new Date().toISOString(), + }) + .eq('id', deliveryId) + .select('id') + .maybeSingle(); + + if (error) { + logger.error('enqueueDeliveryReplay failed', { error, deliveryId }); + return false; + } + return !!data; +} + export async function markFailedOrRetry( delivery: DeliveryRow, responseStatus: number | null,