mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 17:27:24 +01:00
feat(settings): per-endpoint webhook deliveries drawer
eefbcba5deferred this to a follow-up. Today customers can mint webhook endpoints and watch them fire (via 2755a8a5's worker), but /settings/integrations gives them zero visibility into outcomes — they have to query the DB to see whether a delivery succeeded or sat retrying for hours. This commit closes the loop. API: - GET /api/webhook-endpoints/[id]/deliveries Supabase session only (operator surface, not an integration path). Authorises via the new userOwnsEndpoint() — 404 on mismatch to avoid leaking endpoint existence. ?limit= caps at 100, defaults 50. Service: - listRecentDeliveriesForEndpoint(endpointId, limit) Returns newest-first webhook_deliveries rows for one endpoint. The (endpoint_id, created_at DESC) index from211188a3is the hot path. - userOwnsEndpoint(endpointId, userId) Lightweight authorisation check. Returns true for revoked endpoints too — the operator should still be able to review past deliveries for an endpoint they once owned. UI: - WebhookDeliveriesDrawer (new component, ~165 LOC) Lazy-fetches on first open. Status badge (Delivered/Failed/Pending with green/red/grey colours + matching icons), event_type code chip, HTTP status, attempt count when > 1, enqueued/last-attempt/ next-retry timestamps. Manual Refresh button with spinning icon — no auto-refresh (operators reach for this during incidents, not steady-state monitoring). - WebhookEndpointsCard gains a "Deliveries" toggle on each row that expands the drawer inline. Only one endpoint expanded at a time (expandedEndpointId state — keeps the page short, focuses attention). Not in scope this commit: payload preview drawer, search/filter, manual replay button. All callable from the dedicated endpoint view when we eventually have one. 47 suites · 610 tests · 0 failures. tsc + eslint clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
0a9a9f43ad
commit
246216a47d
5 files changed
+333
-29
No files matched your search
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* GET /api/webhook-endpoints/[id]/deliveries
|
||||
*
|
||||
* Lists the most recent deliveries for one endpoint so the
|
||||
* /settings/integrations deliveries drawer can show status, attempt
|
||||
* count, response code, timestamps.
|
||||
*
|
||||
* Auth: Supabase session only — the deliveries drawer is a human
|
||||
* operator view, not an integration surface. We re-use the
|
||||
* ownership check from webhookEndpointsService (404 on mismatch to
|
||||
* avoid leaking endpoint existence to probers).
|
||||
*
|
||||
* Created: 2026-06-04
|
||||
*/
|
||||
|
||||
import { NextRequest } from 'next/server';
|
||||
import { createServerClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
apiSuccess,
|
||||
apiUnauthorized,
|
||||
apiNotFound,
|
||||
handleApiError,
|
||||
} from '@/lib/api/standardResponse';
|
||||
import { listRecentDeliveriesForEndpoint } from '@/services/webhooks/deliveryService';
|
||||
import { userOwnsEndpoint } from '@/services/webhooks/webhookEndpointsService';
|
||||
|
||||
const MAX_LIMIT = 100;
|
||||
const DEFAULT_LIMIT = 50;
|
||||
|
||||
function parseLimit(url: string): number {
|
||||
try {
|
||||
const param = new URL(url).searchParams.get('limit');
|
||||
if (!param) {
|
||||
return DEFAULT_LIMIT;
|
||||
}
|
||||
const parsed = Number.parseInt(param, 10);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return DEFAULT_LIMIT;
|
||||
}
|
||||
return Math.min(parsed, MAX_LIMIT);
|
||||
} catch {
|
||||
return DEFAULT_LIMIT;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const supabase = await createServerClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return apiUnauthorized();
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const owns = await userOwnsEndpoint(id, user.id);
|
||||
if (!owns) {
|
||||
return apiNotFound('Webhook endpoint');
|
||||
}
|
||||
|
||||
const limit = parseLimit(req.url);
|
||||
const deliveries = await listRecentDeliveriesForEndpoint(id, limit);
|
||||
|
||||
return apiSuccess({ deliveries });
|
||||
} catch (error) {
|
||||
return handleApiError(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* Inline deliveries drawer rendered below a webhook endpoint row when
|
||||
* the user clicks "Deliveries". Fetches lazily on first open, exposes
|
||||
* a manual refresh button, and shows status + attempt count + response
|
||||
* status + timestamps so the operator can diagnose without leaving
|
||||
* /settings/integrations.
|
||||
*
|
||||
* Not real-time. Auto-refresh is intentionally out of scope here —
|
||||
* webhook delivery is the kind of thing operators reach for during
|
||||
* incident response, not steady-state monitoring.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { CheckCircle2, Clock, RefreshCw, XCircle } from 'lucide-react';
|
||||
import { logger } from '@/utils/logger';
|
||||
|
||||
interface DeliveryRow {
|
||||
id: string;
|
||||
endpoint_id: string;
|
||||
event_type: string;
|
||||
event_id: string;
|
||||
payload: unknown;
|
||||
status: 'pending' | 'delivered' | 'failed';
|
||||
response_status: number | null;
|
||||
response_body: string | null;
|
||||
attempt_count: number;
|
||||
last_attempt_at: string | null;
|
||||
next_attempt_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
endpointId: string;
|
||||
}
|
||||
|
||||
function formatTimestamp(value: string | null): string {
|
||||
if (!value) {
|
||||
return '—';
|
||||
}
|
||||
return new Date(value).toLocaleString();
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: DeliveryRow['status'] }) {
|
||||
if (status === 'delivered') {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded bg-emerald-100 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-emerald-800">
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
Delivered
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === 'failed') {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-destructive">
|
||||
<XCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
Pending
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function WebhookDeliveriesDrawer({ endpointId }: Props) {
|
||||
const [deliveries, setDeliveries] = useState<DeliveryRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const cancelRef = useRef(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
cancelRef.current = false;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch(`/api/webhook-endpoints/${endpointId}/deliveries`, {
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to load deliveries (${res.status})`);
|
||||
}
|
||||
const json = (await res.json()) as { data: { deliveries: DeliveryRow[] } };
|
||||
if (!cancelRef.current) {
|
||||
setDeliveries(json.data?.deliveries ?? []);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('Failed to load webhook deliveries', { err });
|
||||
if (!cancelRef.current) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load deliveries');
|
||||
}
|
||||
} finally {
|
||||
if (!cancelRef.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [endpointId]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
return () => {
|
||||
cancelRef.current = true;
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
return (
|
||||
<div className="mt-3 rounded-md border border-border-subtle bg-muted/20 p-3">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<h4 className="text-xs font-medium text-foreground">Recent deliveries</h4>
|
||||
<button
|
||||
type="button"
|
||||
onClick={load}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2 py-1 text-[11px] text-muted-foreground hover:bg-muted/60 hover:text-foreground disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`h-3 w-3 ${loading ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-2 rounded border border-destructive/30 bg-destructive/5 px-2 py-1 text-xs text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && deliveries.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">Loading…</p>
|
||||
) : deliveries.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
No deliveries yet. The next entity create on this actor will fire here.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-border-subtle">
|
||||
{deliveries.map(d => (
|
||||
<li
|
||||
key={d.id}
|
||||
className="flex flex-wrap items-start justify-between gap-2 py-2 text-xs"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge status={d.status} />
|
||||
<code className="rounded bg-muted px-1 text-[10px]">{d.event_type}</code>
|
||||
{d.response_status !== null && (
|
||||
<span className="text-muted-foreground">HTTP {d.response_status}</span>
|
||||
)}
|
||||
{d.attempt_count > 1 && (
|
||||
<span className="text-muted-foreground">attempt {d.attempt_count}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted-foreground">
|
||||
<span>Enqueued {formatTimestamp(d.created_at)}</span>
|
||||
<span>Last attempt {formatTimestamp(d.last_attempt_at)}</span>
|
||||
{d.status === 'pending' && d.next_attempt_at && (
|
||||
<span>Next retry {formatTimestamp(d.next_attempt_at)}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,9 +10,10 @@
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Copy, Plus, Trash2 } from 'lucide-react';
|
||||
import { ChevronDown, ChevronRight, Copy, Plus, Trash2 } from 'lucide-react';
|
||||
import Button from '@/components/ui/Button';
|
||||
import { logger } from '@/utils/logger';
|
||||
import WebhookDeliveriesDrawer from '@/components/settings/WebhookDeliveriesDrawer';
|
||||
|
||||
interface WebhookEndpoint {
|
||||
id: string;
|
||||
@@ -57,6 +58,7 @@ export default function WebhookEndpointsCard({ actors, defaultActorId }: Props)
|
||||
const [minting, setMinting] = useState(false);
|
||||
const [mintedSecret, setMintedSecret] = useState<string | null>(null);
|
||||
const [mintedPrefix, setMintedPrefix] = useState<string | null>(null);
|
||||
const [expandedEndpointId, setExpandedEndpointId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedActorId && defaultActorId) {
|
||||
@@ -269,41 +271,58 @@ export default function WebhookEndpointsCard({ actors, defaultActorId }: Props)
|
||||
<ul className="divide-y divide-border-subtle">
|
||||
{endpoints.map(endpoint => {
|
||||
const isRevoked = !!endpoint.revoked_at;
|
||||
const isExpanded = expandedEndpointId === endpoint.id;
|
||||
const actorLabel =
|
||||
actors.find(a => a.actor_id === endpoint.actor_id)?.label ?? endpoint.actor_id;
|
||||
return (
|
||||
<li
|
||||
key={endpoint.id}
|
||||
className="flex flex-wrap items-start justify-between gap-3 p-4"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-foreground">{endpoint.name}</span>
|
||||
{isRevoked && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">
|
||||
Revoked
|
||||
<li key={endpoint.id} className="p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-foreground">{endpoint.name}</span>
|
||||
{isRevoked && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">
|
||||
Revoked
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
|
||||
<span className="truncate max-w-full sm:max-w-xs">
|
||||
<code className="rounded bg-muted px-1">{endpoint.url}</code>
|
||||
</span>
|
||||
<span>Acts as {actorLabel}</span>
|
||||
<span>Created {formatTimestamp(endpoint.created_at)}</span>
|
||||
<span>Last delivery {formatTimestamp(endpoint.last_delivery_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setExpandedEndpointId(prev => (prev === endpoint.id ? null : endpoint.id))
|
||||
}
|
||||
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-muted/60 hover:text-foreground"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<ChevronRight className="h-3.5 w-3.5" />
|
||||
)}
|
||||
Deliveries
|
||||
</button>
|
||||
{!isRevoked && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRevoke(endpoint)}
|
||||
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-muted/60 hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
Revoke
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
|
||||
<span className="truncate max-w-full sm:max-w-xs">
|
||||
<code className="rounded bg-muted px-1">{endpoint.url}</code>
|
||||
</span>
|
||||
<span>Acts as {actorLabel}</span>
|
||||
<span>Created {formatTimestamp(endpoint.created_at)}</span>
|
||||
<span>Last delivery {formatTimestamp(endpoint.last_delivery_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{!isRevoked && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRevoke(endpoint)}
|
||||
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-muted/60 hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
Revoke
|
||||
</button>
|
||||
)}
|
||||
{isExpanded && <WebhookDeliveriesDrawer endpointId={endpoint.id} />}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -128,6 +128,31 @@ export async function enqueueWebhookEvent(params: {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List the most recent deliveries for a single endpoint. Powers the
|
||||
* /settings/integrations deliveries drawer. Caller MUST have already
|
||||
* verified the endpoint belongs to the requesting user (route does this
|
||||
* with a join through webhook_endpoints.user_id).
|
||||
*/
|
||||
export async function listRecentDeliveriesForEndpoint(
|
||||
endpointId: string,
|
||||
limit: number = 50
|
||||
): Promise<DeliveryRow[]> {
|
||||
const admin = createAdminClient();
|
||||
const { data, error } = await admin
|
||||
.from(DATABASE_TABLES.WEBHOOK_DELIVERIES)
|
||||
.select('*')
|
||||
.eq('endpoint_id', endpointId)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(limit);
|
||||
|
||||
if (error) {
|
||||
logger.error('listRecentDeliveriesForEndpoint: query failed', { error, endpointId });
|
||||
return [];
|
||||
}
|
||||
return (data ?? []) as DeliveryRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick up to `limit` deliveries that are due now. The worker calls this
|
||||
* once per cron invocation; rows are returned newest-first so a slow
|
||||
|
||||
@@ -187,6 +187,28 @@ export async function getEndpointSigningContext(
|
||||
return { url: row.url, secret: row.secret_plaintext, actorId: row.actor_id };
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorisation check for endpoint-scoped routes (deliveries drawer
|
||||
* etc.): does this endpoint exist AND belong to the caller? Returns
|
||||
* true even when the endpoint is revoked — the user can still review
|
||||
* past deliveries for an endpoint they once owned.
|
||||
*/
|
||||
export async function userOwnsEndpoint(endpointId: string, userId: string): Promise<boolean> {
|
||||
const admin = createAdminClient();
|
||||
const { data, error } = await admin
|
||||
.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS)
|
||||
.select('id')
|
||||
.eq('id', endpointId)
|
||||
.eq('user_id', userId)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
logger.warn('userOwnsEndpoint: query failed', { error, endpointId, userId });
|
||||
return false;
|
||||
}
|
||||
return !!data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bump last_delivery_at on the endpoint — fire-and-forget from the worker
|
||||
* after a successful POST so the /settings/integrations UI shows freshness.
|
||||
|
||||
Reference in new issue
Block a user