'use client' import * as React from 'react' import type { WebhookEndpointListItem } from '@admin/actions/webhooks' import { createWebhook, getWebhookSecret, regenerateWebhookSecret, updateWebhook } from '@admin/actions/webhooks' import { Alert, AlertDescription } from '@admin/components/ui/alert' import { Button } from '@admin/components/ui/button' import { Checkbox } from '@admin/components/ui/checkbox' import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTitle } from '@admin/components/ui/drawer' import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@admin/components/ui/form' import { Input } from '@admin/components/ui/input' import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@admin/components/ui/input-group' import { ScrollArea } from '@admin/components/ui/scroll-area' import { Spinner } from '@admin/components/ui/spinner' import { Switch } from '@admin/components/ui/switch' import { Toggle } from '@admin/components/ui/toggle' import { webhookEventSources } from '@admin/data/webhook-events' import { useCopyToClipboard } from '@admin/hooks/use-copy-to-clipboard' import { useSendTestWebhook, useWebhookSubscriptions } from '@admin/hooks/use-webhooks' import { cn } from '@admin/utils/shared/cn' import { standardSchemaResolver } from '@hookform/resolvers/standard-schema' import { useMutation, useQueryClient } from '@tanstack/react-query' import { Check, Copy, Eye, EyeClosed, KeyRound, X } from 'lucide-react' import { useForm, useWatch } from 'react-hook-form' import { toast } from 'sonner' import { z } from 'zod/v3' import { WebhookEventPicker } from './webhook-event-picker' const endpointSchema = z.object({ name: z.string().trim().min(1, 'Name is required').max(200, 'Name is too long'), url: z.string().trim().url('Enter a valid URL'), enabled: z.boolean(), events: z.array(z.string()), sendTest: z.boolean() }) type EndpointFormValues = z.infer interface WebhookEndpointDrawerProps { webhook: WebhookEndpointListItem | null open: boolean onOpenChange: (open: boolean) => void } export function WebhookEndpointDrawer({ webhook, open, onOpenChange }: WebhookEndpointDrawerProps) { const queryClient = useQueryClient() const isEdit = webhook !== null const { data: subscriptions } = useWebhookSubscriptions() const subscribedEvents = React.useMemo( () => webhook ? (subscriptions ?? []) .filter((entry) => entry.webhookId === webhook.id) .map((entry) => entry.event) : [], [subscriptions, webhook] ) const [secret, setSecret] = React.useState(null) const [secretVisible, setSecretVisible] = React.useState(false) const sendTest = useSendTestWebhook() const [copySecret, isSecretCopied] = useCopyToClipboard() const form = useForm({ resolver: standardSchemaResolver(endpointSchema), defaultValues: { name: webhook?.name ?? '', url: webhook?.url ?? '', enabled: webhook?.enabled ?? true, events: subscribedEvents, sendTest: !isEdit } }) const events = useWatch({ control: form.control, name: 'events' }) React.useEffect(() => { if (!open) return form.reset({ name: webhook?.name ?? '', url: webhook?.url ?? '', enabled: webhook?.enabled ?? true, events: subscribedEvents, sendTest: webhook === null }) setSecret(null) setSecretVisible(false) }, [form, open, subscribedEvents, webhook]) const saveMutation = useMutation({ mutationFn: async (values: EndpointFormValues) => { const endpointValues = { name: values.name, url: values.url, enabled: values.enabled, events: values.events } const result = webhook ? await updateWebhook(webhook.id, endpointValues) : await createWebhook(endpointValues) if (!result.success) { throw new Error(result.error || 'Failed to save this webhook') } return { result, sendTest: !webhook && values.sendTest } }, onSuccess: async ({ result, sendTest: shouldSendTest }) => { toast.success(isEdit ? 'Webhook saved' : 'Webhook created') await queryClient.invalidateQueries({ queryKey: ['webhooks'] }) await queryClient.invalidateQueries({ queryKey: ['webhook-subscriptions'] }) onOpenChange(false) if (shouldSendTest && result.webhook) { sendTest.mutate(result.webhook.id) } }, onError: (error: Error) => { toast.error(error.message || 'Failed to save this webhook') } }) const revealSecretMutation = useMutation({ mutationFn: async () => { if (!webhook) throw new Error('Save this webhook first.') const result = await getWebhookSecret(webhook.id) if (!result.success || !result.secret) { throw new Error(result.error || 'Failed to fetch signing secret') } return result.secret }, onSuccess: (value) => setSecret(value), onError: (error: Error) => { setSecretVisible(false) toast.error(error.message || 'Failed to fetch signing secret') } }) const regenerateSecretMutation = useMutation({ mutationFn: async () => { if (!webhook) throw new Error('Save this webhook first.') const result = await regenerateWebhookSecret(webhook.id) if (!result.success || !result.secret) { throw new Error(result.error || 'Failed to regenerate signing secret') } return result.secret }, onSuccess: (value) => { setSecret(value) setSecretVisible(true) toast.success('Signing secret regenerated') }, onError: (error: Error) => { toast.error(error.message || 'Failed to regenerate signing secret') } }) const isPending = saveMutation.isPending async function handleCopySecret() { let value = secret if (value === null) { try { value = await revealSecretMutation.mutateAsync() } catch { return } } if (!(await copySecret(value))) { toast.error('Failed to copy signing secret') } } function setEvents(nextEvents: string[]) { form.setValue('events', nextEvents, { shouldDirty: true, shouldValidate: true }) } function toggleEvent(event: string, checked: boolean) { const currentEvents = form.getValues('events') setEvents( checked ? currentEvents.includes(event) ? currentEvents : [...currentEvents, event] : currentEvents.filter((entry) => entry !== event) ) } function toggleEvents(eventsToToggle: string[], checked: boolean) { const currentEvents = form.getValues('events') setEvents( checked ? [...new Set([...currentEvents, ...eventsToToggle])] : currentEvents.filter((entry) => !eventsToToggle.includes(entry)) ) } return (
saveMutation.mutate(values))} > {isEdit ? `Edit webhook — ${webhook.name}` : 'Add endpoint'} } aria-label="Close" >
( Name )} /> ( URL )} /> ( Enabled )} /> {isEdit ? (

Signing secret

{ setSecretVisible(pressed) if (pressed && secret === null) revealSecretMutation.mutate() }} > {revealSecretMutation.isPending ? ( ) : secretVisible ? ( ) : ( )} {isSecretCopied ? : }
) : ( Every request carries x-webhook-signature, an HMAC-SHA256 of the timestamp and body )}
( )} />
{isEdit ? ( ) : ( ( field.onChange(checked === true)} /> Send a test delivery )} /> )}
}> Cancel
) }