Files
pn-new-crm/src/app/(dashboard)/[portSlug]/admin/webhooks/page.tsx
Matt ebdd8408bf fix(audit-wave-11): dossier sweep — error-ux + webhook + storage + search + maintainability
Final pass over the unaddressed AUDIT-2026-05-12 dossiers, taking the
tractable Critical/High items from each:

error-ux-auditor (5 items)
- C2: 17 toast.error(err.message) sites swept to toastError(err, …) so
  every user-visible failure carries a copy-paste Reference ID
- C3: apiFetch synthesizes a client-side correlation id when a 5xx
  comes back with a non-JSON body (reverse-proxy HTML pages); message
  becomes "The server is unreachable. Please try again." with code
  UPSTREAM_UNREACHABLE
- C4: checkRateLimit fails OPEN when Redis is unavailable so an outage
  no longer 500s login + portal sign-in; logged at warn so monitoring
  catches it
- H2: StorageTimeoutError (name='TimeoutError') replaces the plain
  Error throw in s3.ts withTimeout — error-classifier hints fire now
- H5: errorResponse() adopted across /api/storage/[token],
  /api/public/website-inquiries, and the Documenso webhook body (drops
  the "Invalid secret" reconnaissance string)

outbound-webhook-auditor (5 items)
- C1: signature is now HMAC(secret, `${ts}.${body}`) with the
  timestamp surfaced as X-Webhook-Timestamp so receivers can reject
  replays outside a freshness window
- C3: dead-letter with reason missing_signing_secret when secret is
  null (defence-in-depth against DB tampering / future migration
  mistakes)
- H2: webhooks queue bumped to maxAttempts=8 with 30 s base
  exponential backoff so a 30 s receiver blip during a deploy no
  longer dead-letters every in-flight event; per-queue
  backoffDelayMs added to QUEUE_CONFIGS
- M1: SSRF denylist gains Oracle Cloud metadata 192.0.0.192
- M2: dispatch-time https:// assertion before fetch, so a bad DB edit
  can't slip plaintext through

storage-pathing-auditor (2 items)
- H1: berth-PDF presigned-upload keys now `${portSlug}/berths/…/…`
  with portSlug threaded into backend.presignUpload — engages the
  filesystem-proxy port-binding `p` token verifier
- H2: presignDownloadUrl auto-derives portSlug from the key's first
  segment when callers don't pass it, so all 8 download sites engage
  the `p`-token guard without per-site plumbing

search-auditor (1 item)
- H3: removed dead void wantEmail; void wantPhone; pair plus the
  unused looksLikeEmail helper — the bucket-reorder it was scaffolded
  for was never wired

maintainability-auditor (1 item)
- M2: swept seven abandoned `void <symbol>` markers and their dead
  imports across clients/bulk, interests/bulk, admin/email-templates,
  admin/website-submissions, alert-rules, and notes.service

Deferred to future work (substantial refactors, schema migrations, or
multi-file UI work):
- error-ux M3-M8 (global-error.tsx, per-route loading.tsx coverage,
  ErrorBanner component, /api/ready route, worker DLQ admin surface)
- maintainability C1-C4 (documents/search/notes service splits,
  interest-tabs split — multi-hour refactors)
- currency C1-H5 (mixed-currency dashboard aggregation, FX history
  table, rounding policy) — wait for second non-USD port
- outbound-webhook C2 (deliveries reaper job), H1 (DNS-rebind TOCTOU
  with undici Agent), H3 (circuit-breaker), H5 (presigned-post-policy)
- storage-pathing C2 (orphan reaper), H3-H5 (streaming + content-type
  binding)

Tests: 1315/1315 vitest  ; tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 13:27:32 +02:00

268 lines
9.1 KiB
TypeScript

