feat(settings): webhook endpoints panel + extract keys card from page

Completes the user-visible surface for the webhook stack landed across
211188a3 / 7dfdab2f / 6cc7e4ba / 2755a8a5. Before this commit every
webhook operation required direct SQL — minting an endpoint, listing,
revoking. Now they all live in /settings/integrations alongside the
existing integration-keys panel.

API:
  - GET  /api/webhook-endpoints       list caller's endpoints (no secret)
  - POST /api/webhook-endpoints       mint + return plaintext secret ONCE
                                      (enforces https:// in production)
  - DELETE /api/webhook-endpoints/:id soft-revoke
Both auth via Supabase session (an integration key cannot mint another —
same escalation argument as integration keys). The routes mirror
src/app/api/integration-keys/* on purpose; this is the same actor-bound
platform-plumbing pattern.

Components:
  - WebhookEndpointsCard.tsx          new — mint + list + revoke flow
  - IntegrationKeysCard.tsx           lifted from the page so the file
                                      stays under the 300-line component
                                      cap with both surfaces present

Page:
  - /settings/integrations now orchestrates both cards (~100 LOC).
    Both share the same actor selector — resolved once, passed down.

Deliveries drawer (per-endpoint status / attempt history) was originally
in scope for this commit but split out to a follow-up to stay tight.

46 suites · 604 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.7 committed 2026-06-03 23:58:58 +02:00
1 parent 2755a8a57b
commit eefbcba59f
5 files changed
+793 -303

No files matched your search

@@ -1,182 +1,39 @@
'use client';
/**
* Integration keys settings page.
* Integrations settings — two panels:
*
* Surfaces the outbound platform API keys a user has minted, plus a
* minimal mint flow. The plaintext key is shown ONCE on mint and never
* again — users copy it before closing the reveal dialog.
* 1. Integration keys (outbound API auth — FleetCrown, hirn.li, …)
* 2. Webhook endpoints (inbound signed events to your URL)
*
* Companion to:
* - service: src/services/auth/integrationKeys.ts
* - api: src/app/api/integration-keys/*
* Both panels share the actor selector (personal + group actors), so
* we resolve actors once here and pass them down.
*
* Created: 2026-06-03
* Last Modified: 2026-06-03
* Last Modified Summary: Initial implementation — FleetCrown integration UX now end-to-end without SQL.
* Lift history:
* Pre-2026-06-03 — single keys panel inline in this page.
* 2026-06-03 — extracted IntegrationKeysCard + WebhookEndpointsCard
* so the page stays under the 300-line cap with both
* surfaces shown.
*/
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Copy, KeyRound, LogIn, Plus, Trash2 } from 'lucide-react';
import { ArrowLeft, KeyRound, LogIn, Webhook } from 'lucide-react';
import { useRequireAuth } from '@/hooks/useAuth';
import { useMessagingActors } from '@/features/messaging/hooks/useMessagingActors';
import { ROUTES } from '@/config/routes';
import Loading from '@/components/Loading';
import Button from '@/components/ui/Button';
import { logger } from '@/utils/logger';
import IntegrationKeysCard from '@/components/settings/IntegrationKeysCard';
import WebhookEndpointsCard from '@/components/settings/WebhookEndpointsCard';
interface IntegrationKey {
id: string;
actor_id: string;
name: string;
key_prefix: string;
created_at: string;
last_used_at: string | null;
expires_at: string | null;
revoked_at: string | null;
}
interface MintResponse {
data: { key: IntegrationKey; plaintext: string };
}
function formatTimestamp(value: string | null): string {
if (!value) {
return '—';
}
return new Date(value).toLocaleString();
}
export default function IntegrationKeysPage() {
// Hydration ceiling lives inside useRequireAuth now (2026-06-03) —
// every auth-gated page benefits, not just this one.
export default function IntegrationsPage() {
const { user, isLoading: authLoading } = useRequireAuth();
const { personalActor, groupActors } = useMessagingActors();
const [keys, setKeys] = useState<IntegrationKey[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [name, setName] = useState('');
const [selectedActorId, setSelectedActorId] = useState<string | null>(null);
const [minting, setMinting] = useState(false);
const [mintedPlaintext, setMintedPlaintext] = useState<string | null>(null);
const [mintedPrefix, setMintedPrefix] = useState<string | null>(null);
useEffect(() => {
if (!user) {
return;
}
let cancelled = false;
(async () => {
try {
const res = await fetch('/api/integration-keys', { credentials: 'include' });
if (!res.ok) {
throw new Error(`Failed to load keys (${res.status})`);
}
const json = (await res.json()) as { data: { keys: IntegrationKey[] } };
if (!cancelled) {
setKeys(json.data?.keys ?? []);
setLoading(false);
}
} catch (err) {
logger.error('Failed to load integration keys', { err });
if (!cancelled) {
setError(err instanceof Error ? err.message : 'Failed to load keys');
setLoading(false);
}
}
})();
return () => {
cancelled = true;
};
}, [user]);
const allActors = [
...(personalActor ? [{ ...personalActor, label: `${personalActor.name} (Personal)` }] : []),
...groupActors.map(a => ({ ...a, label: a.name })),
];
// Default the actor pick to the personal actor once it loads.
useEffect(() => {
if (!selectedActorId && personalActor) {
setSelectedActorId(personalActor.actor_id);
}
}, [personalActor, selectedActorId]);
async function handleMint(e: React.FormEvent) {
e.preventDefault();
if (!selectedActorId || !name.trim()) {
return;
}
setMinting(true);
setError(null);
try {
const res = await fetch('/api/integration-keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ name: name.trim(), actor_id: selectedActorId }),
});
if (!res.ok) {
const body = (await res.json().catch(() => null)) as { error?: string } | null;
throw new Error(body?.error || `Failed to mint key (${res.status})`);
}
const json = (await res.json()) as MintResponse;
setMintedPlaintext(json.data.plaintext);
setMintedPrefix(json.data.key.key_prefix);
setKeys(prev => [json.data.key, ...prev]);
setName('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to mint key');
} finally {
setMinting(false);
}
}
async function handleRevoke(key: IntegrationKey) {
if (!confirm(`Revoke "${key.name}"? Existing integrations will stop working immediately.`)) {
return;
}
try {
const res = await fetch(`/api/integration-keys/${key.id}`, {
method: 'DELETE',
credentials: 'include',
});
if (!res.ok) {
throw new Error(`Failed to revoke (${res.status})`);
}
setKeys(prev =>
prev.map(k => (k.id === key.id ? { ...k, revoked_at: new Date().toISOString() } : k))
);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to revoke key');
}
}
async function copyPlaintext() {
if (!mintedPlaintext) {
return;
}
try {
await navigator.clipboard.writeText(mintedPlaintext);
} catch (err) {
logger.warn('Clipboard write failed', { err });
}
}
// authLoading already folds in the hydration ceiling — once the
// useRequireAuth timeout fires (default 4s), this is false and we
// fall through to the !user branch with a real sign-in CTA.
if (authLoading) {
return <Loading fullScreen message="Loading integrations..." />;
}
// No user (either definitively unauth'd or the auth store is stuck).
// Render an actionable sign-in surface instead of a perpetual spinner
// or `return null` blank flash. The `from` param brings them back here
// after login.
if (!user) {
const returnTo = `${ROUTES.AUTH}?mode=login&from=${encodeURIComponent(ROUTES.SETTINGS_INTEGRATIONS)}`;
return (
@@ -186,8 +43,8 @@ export default function IntegrationKeysPage() {
</div>
<h1 className="text-xl font-semibold text-foreground">Sign in to manage integrations</h1>
<p className="mt-2 text-sm text-muted-foreground">
Integration keys let external services authenticate to OrangeCat as a specific actor. Sign
in to mint, view, or revoke them.
Integration keys and webhook endpoints both bind to a specific actor. Sign in to mint,
view, or revoke them.
</p>
<Link href={returnTo} className="mt-6 inline-block">
<Button>
@@ -205,9 +62,17 @@ export default function IntegrationKeysPage() {
);
}
const actors = [
...(personalActor
? [{ actor_id: personalActor.actor_id, label: `${personalActor.name} (Personal)` }]
: []),
...groupActors.map(a => ({ actor_id: a.actor_id, label: a.name })),
];
const defaultActorId = personalActor?.actor_id ?? actors[0]?.actor_id ?? null;
return (
<div className="mx-auto max-w-3xl p-4 sm:p-6 lg:p-8">
<div className="mb-6">
<div className="mx-auto max-w-3xl space-y-10 p-4 sm:p-6 lg:p-8">
<div>
<Link
href={ROUTES.SETTINGS}
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
@@ -215,13 +80,9 @@ export default function IntegrationKeysPage() {
<ArrowLeft className="h-4 w-4" />
Settings
</Link>
<h1 className="mt-3 flex items-center gap-2 text-2xl font-semibold text-foreground">
<KeyRound className="h-5 w-5" />
Integration keys
</h1>
<h1 className="mt-3 text-2xl font-semibold text-foreground">Integrations</h1>
<p className="mt-1 text-sm text-muted-foreground">
Let external services (FleetCrown, hirn.li, your own scripts) authenticate to OrangeCat as
a specific actor. Each key acts as one actor and can be revoked individually.
Let external services authenticate to OrangeCat and receive signed events.
</p>
<p className="mt-2 text-xs text-muted-foreground">
API contract:{' '}
@@ -245,143 +106,29 @@ export default function IntegrationKeysPage() {
</p>
</div>
{error && (
<div className="mb-4 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
{error}
</div>
)}
<div>
<h2 className="mb-3 flex items-center gap-2 text-lg font-semibold text-foreground">
<KeyRound className="h-5 w-5" />
Integration keys
</h2>
<p className="mb-4 text-sm text-muted-foreground">
Outbound API auth. Each key acts as one actor and can be revoked individually.
</p>
<IntegrationKeysCard actors={actors} defaultActorId={defaultActorId} />
</div>
{/* Mint form */}
<form
onSubmit={handleMint}
className="mb-6 space-y-3 rounded-lg border border-border-subtle bg-muted/20 p-4"
>
<h2 className="text-sm font-medium text-foreground">Create a new key</h2>
<div className="grid gap-3 sm:grid-cols-2">
<label className="text-xs text-muted-foreground">
Name
<input
type="text"
required
maxLength={120}
value={name}
onChange={e => setName(e.target.value)}
placeholder='e.g. "FleetCrown production"'
className="mt-1 w-full rounded-md border border-border-subtle bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-ring/50 focus:outline-none"
/>
</label>
<label className="text-xs text-muted-foreground">
Acts as
<select
value={selectedActorId ?? ''}
onChange={e => setSelectedActorId(e.target.value || null)}
className="mt-1 w-full rounded-md border border-border-subtle bg-background px-3 py-2 text-sm text-foreground focus:border-ring/50 focus:outline-none"
>
{allActors.map(actor => (
<option key={actor.actor_id} value={actor.actor_id}>
{actor.label}
</option>
))}
</select>
</label>
</div>
<Button type="submit" disabled={minting || !selectedActorId || !name.trim()}>
<Plus className="mr-1 h-4 w-4" />
{minting ? 'Creating…' : 'Create key'}
</Button>
</form>
{/* Reveal — plaintext shown ONCE */}
{mintedPlaintext && (
<div className="mb-6 rounded-lg border border-ring/50 bg-muted/40 p-4">
<p className="text-sm font-medium text-foreground">
Copy this key now — you won&apos;t see it again
</p>
<p className="mt-1 text-xs text-muted-foreground">
Prefix <code className="rounded bg-muted px-1">{mintedPrefix}</code> is all you&apos;ll
see after closing this card.
</p>
<div className="mt-3 flex items-center gap-2">
<code className="flex-1 truncate rounded-md border border-border-subtle bg-background px-3 py-2 font-mono text-xs text-foreground">
{mintedPlaintext}
</code>
<button
type="button"
onClick={copyPlaintext}
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2.5 py-1.5 text-xs text-foreground hover:bg-muted/60"
>
<Copy className="h-3.5 w-3.5" />
Copy
</button>
<button
type="button"
onClick={() => {
setMintedPlaintext(null);
setMintedPrefix(null);
}}
className="text-xs text-muted-foreground hover:text-foreground"
>
Close
</button>
</div>
</div>
)}
{/* List */}
<div className="rounded-lg border border-border-subtle">
<div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">
<h2 className="text-sm font-medium text-foreground">Your keys</h2>
<span className="text-xs text-muted-foreground">
{keys.length} {keys.length === 1 ? 'key' : 'keys'}
</span>
</div>
{loading ? (
<div className="p-4 text-sm text-muted-foreground">Loading…</div>
) : keys.length === 0 ? (
<div className="p-6 text-center text-sm text-muted-foreground">
No keys yet. Create one above to integrate an external service.
</div>
) : (
<ul className="divide-y divide-border-subtle">
{keys.map(key => {
const isRevoked = !!key.revoked_at;
const actorLabel =
allActors.find(a => a.actor_id === key.actor_id)?.label ?? key.actor_id;
return (
<li key={key.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">{key.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>
<code className="rounded bg-muted px-1">{key.key_prefix}…</code>
</span>
<span>Acts as {actorLabel}</span>
<span>Created {formatTimestamp(key.created_at)}</span>
<span>Last used {formatTimestamp(key.last_used_at)}</span>
</div>
</div>
{!isRevoked && (
<button
type="button"
onClick={() => handleRevoke(key)}
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>
)}
</li>
);
})}
</ul>
)}
<div>
<h2 className="mb-3 flex items-center gap-2 text-lg font-semibold text-foreground">
<Webhook className="h-5 w-5" />
Webhook endpoints
</h2>
<p className="mb-4 text-sm text-muted-foreground">
Receive signed POST events when entities the bound actor owns are created. Verify
deliveries with{' '}
<code className="rounded bg-muted px-1 text-xs">verifyWebhookSignature</code> from{' '}
<code className="rounded bg-muted px-1 text-xs">@orangecat/sdk</code>.
</p>
<WebhookEndpointsCard actors={actors} defaultActorId={defaultActorId} />
</div>
</div>
);
@@ -0,0 +1,39 @@
/**
* DELETE /api/webhook-endpoints/[id] — revoke (soft-delete; audit kept).
*
* Auth: Supabase session only. Returns 404 when the endpoint doesn't
* belong to the caller or is already revoked, to avoid leaking endpoint
* existence to other users via probing.
*
* Mirrors src/app/api/integration-keys/[id]/route.ts.
*/
import { NextRequest } from 'next/server';
import { createServerClient } from '@/lib/supabase/server';
import {
apiSuccess,
apiUnauthorized,
apiNotFound,
handleApiError,
} from '@/lib/api/standardResponse';
import { revokeWebhookEndpoint } from '@/services/webhooks/webhookEndpointsService';
export async function DELETE(_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 ok = await revokeWebhookEndpoint(id, user.id);
if (!ok) {
return apiNotFound('Webhook endpoint');
}
return apiSuccess({ revoked: true });
} catch (error) {
return handleApiError(error);
}
}
+99
View File
@@ -0,0 +1,99 @@
/**
* Webhook endpoints — mint and list.
*
* GET /api/webhook-endpoints → list caller's endpoints (no secret)
* POST /api/webhook-endpoints → mint a new endpoint, plaintext secret
* returned ONCE
*
* Auth: Supabase session only. Integration keys themselves cannot mint
* webhook endpoints — same escalation reason as integration keys.
*
* Mirrors src/app/api/integration-keys/route.ts on purpose; both are
* the same actor-bound platform-plumbing pattern.
*/
import { NextRequest } from 'next/server';
import { z } from 'zod';
import { compose } from '@/lib/api/compose';
import { withRequestId } from '@/lib/api/withRequestId';
import { withZodBody } from '@/lib/api/withZod';
import { createServerClient } from '@/lib/supabase/server';
import {
apiSuccess,
apiUnauthorized,
apiForbidden,
handleApiError,
} from '@/lib/api/standardResponse';
import {
createWebhookEndpoint,
listWebhookEndpoints,
ActorNotPermittedError,
} from '@/services/webhooks/webhookEndpointsService';
const createEndpointSchema = z.object({
name: z.string().min(1).max(120),
url: z.string().url().max(2048),
actor_id: z.string().uuid(),
event_types: z.array(z.string().min(1).max(80)).max(20).optional(),
});
async function requireSessionUser(): Promise<{ id: string } | null> {
const supabase = await createServerClient();
const {
data: { user },
} = await supabase.auth.getUser();
return user ?? null;
}
export const GET = compose(withRequestId())(async () => {
try {
const user = await requireSessionUser();
if (!user) {
return apiUnauthorized();
}
const endpoints = await listWebhookEndpoints(user.id);
return apiSuccess({ endpoints });
} catch (error) {
return handleApiError(error);
}
});
export const POST = compose(
withRequestId(),
withZodBody(createEndpointSchema)
)(async (_req: NextRequest, ctx) => {
try {
const user = await requireSessionUser();
if (!user) {
return apiUnauthorized();
}
const body = ctx.body as {
name: string;
url: string;
actor_id: string;
event_types?: string[];
};
// https-only in production; localhost allowed in dev for testing.
const isProd = process.env.NODE_ENV === 'production';
if (isProd && !body.url.startsWith('https://')) {
return apiForbidden('Webhook URL must use https in production.');
}
try {
const minted = await createWebhookEndpoint({
userId: user.id,
actorId: body.actor_id,
name: body.name,
url: body.url,
eventTypes: body.event_types ?? null,
});
return apiSuccess({ endpoint: minted.endpoint, secret: minted.secret }, { status: 201 });
} catch (error) {
if (error instanceof ActorNotPermittedError) {
return apiForbidden('You are not permitted to create an endpoint for this actor.');
}
throw error;
}
} catch (error) {
return handleApiError(error);
}
});
@@ -0,0 +1,290 @@
'use client';
/**
* Integration keys panel — mint + list + revoke.
*
* Lifted from /settings/integrations/page.tsx 2026-06-03 so the page
* could grow a sibling webhook-endpoints panel without exceeding the
* 300-line component cap.
*/
import { useEffect, useState } from 'react';
import { Copy, Plus, Trash2 } from 'lucide-react';
import Button from '@/components/ui/Button';
import { logger } from '@/utils/logger';
export interface IntegrationKey {
id: string;
actor_id: string;
name: string;
key_prefix: string;
created_at: string;
last_used_at: string | null;
expires_at: string | null;
revoked_at: string | null;
}
interface MintResponse {
data: { key: IntegrationKey; plaintext: string };
}
interface ActorOption {
actor_id: string;
label: string;
}
interface Props {
actors: ActorOption[];
defaultActorId: string | null;
}
function formatTimestamp(value: string | null): string {
if (!value) {
return '—';
}
return new Date(value).toLocaleString();
}
export default function IntegrationKeysCard({ actors, defaultActorId }: Props) {
const [keys, setKeys] = useState<IntegrationKey[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [name, setName] = useState('');
const [selectedActorId, setSelectedActorId] = useState<string | null>(defaultActorId);
const [minting, setMinting] = useState(false);
const [mintedPlaintext, setMintedPlaintext] = useState<string | null>(null);
const [mintedPrefix, setMintedPrefix] = useState<string | null>(null);
useEffect(() => {
if (!selectedActorId && defaultActorId) {
setSelectedActorId(defaultActorId);
}
}, [defaultActorId, selectedActorId]);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const res = await fetch('/api/integration-keys', { credentials: 'include' });
if (!res.ok) {
throw new Error(`Failed to load keys (${res.status})`);
}
const json = (await res.json()) as { data: { keys: IntegrationKey[] } };
if (!cancelled) {
setKeys(json.data?.keys ?? []);
setLoading(false);
}
} catch (err) {
logger.error('Failed to load integration keys', { err });
if (!cancelled) {
setError(err instanceof Error ? err.message : 'Failed to load keys');
setLoading(false);
}
}
})();
return () => {
cancelled = true;
};
}, []);
async function handleMint(e: React.FormEvent) {
e.preventDefault();
if (!selectedActorId || !name.trim()) {
return;
}
setMinting(true);
setError(null);
try {
const res = await fetch('/api/integration-keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ name: name.trim(), actor_id: selectedActorId }),
});
if (!res.ok) {
const body = (await res.json().catch(() => null)) as { error?: string } | null;
throw new Error(body?.error || `Failed to mint key (${res.status})`);
}
const json = (await res.json()) as MintResponse;
setMintedPlaintext(json.data.plaintext);
setMintedPrefix(json.data.key.key_prefix);
setKeys(prev => [json.data.key, ...prev]);
setName('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to mint key');
} finally {
setMinting(false);
}
}
async function handleRevoke(key: IntegrationKey) {
if (!confirm(`Revoke "${key.name}"? Existing integrations will stop working immediately.`)) {
return;
}
try {
const res = await fetch(`/api/integration-keys/${key.id}`, {
method: 'DELETE',
credentials: 'include',
});
if (!res.ok) {
throw new Error(`Failed to revoke (${res.status})`);
}
setKeys(prev =>
prev.map(k => (k.id === key.id ? { ...k, revoked_at: new Date().toISOString() } : k))
);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to revoke key');
}
}
async function copyPlaintext() {
if (!mintedPlaintext) {
return;
}
try {
await navigator.clipboard.writeText(mintedPlaintext);
} catch (err) {
logger.warn('Clipboard write failed', { err });
}
}
return (
<section className="space-y-4">
{error && (
<div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
{error}
</div>
)}
<form
onSubmit={handleMint}
className="space-y-3 rounded-lg border border-border-subtle bg-muted/20 p-4"
>
<h3 className="text-sm font-medium text-foreground">Create a new key</h3>
<div className="grid gap-3 sm:grid-cols-2">
<label className="text-xs text-muted-foreground">
Name
<input
type="text"
required
maxLength={120}
value={name}
onChange={e => setName(e.target.value)}
placeholder='e.g. "FleetCrown production"'
className="mt-1 w-full rounded-md border border-border-subtle bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-ring/50 focus:outline-none"
/>
</label>
<label className="text-xs text-muted-foreground">
Acts as
<select
value={selectedActorId ?? ''}
onChange={e => setSelectedActorId(e.target.value || null)}
className="mt-1 w-full rounded-md border border-border-subtle bg-background px-3 py-2 text-sm text-foreground focus:border-ring/50 focus:outline-none"
>
{actors.map(actor => (
<option key={actor.actor_id} value={actor.actor_id}>
{actor.label}
</option>
))}
</select>
</label>
</div>
<Button type="submit" disabled={minting || !selectedActorId || !name.trim()}>
<Plus className="mr-1 h-4 w-4" />
{minting ? 'Creating…' : 'Create key'}
</Button>
</form>
{mintedPlaintext && (
<div className="rounded-lg border border-ring/50 bg-muted/40 p-4">
<p className="text-sm font-medium text-foreground">
Copy this key now — you won&apos;t see it again
</p>
<p className="mt-1 text-xs text-muted-foreground">
Prefix <code className="rounded bg-muted px-1">{mintedPrefix}</code> is all you&apos;ll
see after closing this card.
</p>
<div className="mt-3 flex items-center gap-2">
<code className="flex-1 truncate rounded-md border border-border-subtle bg-background px-3 py-2 font-mono text-xs text-foreground">
{mintedPlaintext}
</code>
<button
type="button"
onClick={copyPlaintext}
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2.5 py-1.5 text-xs text-foreground hover:bg-muted/60"
>
<Copy className="h-3.5 w-3.5" />
Copy
</button>
<button
type="button"
onClick={() => {
setMintedPlaintext(null);
setMintedPrefix(null);
}}
className="text-xs text-muted-foreground hover:text-foreground"
>
Close
</button>
</div>
</div>
)}
<div className="rounded-lg border border-border-subtle">
<div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">
<h3 className="text-sm font-medium text-foreground">Your keys</h3>
<span className="text-xs text-muted-foreground">
{keys.length} {keys.length === 1 ? 'key' : 'keys'}
</span>
</div>
{loading ? (
<div className="p-4 text-sm text-muted-foreground">Loading…</div>
) : keys.length === 0 ? (
<div className="p-6 text-center text-sm text-muted-foreground">
No keys yet. Create one above to integrate an external service.
</div>
) : (
<ul className="divide-y divide-border-subtle">
{keys.map(key => {
const isRevoked = !!key.revoked_at;
const actorLabel =
actors.find(a => a.actor_id === key.actor_id)?.label ?? key.actor_id;
return (
<li key={key.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">{key.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>
<code className="rounded bg-muted px-1">{key.key_prefix}…</code>
</span>
<span>Acts as {actorLabel}</span>
<span>Created {formatTimestamp(key.created_at)}</span>
<span>Last used {formatTimestamp(key.last_used_at)}</span>
</div>
</div>
{!isRevoked && (
<button
type="button"
onClick={() => handleRevoke(key)}
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>
)}
</li>
);
})}
</ul>
)}
</div>
</section>
);
}
@@ -0,0 +1,315 @@
'use client';
/**
* Webhook endpoints panel — mint + list + revoke.
*
* Same UX as IntegrationKeysCard (sibling on /settings/integrations).
* Endpoints receive signed POSTs from OrangeCat when entities the bound
* actor owns get created — verified by the integration with
* `verifyWebhookSignature` from @orangecat/sdk.
*/
import { useEffect, useState } from 'react';
import { Copy, Plus, Trash2 } from 'lucide-react';
import Button from '@/components/ui/Button';
import { logger } from '@/utils/logger';
interface WebhookEndpoint {
id: string;
actor_id: string;
name: string;
url: string;
secret_prefix: string;
event_types: string[] | null;
created_at: string;
last_delivery_at: string | null;
revoked_at: string | null;
}
interface MintResponse {
data: { endpoint: WebhookEndpoint; secret: string };
}
interface ActorOption {
actor_id: string;
label: string;
}
interface Props {
actors: ActorOption[];
defaultActorId: string | null;
}
function formatTimestamp(value: string | null): string {
if (!value) {
return '—';
}
return new Date(value).toLocaleString();
}
export default function WebhookEndpointsCard({ actors, defaultActorId }: Props) {
const [endpoints, setEndpoints] = useState<WebhookEndpoint[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [name, setName] = useState('');
const [url, setUrl] = useState('');
const [selectedActorId, setSelectedActorId] = useState<string | null>(defaultActorId);
const [minting, setMinting] = useState(false);
const [mintedSecret, setMintedSecret] = useState<string | null>(null);
const [mintedPrefix, setMintedPrefix] = useState<string | null>(null);
useEffect(() => {
if (!selectedActorId && defaultActorId) {
setSelectedActorId(defaultActorId);
}
}, [defaultActorId, selectedActorId]);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const res = await fetch('/api/webhook-endpoints', { credentials: 'include' });
if (!res.ok) {
throw new Error(`Failed to load endpoints (${res.status})`);
}
const json = (await res.json()) as { data: { endpoints: WebhookEndpoint[] } };
if (!cancelled) {
setEndpoints(json.data?.endpoints ?? []);
setLoading(false);
}
} catch (err) {
logger.error('Failed to load webhook endpoints', { err });
if (!cancelled) {
setError(err instanceof Error ? err.message : 'Failed to load endpoints');
setLoading(false);
}
}
})();
return () => {
cancelled = true;
};
}, []);
async function handleMint(e: React.FormEvent) {
e.preventDefault();
if (!selectedActorId || !name.trim() || !url.trim()) {
return;
}
setMinting(true);
setError(null);
try {
const res = await fetch('/api/webhook-endpoints', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
name: name.trim(),
url: url.trim(),
actor_id: selectedActorId,
}),
});
if (!res.ok) {
const body = (await res.json().catch(() => null)) as { error?: string } | null;
throw new Error(body?.error || `Failed to create endpoint (${res.status})`);
}
const json = (await res.json()) as MintResponse;
setMintedSecret(json.data.secret);
setMintedPrefix(json.data.endpoint.secret_prefix);
setEndpoints(prev => [json.data.endpoint, ...prev]);
setName('');
setUrl('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create endpoint');
} finally {
setMinting(false);
}
}
async function handleRevoke(endpoint: WebhookEndpoint) {
if (!confirm(`Revoke "${endpoint.name}"? Deliveries to this URL will stop immediately.`)) {
return;
}
try {
const res = await fetch(`/api/webhook-endpoints/${endpoint.id}`, {
method: 'DELETE',
credentials: 'include',
});
if (!res.ok) {
throw new Error(`Failed to revoke (${res.status})`);
}
setEndpoints(prev =>
prev.map(e => (e.id === endpoint.id ? { ...e, revoked_at: new Date().toISOString() } : e))
);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to revoke endpoint');
}
}
async function copySecret() {
if (!mintedSecret) {
return;
}
try {
await navigator.clipboard.writeText(mintedSecret);
} catch (err) {
logger.warn('Clipboard write failed', { err });
}
}
return (
<section className="space-y-4">
{error && (
<div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
{error}
</div>
)}
<form
onSubmit={handleMint}
className="space-y-3 rounded-lg border border-border-subtle bg-muted/20 p-4"
>
<h3 className="text-sm font-medium text-foreground">Create a new endpoint</h3>
<div className="grid gap-3 sm:grid-cols-2">
<label className="text-xs text-muted-foreground sm:col-span-1">
Name
<input
type="text"
required
maxLength={120}
value={name}
onChange={e => setName(e.target.value)}
placeholder='e.g. "FleetCrown subscriptions"'
className="mt-1 w-full rounded-md border border-border-subtle bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-ring/50 focus:outline-none"
/>
</label>
<label className="text-xs text-muted-foreground sm:col-span-1">
Acts as
<select
value={selectedActorId ?? ''}
onChange={e => setSelectedActorId(e.target.value || null)}
className="mt-1 w-full rounded-md border border-border-subtle bg-background px-3 py-2 text-sm text-foreground focus:border-ring/50 focus:outline-none"
>
{actors.map(actor => (
<option key={actor.actor_id} value={actor.actor_id}>
{actor.label}
</option>
))}
</select>
</label>
<label className="text-xs text-muted-foreground sm:col-span-2">
Target URL (https in production)
<input
type="url"
required
maxLength={2048}
value={url}
onChange={e => setUrl(e.target.value)}
placeholder="https://fleetcrown.app/webhooks/orangecat"
className="mt-1 w-full rounded-md border border-border-subtle bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-ring/50 focus:outline-none"
/>
</label>
</div>
<Button type="submit" disabled={minting || !selectedActorId || !name.trim() || !url.trim()}>
<Plus className="mr-1 h-4 w-4" />
{minting ? 'Creating…' : 'Create endpoint'}
</Button>
</form>
{mintedSecret && (
<div className="rounded-lg border border-ring/50 bg-muted/40 p-4">
<p className="text-sm font-medium text-foreground">
Copy this signing secret now — you won&apos;t see it again
</p>
<p className="mt-1 text-xs text-muted-foreground">
Prefix <code className="rounded bg-muted px-1">{mintedPrefix}</code> is all you&apos;ll
see after closing this card. Use this secret with{' '}
<code className="rounded bg-muted px-1">verifyWebhookSignature</code> from{' '}
<code className="rounded bg-muted px-1">@orangecat/sdk</code>.
</p>
<div className="mt-3 flex items-center gap-2">
<code className="flex-1 truncate rounded-md border border-border-subtle bg-background px-3 py-2 font-mono text-xs text-foreground">
{mintedSecret}
</code>
<button
type="button"
onClick={copySecret}
className="inline-flex items-center gap-1 rounded-md border border-border-subtle px-2.5 py-1.5 text-xs text-foreground hover:bg-muted/60"
>
<Copy className="h-3.5 w-3.5" />
Copy
</button>
<button
type="button"
onClick={() => {
setMintedSecret(null);
setMintedPrefix(null);
}}
className="text-xs text-muted-foreground hover:text-foreground"
>
Close
</button>
</div>
</div>
)}
<div className="rounded-lg border border-border-subtle">
<div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">
<h3 className="text-sm font-medium text-foreground">Your endpoints</h3>
<span className="text-xs text-muted-foreground">
{endpoints.length} {endpoints.length === 1 ? 'endpoint' : 'endpoints'}
</span>
</div>
{loading ? (
<div className="p-4 text-sm text-muted-foreground">Loading…</div>
) : endpoints.length === 0 ? (
<div className="p-6 text-center text-sm text-muted-foreground">
No endpoints yet. Create one above to receive signed events.
</div>
) : (
<ul className="divide-y divide-border-subtle">
{endpoints.map(endpoint => {
const isRevoked = !!endpoint.revoked_at;
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
</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>
{!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>
)}
</li>
);
})}
</ul>
)}
</div>
</section>
);
}