fix(ui): consolidate webhook source management

This commit is contained in:
sam committed 2026-11-24 07:59:24 +11:00
1 parent 19b273a87b
commit 58f1f9ce57
10 files changed
+129 -544

No files matched your search

-2
View File
@@ -3,7 +3,6 @@ import { breakpointsTailwind, useBreakpoints } from "@vueuse/core";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import SourcesPanel from "@/sources/SourcesPanel.vue";
import CaptureDetail from "./CaptureDetail.vue";
import CapturesCard from "./CapturesCard.vue";
import EventTypesCard from "./EventTypesCard.vue";
@@ -91,7 +90,6 @@ watch(selected, (capture) => {
</script>
<template>
<SourcesPanel />
<!-- Split only when there is a capture to show beside the list. -->
<div
class="grid min-w-0 items-start gap-4"
-2
View File
@@ -16,7 +16,6 @@ import { logs } from "./logs.ts";
import { mappings } from "./mappings.ts";
import { org } from "./org.ts";
import { settings } from "./settings.ts";
import { sources } from "./sources.ts";
import { stores } from "./stores.ts";
import { tasks } from "./tasks.ts";
import { workflows } from "./workflows.ts";
@@ -37,7 +36,6 @@ export const errors = {
mappings,
org,
settings,
sources,
stores,
tasks,
workflows,
-6
View File
@@ -1,6 +0,0 @@
export const sources = {
panel: {
writeFailed: "That did not take effect",
loadFailed: "Couldn't load sources",
},
} as const;
+5 -1
View File
@@ -2,9 +2,10 @@
import { Badge } from "@/components/ui/badge";
import { enabled as captureEnabled, loading as captureLoading } from "@/captures/state";
import { computed, onMounted, ref, watch, type Component } from "vue";
import { useRoute, useRouter } from "vue-router";
import { RouterLink, useRoute, useRouter } from "vue-router";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import BindingsPage from "@/bindings/BindingsPage.vue";
@@ -99,6 +100,9 @@ const panel = computed(() => PANELS[active.value]);
<template v-if="captureChain && !captureLoading">
<Badge v-if="!captureEnabled" variant="warn">Capture off</Badge>
</template>
<Button v-if="active === 'inspector' && tabs.some((tab) => tab.id === 'sources')" as-child size="sm" variant="outline">
<RouterLink :to="{ query: { tab: 'sources' } }">Manage sources</RouterLink>
</Button>
</PageHeader>
<Tabs :model-value="active" class="mb-4" @update:model-value="show">
<TabsList variant="line" class="w-full justify-start" aria-label="How events become work">
+112 -51
View File
@@ -3,10 +3,12 @@ import { Plus } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import CodeView from "@/base/CodeView.vue";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
@@ -17,11 +19,14 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectVa
import { SettingRow } from "@/components/ui/setting-row";
import { Skeleton } from "@/components/ui/skeleton";
import { errors } from "@/copy/errors";
import { api, describeError, type EventSource_, type SourceVerification } from "@/lib/api";
import { api, describeError, type EventSource_, type SourceIssued, type SourceVerification } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { signingKind, signingLabel, sourceURL } from "@/sources/source-signing";
import { useLiveResource } from "@/stores/session";
const { data, error, reload } = useRead(() => api.eventSources());
const connectors = useRead(() => api.extensions("connectors"));
useLiveResource(null, () => void reload());
onMounted(() => {
void reload();
void connectors.reload();
@@ -34,19 +39,15 @@ const columns: DataTableColumn<EventSource_>[] = [
{ id: "key", label: "Grouped by", hide: "md", width: "16rem" },
];
// A put creates a source or rotates its token; either way the token is shown
// once, since only its hash is kept.
const issued = ref<{ url: string; token?: string } | null>(null);
const webhook = ref<Omit<SourceIssued, "id"> | null>(null);
const busy = ref(false);
const actionError = ref("");
async function put(connector: string, verification?: SourceVerification, existing?: EventSource_ | null, label = ""): Promise<boolean> {
async function save(write: () => Promise<unknown>): Promise<boolean> {
if (busy.value) return false;
busy.value = true;
actionError.value = "";
try {
const created = existing
? await api.updateEventSource(existing.id, connector, verification)
: await api.createEventSource({ label, connector, ...verification });
issued.value = { url: new URL(created.url, window.location.origin).toString(), token: created.token };
await write();
await reload();
return true;
} catch (cause) {
@@ -57,6 +58,31 @@ async function put(connector: string, verification?: SourceVerification, existin
}
}
async function put(connector: string, verification?: SourceVerification, existing?: EventSource_ | null, label = ""): Promise<boolean> {
return save(async () => {
const result = existing
? await api.updateEventSource(existing.id, connector, verification)
: await api.createEventSource({ label, connector, ...verification });
webhook.value = { ...result, url: new URL(result.url, window.location.origin).toString() };
});
}
function showWebhook(source: EventSource_, secret?: string): void {
webhook.value = { url: sourceURL(window.location.origin, source.webhook_path), secret };
}
function saveSigning(write: () => Promise<EventSource_>): Promise<boolean> {
return save(async () => {
const result = await write();
if (result.secret) showWebhook(result, result.secret);
});
}
const toggleCapture = (source: EventSource_) => save(() => api.sourceCapture(source.id, !source.capture));
const rotateSecret = (source: EventSource_) => saveSigning(() => api.sourceSecret(source.id));
const setSigning = (source: EventSource_, signed: boolean) => saveSigning(() => api.sourceSigning(source.id, signed));
const approveUnsigned = (source: EventSource_) => saveSigning(() => api.sourceApproveUnsigned(source.id));
const adding = ref(false);
const editing = ref<EventSource_ | null>(null);
const blank = { label: "", connector: "", verification: "token" as SourceVerification["verification"], hmac_header: "", hmac_prefix: "", hmac_secret: "" };
@@ -71,11 +97,8 @@ async function add(): Promise<void> {
draft.value = { ...blank };
}
}
// A blank secret keeps the stored one, so it is required only when a source
// has none yet.
const secretOptional = computed(() => editing.value?.verification === "hmac" && editing.value.hmac_secret_set);
const addDisabled = computed(() => busy.value || !draft.value.label || !draft.value.connector
|| (draft.value.verification === "hmac" && (!draft.value.hmac_header || (!draft.value.hmac_secret && !secretOptional.value))));
const addDisabled = computed(() => busy.value || !draft.value.label.trim() || !draft.value.connector
|| (draft.value.verification === "hmac" && !draft.value.hmac_header));
function openAdd(): void {
editing.value = null;
draft.value = { ...blank };
@@ -92,27 +115,31 @@ function openEdit(source: EventSource_): void {
actionError.value = "";
}
const keyFieldsOf = ref<EventSource_ | null>(null);
const keyFields = ref("");
function editKeyFields(source: EventSource_): void {
keyFieldsOf.value = source;
keyFields.value = (source.key_fields ?? []).join(", ");
const sourceFields = {
label: { label: "Source name", required: true, write: api.sourceLabel },
webhook_path: { label: "Webhook path", required: true, write: api.sourceWebhookPath },
delivery_header: { label: "Delivery ID header", required: false, write: api.sourceDeliveryHeader },
key_fields: {
label: "Group by", required: false,
write: (id: string, value: string) => api.putSourceKeyFields(id, value.split(",").map((path) => path.trim()).filter(Boolean)),
},
};
const fieldEdit = ref<{ source: EventSource_; key: keyof typeof sourceFields; value: string } | null>(null);
function openField(source: EventSource_, key: keyof typeof sourceFields): void {
const value = key === "key_fields" ? (source.key_fields ?? []).join(", ") : source[key] ?? "";
fieldEdit.value = { source, key, value };
actionError.value = "";
}
async function saveKeyFields(): Promise<void> {
if (!keyFieldsOf.value) return;
busy.value = true;
actionError.value = "";
try {
const paths = keyFields.value.split(",").map((p) => p.trim()).filter(Boolean);
await api.putSourceKeyFields(keyFieldsOf.value.id, paths);
keyFieldsOf.value = null;
await reload();
} catch (cause) {
actionError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
async function saveField(): Promise<void> {
const edit = fieldEdit.value;
if (edit && await save(() => sourceFields[edit.key].write(edit.source.id, edit.value.trim()))) fieldEdit.value = null;
}
const pendingDelete = ref<EventSource_ | null>(null);
function deleteSource(): void {
const source = pendingDelete.value;
pendingDelete.value = null;
if (source) void save(() => api.sourceDelete(source.id));
}
const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c.name));
const connectorPlaceholder = computed(() => {
@@ -125,12 +152,13 @@ const connectorPlaceholder = computed(() => {
<template>
<div>
<Section v-if="issued" title="Webhook" :description="issued.token ? 'Copy the token now: it is not shown again.' : undefined">
<SettingRow label="URL"><CodeView :code="issued.url" /></SettingRow>
<SettingRow v-if="issued.token" label="Bearer token"><CodeView :code="issued.token" /></SettingRow>
<div class="flex justify-end"><Button size="sm" variant="outline" @click="issued = null">Done</Button></div>
<Section v-if="webhook" title="Webhook" :description="webhook.token || webhook.secret ? 'Copy the credential now. It won’t be shown again.' : undefined">
<SettingRow label="URL"><CodeView :code="webhook.url" /></SettingRow>
<SettingRow v-if="webhook.token" label="Bearer token"><CodeView :code="webhook.token" /></SettingRow>
<SettingRow v-if="webhook.secret" label="Signing secret"><CodeView :code="webhook.secret" /></SettingRow>
<div class="flex justify-end"><Button size="sm" variant="outline" @click="webhook = null">Done</Button></div>
</Section>
<p v-if="actionError && !adding && !keyFieldsOf" role="alert" class="mb-2 text-caption text-danger">{{ actionError }}</p>
<p v-if="actionError && !adding && !fieldEdit" role="alert" class="mb-2 text-caption text-danger">{{ actionError }}</p>
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<div v-else-if="!data" role="status" aria-label="Loading sources" class="space-y-2"><Skeleton class="h-8 w-full" /></div>
<template v-else>
@@ -140,13 +168,26 @@ const connectorPlaceholder = computed(() => {
<DataTable :columns="columns" :rows="data" :row-key="(s) => s.id" storage-key="sources">
<template #cell-label="{ row }"><span class="font-medium">{{ row.label }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.connector }}</span></template>
<template #cell-connector="{ row }">{{ row.connector }}</template>
<template #cell-verification="{ row }">{{ row.verification === "hmac" ? `HMAC (${row.hmac_header})` : row.verification === "none" ? "None" : "Bearer token" }}</template>
<template #cell-verification="{ row }">
<Badge :variant="signingKind(row.signing)">{{ row.verification === "hmac" ? `HMAC (${row.hmac_header})` : signingLabel(row.signing) }}</Badge>
</template>
<template #cell-key="{ row }"><span class="font-mono text-caption">{{ (row.key_fields ?? []).join(", ") || "Connector default" }}</span></template>
<template #actions="{ row }">
<MoreMenu :label="`${row.label} actions`">
<DropdownMenuItem @select="openEdit(row)">Edit…</DropdownMenuItem>
<DropdownMenuItem @select="editKeyFields(row)">Group by…</DropdownMenuItem>
<DropdownMenuItem :disabled="!!(webhook?.token || webhook?.secret)" @select="showWebhook(row)">Webhook URL</DropdownMenuItem>
<DropdownMenuItem @select="openEdit(row)">Edit connector and verification…</DropdownMenuItem>
<DropdownMenuItem @select="openField(row, 'label')">Rename…</DropdownMenuItem>
<DropdownMenuItem @select="openField(row, 'webhook_path')">Change webhook path…</DropdownMenuItem>
<DropdownMenuItem @select="openField(row, 'delivery_header')">Set delivery ID header…</DropdownMenuItem>
<DropdownMenuItem @select="openField(row, 'key_fields')">Group by…</DropdownMenuItem>
<DropdownMenuItem :disabled="busy" @select="toggleCapture(row)">{{ row.capture ? "Stop keeping payloads" : "Keep payloads" }}</DropdownMenuItem>
<DropdownMenuItem v-if="row.verification === 'token'" :disabled="busy" @select="put(row.connector, { verification: 'token' }, row)">Rotate token</DropdownMenuItem>
<DropdownMenuItem v-if="row.signing === 'signed'" :disabled="busy" @select="rotateSecret(row)">Rotate signing secret</DropdownMenuItem>
<DropdownMenuItem v-if="row.signing === 'signed'" :disabled="busy" @select="setSigning(row, false)">Request unsigned deliveries</DropdownMenuItem>
<DropdownMenuItem v-if="row.signing === 'unsigned_pending_approval'" :disabled="busy" @select="approveUnsigned(row)">Approve unsigned deliveries</DropdownMenuItem>
<DropdownMenuItem v-if="row.verification === 'none' && row.hmac_header" :disabled="busy" @select="setSigning(row, true)">Require signing</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" :disabled="busy" @select="pendingDelete = row">Delete source…</DropdownMenuItem>
</MoreMenu>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No sources</EmptyTitle></EmptyHeader></Empty></template>
@@ -198,8 +239,8 @@ const connectorPlaceholder = computed(() => {
<Input id="source-signature-prefix" v-model="draft.hmac_prefix" placeholder="sha256=" />
</Field>
<Field>
<FieldLabel for="source-signing-secret">{{ secretOptional ? "New signing secret (optional)" : "Signing secret" }}</FieldLabel>
<Input id="source-signing-secret" v-model="draft.hmac_secret" type="password" autocomplete="off" :required="!secretOptional" />
<FieldLabel for="source-signing-secret">Signing secret (optional)</FieldLabel>
<Input id="source-signing-secret" v-model="draft.hmac_secret" type="password" autocomplete="off" />
</Field>
</template>
<p v-if="actionError" role="alert" class="col-span-2 text-caption text-danger">{{ actionError }}</p>
@@ -213,16 +254,36 @@ const connectorPlaceholder = computed(() => {
</DialogContent>
</Dialog>
<Dialog :open="!!keyFieldsOf" @update:open="(open) => { if (!open) keyFieldsOf = null; }">
<DialogContent>
<DialogHeader><DialogTitle>Group {{ keyFieldsOf?.label }} events by</DialogTitle></DialogHeader>
<form id="key-fields" class="space-y-3" @submit.prevent="saveKeyFields">
<Input v-model="keyFields" aria-label="Field paths" placeholder="labels.alertname, labels.instance" />
<p class="text-caption text-fg-muted">Comma-separated field paths. Leave empty for the connector's default. Applies to events that arrive after you save.</p>
<Dialog :open="!!fieldEdit" @update:open="(open) => { if (!open) fieldEdit = null; }">
<DialogContent v-if="fieldEdit" class="top-[50dvh] left-[50dvw] max-w-[calc(100dvw-2rem)]">
<DialogHeader><DialogTitle>Edit {{ fieldEdit.source.label }}</DialogTitle></DialogHeader>
<form id="edit-source-field" class="flex flex-col gap-2" @submit.prevent="saveField">
<Field>
<FieldLabel for="source-field">{{ sourceFields[fieldEdit.key].label }}</FieldLabel>
<Input id="source-field" v-model="fieldEdit.value" :required="sourceFields[fieldEdit.key].required" />
</Field>
<p v-if="fieldEdit.key === 'key_fields'" class="text-caption text-fg-muted">Comma-separated field paths. Leave empty for the connector's default. Applies to events that arrive after you save.</p>
<p v-if="fieldEdit.key === 'webhook_path'" class="text-caption text-fg-muted">Senders must post to the new URL.</p>
<p v-if="actionError" role="alert" class="text-caption text-danger">{{ actionError }}</p>
</form>
<DialogFooter><Button type="submit" form="key-fields" :disabled="busy">Save</Button></DialogFooter>
<DialogFooter class="flex-row justify-end">
<Button type="button" variant="outline" @click="fieldEdit = null">Cancel</Button>
<Button type="submit" form="edit-source-field" :disabled="busy">Save</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog :open="!!pendingDelete" @update:open="(open) => { if (!open) pendingDelete = null; }">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {{ pendingDelete?.label }}?</AlertDialogTitle>
<AlertDialogDescription>Its webhook URL will stop accepting deliveries.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="deleteSource">Delete source</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
+12 -12
View File
@@ -663,25 +663,25 @@ export const api = {
request<T>(`/api/bindings/${encodeURIComponent(id)}/pause`, { method: "POST" }),
bindingResume: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/resume`, { method: "POST" }),
sourceSigning: <T = unknown>(id: string, signed: boolean) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/signing`, {
sourceSigning: (id: string, signed: boolean) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/signing`, {
method: "POST",
body: { signed },
}),
sourceApproveUnsigned: <T = unknown>(id: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/approve-unsigned`, {
sourceApproveUnsigned: (id: string) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/approve-unsigned`, {
method: "POST",
}),
sourceLabel: <T = unknown>(id: string, label: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/label`, { method: "PUT", body: { label } }),
sourceWebhookPath: <T = unknown>(id: string, path: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/webhook-path`, { method: "PUT", body: { path } }),
sourceDeliveryHeader: <T = unknown>(id: string, header: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/delivery-header`, { method: "PUT", body: { header } }),
sourceLabel: (id: string, label: string) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/label`, { method: "PUT", body: { label } }),
sourceWebhookPath: (id: string, path: string) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/webhook-path`, { method: "PUT", body: { path } }),
sourceDeliveryHeader: (id: string, header: string) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/delivery-header`, { method: "PUT", body: { header } }),
sourceDelete: (id: string) =>
request<void>(`/api/sources/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
sourceSecret: <T = unknown>(id: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/secret`, {
sourceSecret: (id: string) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/secret`, {
method: "POST",
}),
chatSessions: () => request<ChatSessions>("/api/chat/sessions"),
-55
View File
@@ -1,55 +0,0 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { Check, Copy, KeyRound, X } from "@lucide/vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { sourceURL, type Source } from "./source-signing";
const props = defineProps<{ source: Source }>();
const emit = defineEmits<{ dismiss: [] }>();
const url = computed(() => sourceURL(window.location.origin, props.source.webhook_path));
const copied = ref<string | null>(null);
async function copy(value: string): Promise<void> {
await navigator.clipboard.writeText(value);
copied.value = value;
setTimeout(() => (copied.value = null), 1500);
}
</script>
<template>
<Alert>
<KeyRound />
<AlertTitle class="flex items-center justify-between gap-2 text-caption">
<span class="font-mono"
>{{ source.label }} · signing secret, shown once</span
>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label="Dismiss"
@click="emit('dismiss')"
><X
/></Button>
</AlertTitle>
<AlertDescription class="col-start-2 flex items-center gap-2">
<code class="min-w-0 flex-1 break-all font-mono text-caption">{{ url }}</code>
<Button type="button" variant="ghost" size="icon-sm" aria-label="Copy URL" @click="copy(url)"><Check v-if="copied === url" /><Copy v-else /></Button>
</AlertDescription>
<AlertDescription class="col-start-2 flex items-center gap-2">
<code class="min-w-0 flex-1 break-all font-mono text-caption">{{
source.secret
}}</code>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label="Copy secret"
@click="copy(source.secret || '')"
>
<Check v-if="copied === source.secret" />
<Copy v-else />
</Button>
</AlertDescription>
</Alert>
</template>
-295
View File
@@ -1,295 +0,0 @@
<script setup lang="ts">
import { Check, Copy, Eye, EyeOff, KeyRound, Lock, LockOpen, Plus, Trash2 } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Section } from "@/components/ui/section";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { errors } from "@/copy/errors";
import { api } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { useLiveResource } from "@/stores/session";
import {
signingKind,
signingLabel,
sourceURL,
type Source,
} from "./source-signing";
import SourceSecret from "./SourceSecret.vue";
import { useSources } from "./use-sources";
/**
* Capture sources: the endpoint each sender posts to and its signing setting
* (docs/prds/event-automation.md "Sources"). Turning signing off is a request
* that takes effect only once approved.
*/
const {
sources,
loadError,
failure,
revealed,
busy,
load,
create,
newSecret,
requestUnsigned,
requireSigning,
approveUnsigned,
rename,
setWebhookPath,
setDeliveryHeader,
setCapture,
remove,
} = useSources();
const connectors = useRead(() => api.extensions("connectors"));
const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c.name));
const connector = ref("");
const header = ref("");
const pending = ref<Source | null>(null);
const label = ref("");
const copied = ref<string | null>(null);
useLiveResource(null, () => void load());
onMounted(() => {
void load();
void connectors.reload();
});
async function copy(value: string): Promise<void> {
await navigator.clipboard.writeText(value);
copied.value = value;
setTimeout(() => (copied.value = null), 1500);
}
async function submit(): Promise<void> {
await create(label.value.trim(), connector.value, header.value.trim());
if (!failure.value) {
label.value = "";
header.value = "";
}
}
function url(source: Source): string {
return sourceURL(window.location.origin, source.webhook_path);
}
</script>
<template>
<section class="mb-6 flex flex-col gap-3">
<form
class="flex flex-wrap items-center justify-end gap-2"
@submit.prevent="submit"
>
<Input
v-model="label"
class="w-full sm:w-48"
placeholder="Source name"
aria-label="Source name"
required
/>
<Select v-model="connector" required>
<SelectTrigger class="w-full sm:w-44" aria-label="Connector"><SelectValue placeholder="Connector" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="name in connectorNames" :key="name" :value="name">{{ name }}</SelectItem>
</SelectContent>
</Select>
<Input
v-model="header"
class="w-full font-mono sm:w-48"
placeholder="Signature header"
aria-label="Signature header"
required
/>
<Button type="submit" variant="outline" :disabled="busy || !label || !connector || !header">
<Plus data-icon="inline-start" />
New source</Button>
</form>
<Alert v-if="failure" variant="destructive">
<AlertTitle>{{ errors.sources.panel.writeFailed }}</AlertTitle>
<AlertDescription>{{ failure }}</AlertDescription>
</Alert>
<Alert v-if="loadError" variant="destructive">
<AlertTitle>{{ errors.sources.panel.loadFailed }}</AlertTitle>
<AlertDescription>{{ loadError }} <Button variant="link" size="xs" @click="load">Retry</Button></AlertDescription>
</Alert>
<SourceSecret v-if="revealed" :source="revealed" @dismiss="revealed = null" />
<Section v-if="sources && sources.length">
<Table>
<TableHeader>
<TableRow>
<TableHead>Source</TableHead>
<TableHead>Signing</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="source in sources" :key="source.id">
<TableCell class="font-mono text-fg-muted">
<div class="flex w-64 max-w-full min-w-0 flex-col gap-1">
<Input
class="h-7 border-transparent px-1 font-sans shadow-none hover:border-input dark:bg-transparent"
:model-value="source.label"
placeholder="Name this source"
:aria-label="`Name of source ${source.label}`"
:disabled="busy"
@change="rename(source, ($event.target as HTMLInputElement).value)"
/>
<Tooltip><TooltipTrigger as-child>
<Input
class="h-6 border-transparent px-1 font-mono text-caption text-fg-muted shadow-none hover:border-input md:text-caption dark:bg-transparent"
:model-value="source.webhook_path"
placeholder="Webhook path"
:aria-label="`Webhook path of source ${source.label}`"
pattern="[a-z][a-z0-9\-]*"
:disabled="busy"
@change="setWebhookPath(source, ($event.target as HTMLInputElement).value)"
/>
</TooltipTrigger><TooltipContent>{{ url(source) }}</TooltipContent></Tooltip>
<Input
class="h-6 border-transparent px-1 font-mono text-caption text-fg-muted shadow-none hover:border-input md:text-caption dark:bg-transparent"
:model-value="source.delivery_header ?? ''"
placeholder="Delivery ID header"
title="The header the sender repeats on every retry of one delivery; a retry then starts no second run"
:aria-label="`Delivery ID header of source ${source.label}`"
:disabled="busy"
@change="setDeliveryHeader(source, ($event.target as HTMLInputElement).value)"
/>
</div></TableCell
>
<TableCell>
<Badge :variant="signingKind(source.signing)">{{
signingLabel(source.signing)
}}</Badge>
</TableCell>
<TableCell>
<div class="flex flex-wrap items-center justify-end gap-1">
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
aria-label="Copy URL"
@click="copy(url(source))"
>
<Check v-if="copied === url(source)" />
<Copy v-else />
</Button>
</TooltipTrigger>
<TooltipContent>Copy URL</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
aria-label="New secret"
:disabled="busy"
@click="newSecret(source)"
>
<KeyRound />
</Button>
</TooltipTrigger>
<TooltipContent>New secret</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
:aria-label="source.capture ? 'Stop keeping payloads' : 'Keep payloads'"
:disabled="busy"
@click="setCapture(source, !source.capture)"
>
<Eye v-if="source.capture" />
<EyeOff v-else />
</Button>
</TooltipTrigger>
<TooltipContent>{{ source.capture ? "Stop keeping payloads" : "Keep payloads" }}</TooltipContent>
</Tooltip>
<Button
v-if="source.signing === 'signed'"
variant="outline"
size="sm"
:disabled="busy"
@click="requestUnsigned(source)"
>
<LockOpen data-icon="inline-start" />
Turn off signing</Button>
<Button
v-if="source.signing === 'unsigned_pending_approval'"
size="sm"
:disabled="busy"
@click="approveUnsigned(source)"
>
<Check data-icon="inline-start" />
Approve unsigned</Button>
<Button
v-if="source.signing === 'unsigned' || source.signing === 'unsigned_pending_approval'"
variant="outline"
size="sm"
:disabled="busy"
@click="requireSigning(source)"
>
<Lock data-icon="inline-start" />
Require signing</Button>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
aria-label="Delete source"
:disabled="busy"
@click="pending = source"
>
<Trash2 />
</Button>
</TooltipTrigger>
<TooltipContent>Delete source</TooltipContent>
</Tooltip>
</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
</Section>
<Empty v-else-if="sources && !loadError">
<EmptyHeader><EmptyTitle>No sources yet</EmptyTitle></EmptyHeader>
</Empty>
</section>
<AlertDialog :open="pending !== null" @update:open="(v: boolean) => { if (!v) pending = null; }">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete source?</AlertDialogTitle>
<AlertDialogDescription>Delete the source "{{ pending?.label }}"? Its webhook endpoint stops accepting deliveries.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="if (pending) { const src = pending; pending = null; remove(src); }">Delete source</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</template>
-36
View File
@@ -1,39 +1,3 @@
/**
* The sources vocabulary: a source as the panel shows it, and the signing
* states the server reports. A source's secret is only ever in the response to
* the write that generated it.
*/
import type { EventSource_ } from "@/lib/api";
export interface Source {
/** The source's id, which never changes. */
id: string;
/** The name people see. */
label: string;
/** The last segment of the webhook URL; it can be changed. */
webhook_path: string;
/** The header the sender repeats on every retry of one delivery. */
delivery_header?: string;
signing?: string;
/** Whether the source keeps each delivery's headers and payload. */
capture: boolean;
/** Present only on create and on a new secret. */
secret?: string;
}
export function toSource(view: EventSource_): Source {
return {
id: view.id,
label: view.label,
webhook_path: view.webhook_path,
delivery_header: view.delivery_header,
signing: view.signing,
capture: view.capture,
secret: view.secret,
};
}
export type SigningKind = "ok" | "info" | "warn" | "idle";
const LABELS: Record<string, string> = {
-84
View File
@@ -1,84 +0,0 @@
import { ref } from "vue";
import { errors } from "@/copy/errors";
import { api, describeError, type EventSource_ } from "@/lib/api";
import { toSource, type Source } from "./source-signing";
/**
* The sources list and its writes. A write that generates a secret keeps the
* returned source in `revealed` until dismissed: it is the only time the
* browser ever holds that secret.
*/
export function useSources() {
// null means loading, [] means loaded and empty.
const sources = ref<Source[] | null>(null);
// Read failures are kept apart from write failures: a failed load is not "a
// write that did not take effect", and belongs next to the list, with Retry.
const loadError = ref<string | null>(null);
const failure = ref<string | null>(null);
const revealed = ref<Source | null>(null);
const busy = ref(false);
let generation = 0;
async function load(): Promise<void> {
const current = ++generation;
try {
const res = await api.eventSources();
if (current !== generation) return;
sources.value = res.map(toSource);
failure.value = null;
loadError.value = null;
} catch (err) {
if (current !== generation) return;
loadError.value = describeError(err, errors.common.unknown);
}
}
async function run(write: () => Promise<Source | void>): Promise<void> {
busy.value = true;
failure.value = null;
try {
const result = await write();
if (result?.secret) revealed.value = result;
await load();
} catch (err) {
failure.value = describeError(err, errors.common.unknown);
} finally {
busy.value = false;
}
}
const source = (write: Promise<EventSource_>) => write.then(toSource);
return {
sources,
loadError,
failure,
revealed,
busy,
load,
// A new source signs with an HMAC over the body; the server generates the
// secret and returns it once.
create: (label: string, connector: string, header: string) =>
run(async () => {
const created = await api.createEventSource({ label, connector, verification: "hmac", hmac_header: header });
return {
id: created.id, label, webhook_path: created.url.split("/").pop() ?? "",
signing: "signed", capture: true, secret: created.secret,
};
}),
newSecret: (s: Source) => run(() => source(api.sourceSecret<EventSource_>(s.id))),
requestUnsigned: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.id, false))),
requireSigning: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.id, true))),
approveUnsigned: (s: Source) => run(() => source(api.sourceApproveUnsigned<EventSource_>(s.id))),
rename: (s: Source, label: string) => run(() => source(api.sourceLabel<EventSource_>(s.id, label.trim()))),
setWebhookPath: (s: Source, path: string) =>
run(() => source(api.sourceWebhookPath<EventSource_>(s.id, path.trim()))),
setDeliveryHeader: (s: Source, header: string) =>
run(() => source(api.sourceDeliveryHeader<EventSource_>(s.id, header.trim()))),
setCapture: (s: Source, capture: boolean) => run(() => source(api.sourceCapture(s.id, capture))),
// A trigger that names the source refuses the delete; the refusal shows
// as the panel's failure.
remove: (s: Source) => run(() => api.sourceDelete(s.id)),
};
}