'use client';
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { PageHeader } from '@/components/shared/page-header';
import { Badge } from '@/components/ui/badge';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { WebhookForm } from '@/components/admin/webhooks/webhook-form';
import { WebhookDeliveryLog } from '@/components/admin/webhooks/webhook-delivery-log';
import { WebhookSecretDisplay } from '@/components/admin/webhooks/webhook-secret-display';
interface Webhook {
id: string;
name: string;
url: string;
events: string[];
isActive: boolean;
secretMasked: string;
createdAt: string;
}
const WEBHOOKS_QUERY_KEY = ['admin', 'webhooks'] as const;
export default function WebhooksPage() {
const queryClient = useQueryClient();
const [formOpen, setFormOpen] = useState(false);
const [editTarget, setEditTarget] = useState<Webhook | null>(null);
const [deleteTarget, setDeleteTarget] = useState<Webhook | null>(null);
const [expandedId, setExpandedId] = useState<string | null>(null);
const [regenerating, setRegenerating] = useState<string | null>(null);
const [newSecret, setNewSecret] = useState<{
webhookId: string;
secret: string;
masked: string;
} | null>(null);
const { data: webhooks = [], isLoading: loading } = useQuery<Webhook[]>({
queryKey: WEBHOOKS_QUERY_KEY,
queryFn: () => apiFetch<{ data: Webhook[] }>('/api/v1/admin/webhooks').then((r) => r.data),
});
const loadWebhooks = () => queryClient.invalidateQueries({ queryKey: WEBHOOKS_QUERY_KEY });
async function handleDelete() {
if (!deleteTarget) return;
try {
await apiFetch(`/api/v1/admin/webhooks/${deleteTarget.id}`, { method: 'DELETE' });
setDeleteTarget(null);
toast.success('Webhook deleted');
void loadWebhooks();
} catch (err) {
toastError(err, 'Failed to delete webhook');
}
}
async function handleRegenerate(webhookId: string) {
setRegenerating(webhookId);
try {
const result = await apiFetch<{ data: { secret: string; secretMasked: string } }>(
`/api/v1/admin/webhooks/${webhookId}/regenerate-secret`,
{ method: 'POST' },
);
setNewSecret({ webhookId, secret: result.data.secret, masked: result.data.secretMasked });
void loadWebhooks();
} catch (err) {
toastError(err, 'Failed to regenerate secret');
} finally {
setRegenerating(null);
}
}
async function handleToggleActive(webhook: Webhook) {
try {
await apiFetch(`/api/v1/admin/webhooks/${webhook.id}`, {
method: 'PATCH',
body: { isActive: !webhook.isActive },
});
toast.success(webhook.isActive ? 'Webhook disabled' : 'Webhook enabled');
void loadWebhooks();
} catch (err) {
toastError(err, 'Failed to toggle webhook');
}
}
function toggleExpand(id: string) {
setExpandedId((prev) => (prev === id ? null : id));
}
return (
<div className="space-y-6">
<PageHeader
title="Webhooks"
description="Configure outgoing webhook integrations"
actions={
<Button
onClick={() => {
setEditTarget(null);
setFormOpen(true);
}}
>
Add Webhook
</Button>
}
/>
{loading ? (
<p className="text-sm text-muted-foreground">Loading...</p>
) : webhooks.length === 0 ? (
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12">
<p className="text-lg font-medium text-muted-foreground">No webhooks configured</p>
<p className="text-sm text-muted-foreground mt-1">
Add a webhook to receive real-time notifications of CRM events.
</p>
<Button
className="mt-4"
onClick={() => {
setEditTarget(null);
setFormOpen(true);
}}
>
Add Webhook
</Button>
</div>
) : (
<div className="space-y-2">
{webhooks.map((webhook) => (
<div key={webhook.id} className="rounded-lg border bg-card">
<div className="flex items-center gap-4 p-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium truncate">{webhook.name}</span>
<Badge variant={webhook.isActive ? 'default' : 'secondary'}>
{webhook.isActive ? 'Active' : 'Inactive'}
</Badge>
</div>
<p className="text-xs text-muted-foreground font-mono truncate mt-0.5">
{webhook.url}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{webhook.events.length} event{webhook.events.length !== 1 ? 's' : ''}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button variant="ghost" size="sm" onClick={() => handleToggleActive(webhook)}>
{webhook.isActive ? 'Disable' : 'Enable'}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setEditTarget(webhook);
setFormOpen(true);
}}
>
Edit
</Button>
<Button
variant="ghost"
size="sm"
className="text-destructive"
onClick={() => setDeleteTarget(webhook)}
>
Delete
</Button>
<Button variant="ghost" size="sm" onClick={() => toggleExpand(webhook.id)}>
{expandedId === webhook.id ? 'Collapse' : 'Details'}
</Button>
</div>
</div>
{expandedId === webhook.id && (
<div className="border-t px-4 py-4 space-y-6">
{/* Events */}
<div>
<h3 className="text-sm font-medium mb-2">Subscribed Events</h3>
<div className="flex flex-wrap gap-1">
{webhook.events.map((e) => (
<Badge key={e} variant="outline" className="font-mono text-xs">
{e}
</Badge>
))}
</div>
</div>
{/* Secret */}
<div>
<h3 className="text-sm font-medium mb-2">Signing Secret</h3>
{newSecret?.webhookId === webhook.id ? (
<WebhookSecretDisplay
plaintext={newSecret.secret}
masked={newSecret.masked}
/>
) : (
<WebhookSecretDisplay masked={webhook.secretMasked} />
)}
<Button
variant="outline"
size="sm"
className="mt-2"
disabled={regenerating === webhook.id}
onClick={() => handleRegenerate(webhook.id)}
>
{regenerating === webhook.id ? 'Regenerating...' : 'Regenerate Secret'}
</Button>
</div>
{/* Delivery Log */}
<div>
<h3 className="text-sm font-medium mb-2">Delivery Log</h3>
<WebhookDeliveryLog webhookId={webhook.id} />
</div>
</div>
)}
</div>
))}
</div>
)}
<WebhookForm
open={formOpen}
onOpenChange={setFormOpen}
webhook={editTarget}
onSuccess={loadWebhooks}
/>
<AlertDialog
open={!!deleteTarget}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null);
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Webhook</AlertDialogTitle>
<AlertDialogDescription>
Delete &quot;{deleteTarget?.name}&quot;? This will also delete all delivery history.
This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}