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,