From 2a0911a964071e2dffec3fc320a92dec4aa89f2e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 26 Oct 2026 12:51:28 -0400 Subject: [PATCH 1/7] Webhooks: endpoint settings in the dashboard, and docs for the webhooks CoderHelm sends - Settings, Webhooks: add endpoints (https address, description, events grouped by the catalog or all events, on/off), the secret shown once, reveal and rotate with an overlap, send a test event, recent deliveries with every attempt and Resend, and replay a time range. Admins only (the webhooks capability). - Deliveries: webhook rows are labelled, Resend works for them, and a row links to its endpoint. - Docs: /api/webhooks/ is now about outbound webhooks: quick start, the event catalog generated from the platform's OpenAPI `webhooks` section, signature checks in Node, Python, Go and Rust, retries and the disable rule, testing, security and versioning. The inbound content moves to /api/incoming-webhooks/, with redirects for the moved reference pages. - Pins the platform at the commit that adds outbound webhooks. --- dashboard/e2e/webhooks.spec.ts | 258 ++++ dashboard/e2e/wide-data/addresses.ts | 2 + dashboard/e2e/wide-data/settings.ts | 37 + dashboard/src/app/settings/webhooks/page.tsx | 1130 ++++++++++++++++++ dashboard/src/components/deliveries.tsx | 16 +- dashboard/src/components/settings-items.tsx | 1 + dashboard/src/lib/api.ts | 4 +- dashboard/src/lib/capabilities.ts | 1 + dashboard/src/lib/routes.ts | 1 + dashboard/src/lib/webhooks.ts | 162 +++ docs/content/docs/api/incoming-webhooks.mdx | 170 +++ docs/content/docs/api/index.mdx | 1 + docs/content/docs/api/meta.json | 5 +- docs/content/docs/api/webhooks.mdx | 385 ++++-- docs/content/docs/index.mdx | 1 + docs/e2e/site.spec.ts | 38 +- docs/platform.lock.json | 2 +- docs/published-pages.json | 18 + docs/redirects.json | 7 +- docs/scripts/import-platform.mjs | 20 +- docs/scripts/lib/webhook-events.mjs | 117 ++ docs/scripts/webhook-events.test.mjs | 70 ++ 22 files changed, 2318 insertions(+), 128 deletions(-) create mode 100644 dashboard/e2e/webhooks.spec.ts create mode 100644 dashboard/src/app/settings/webhooks/page.tsx create mode 100644 dashboard/src/lib/webhooks.ts create mode 100644 docs/content/docs/api/incoming-webhooks.mdx create mode 100644 docs/scripts/lib/webhook-events.mjs create mode 100644 docs/scripts/webhook-events.test.mjs diff --git a/dashboard/e2e/webhooks.spec.ts b/dashboard/e2e/webhooks.spec.ts new file mode 100644 index 00000000..9d4a85b0 --- /dev/null +++ b/dashboard/e2e/webhooks.spec.ts @@ -0,0 +1,258 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; + +// Settings, Webhooks: the endpoints Coderhelm sends the team's events to. +// List, add (the secret is shown once), an address the gateway refuses, a +// test that fails with its reason, reveal and rotate the secret, resend a +// delivery and replay a range. Every API call is answered here. + +const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots"); +const SECRET = "whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD7vS8nSUIQ2c="; +const ROTATED = "whsec_k0q8vX2mZp5Rr3t1YbN6cH9dLwE4fJ7aS1uG0iT2oQs="; +const iso = (minsAgo: number) => new Date(Date.now() - minsAgo * 60_000).toISOString(); + +const LONG_URL = "https://hooks.internal-tools.example.com/coderhelm/webhooks/receive-every-event-for-the-deploy-bot-and-the-release-dashboard"; + +interface Endpoint { + id: string; + url: string; + description: string; + events: string[]; + enabled: boolean; + disabled_reason: string; + secret_hint: string; + previous_secret_expires_at?: string | null; + failing_since?: string | null; + last_success_at?: string | null; + last_failure_at?: string | null; + created_at: string; + created_by: string; + updated_at: string; +} + +function endpoint(id: string, over: Partial = {}): Endpoint { + return { + id, url: LONG_URL, description: "Deploy bot", events: ["run.completed", "run.failed"], enabled: true, disabled_reason: "", + secret_hint: "whsec_…Q2c=", last_success_at: iso(15), created_at: iso(60 * 24 * 4), created_by: "admin@example.com", updated_at: iso(60), + ...over, + }; +} + +const TYPES = [ + ["run.created", "Runs", "A run started"], ["run.completed", "Runs", "A run finished"], ["run.failed", "Runs", "A run failed"], + ["run.needs_input", "Runs", "A run is waiting for a person"], ["pull_request.opened", "Pull requests", "Coderhelm opened a pull request"], + ["review.completed", "Reviews", "A review was posted"], ["ci_fix.started", "CI fixes", "A CI fix started"], ["ci_fix.completed", "CI fixes", "A CI fix finished"], + ["alert.received", "Alerts", "An alert arrived"], ["log_finding.created", "Logs", "A new log finding"], ["log_finding.resolved", "Logs", "A log finding went away"], + ["release_notes.published", "Releases", "Release notes went out"], ["plan.approved", "Plans", "A plan was approved"], + ["plugin.run.completed", "Plugins", "A plugin run finished"], ["webhook.test", "Testing", "A test event"], +].map(([type, group, summary]) => ({ type, group, summary, description: summary, subscribable: type !== "webhook.test", example: {} })); + +const delivery = (id: string, over: Record = {}) => ({ + id, event_id: `evt_${id}`, event: "run.completed", status: "handled", outcome: "Delivered (200)", reason: "", reason_message: "", reason_fix: "", + attempts: [{ at: iso(10), code: 200, duration_ms: 87, error: "" }], next_retry_at: null, created_at: iso(10), + payload_preview: JSON.stringify({ id: `evt_${id}`, type: "run.completed", data: { run_id: "01JBRUN" } }, null, 2), + headers: { "content-type": "application/json", "webhook-id": `evt_${id}`, "webhook-timestamp": "1792420307", "webhook-signature": "[redacted]" }, + ...over, +}); + +const REFUSED = { + status: "failed", outcome: "Refused (401)", reason: "webhook_refused", + reason_message: "Your webhook endpoint refused the event (a 4xx answer), so it isn't retried.", + reason_fix: "Check that the endpoint verifies signatures with the right secret and accepts JSON, then press Resend.", + attempts: [{ at: iso(1), code: 401, duration_ms: 112, error: "Answered 401: bad signature" }], +}; + +interface Db { + endpoints: Endpoint[]; + deliveries: ReturnType[]; + calls: { method: string; path: string; body: Record | null }[]; +} + +async function mockApi(page: Page, me: Record = { role: "admin" }): Promise { + const db: Db = { + endpoints: [ + endpoint("ep_one"), + endpoint("ep_two", { url: "https://status.example.com/hooks/coderhelm", description: "", events: ["*"], enabled: false, disabled_reason: "failing", failing_since: iso(60 * 24 * 6), last_success_at: null }), + ], + deliveries: [delivery("d1"), delivery("d2", { ...REFUSED, event: "run.failed", attempts: [{ at: iso(40), code: 500, duration_ms: 300, error: "Answered 500" }, { at: iso(35), code: 401, duration_ms: 112, error: "Answered 401: bad signature" }] })], + calls: [], + }; + const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const req = route.request(); + const p = new URL(req.url()).pathname; + const method = req.method(); + let body: Record | null = null; + try { body = req.postDataJSON(); } catch { body = null; } + db.calls.push({ method, path: p, body }); + if (p === "/api/me") return json(route, { user_id: "u1", team_id: "t_1", github_login: null, email: "admin@example.com", avatar_url: "", ...me }); + if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] }); + if (p === "/api/webhooks/event-types") return json(route, { api_version: "2026-10-26", event_types: TYPES }); + if (p === "/api/webhooks/endpoints" && method === "GET") return json(route, { endpoints: db.endpoints, max: 20, disable_after_days: 5, retention_days: 14 }); + if (p === "/api/webhooks/endpoints" && method === "POST") { + if (String(body?.url).includes("10.0.0.5")) { + return json(route, { error: "That address is inside a private network, so we can't reach it from here.", code: "bad_request", field: "url" }, 400); + } + const made = endpoint("ep_new", { url: String(body?.url), description: String(body?.description ?? ""), events: body?.events as string[], last_success_at: null }); + db.endpoints.push(made); + return json(route, { endpoint: made, secret: SECRET }, 201); + } + const m = p.match(/^\/api\/webhooks\/endpoints\/([^/]+)(\/.*)?$/); + if (m) { + const ep = db.endpoints.find((e) => e.id === m[1]); + const rest = m[2] ?? ""; + if (!ep) return json(route, { error: "No such webhook endpoint." }, 404); + if (!rest && method === "GET") return json(route, ep); + if (!rest && method === "PUT") { Object.assign(ep, body); if (body?.enabled === true) { ep.disabled_reason = ""; ep.failing_since = null; } return json(route, ep); } + if (!rest && method === "DELETE") { db.endpoints = db.endpoints.filter((e) => e !== ep); return json(route, { deleted: true }); } + if (rest === "/secret") return json(route, { secret: SECRET, previous_secret_expires_at: null }); + if (rest === "/secret/rotate") { + const until = Number(body?.overlap_hours) > 0 ? iso(-60 * Number(body?.overlap_hours)) : null; + ep.previous_secret_expires_at = until; + ep.secret_hint = "whsec_…oQs="; + return json(route, { secret: ROTATED, previous_secret_expires_at: until }); + } + if (rest === "/test") { + const d = delivery("dtest", { ...REFUSED, event: "webhook.test", event_id: "evt_test" }); + db.deliveries.unshift(d); + return json(route, d); + } + if (rest === "/deliveries") return json(route, { deliveries: db.deliveries }); + const r = rest.match(/^\/deliveries\/([^/]+)\/resend$/); + if (r) { + const d = db.deliveries.find((x) => x.id === r[1])!; + Object.assign(d, { status: "handled", outcome: "Delivered (200)", reason: "", reason_message: "", reason_fix: "", attempts: [...(d.attempts as unknown[]), { at: iso(0), code: 200, duration_ms: 64, error: "" }] }); + return json(route, d); + } + if (rest === "/replay") return json(route, { queued: 3, found: 7, capped: false }, 202); + } + return json(route, { error: `Not mocked: ${method} ${p}` }, 404); + }); + return db; +} + +/** Full-page screenshots at 1440 and 390, failing if the page scrolls sideways. */ +async function shot(page: Page, name: string) { + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + await page.addStyleTag({ content: "nextjs-portal{display:none!important}" }); + for (const width of [1440, 390]) { + await page.setViewportSize({ width, height: 900 }); + await page.waitForTimeout(250); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow, `${name} scrolls sideways at ${width}px`).toBeLessThanOrEqual(0); + await page.screenshot({ path: path.join(SHOTS_DIR, `${name}-${width}.png`), fullPage: true }); + } + await page.setViewportSize({ width: 1440, height: 900 }); +} + +test.beforeEach(async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }); +}); + +test("an admin sees each endpoint with its events and health", async ({ page }) => { + await mockApi(page); + await page.goto("/settings/webhooks/"); + await expect(page.getByRole("heading", { level: 1, name: "Webhooks" })).toBeVisible(); + const list = page.getByRole("list", { name: "Webhook endpoints" }); + await expect(list.getByTestId("webhook-endpoint")).toHaveCount(2); + const one = list.locator('[data-id="ep_one"]'); + await expect(one).toContainText("run.completed, run.failed"); + await expect(one).toContainText("Deploy bot"); + const two = list.locator('[data-id="ep_two"]'); + await expect(two).toContainText("All events"); + await expect(two).toContainText("Turned off: kept failing"); + await expect(page.getByRole("link", { name: "Read the webhooks guide" })).toHaveAttribute("href", "https://docs.coderhelm.com/api/webhooks/"); + await shot(page, "webhooks-list"); +}); + +test("adding an endpoint shows the address error the gateway names, then the secret once", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/settings/webhooks/"); + await page.getByRole("button", { name: "Add endpoint" }).first().click(); + const dialog = page.getByRole("dialog", { name: "Add a webhook endpoint" }); + await dialog.getByLabel("Address").fill("https://10.0.0.5/hook"); + await dialog.getByRole("button", { name: "Add endpoint" }).click(); + await expect(dialog.getByText("That address is inside a private network")).toBeVisible(); + await expect(dialog.getByLabel("Address")).toHaveAttribute("aria-invalid", "true"); + + await dialog.getByLabel("Address").fill(LONG_URL); + await dialog.getByLabel("Description").fill("Release dashboard"); + await dialog.getByRole("checkbox", { name: /All events/ }).uncheck(); + await dialog.getByRole("checkbox", { name: /review\.completed/ }).check(); + await dialog.getByRole("checkbox", { name: /run\.failed/ }).check(); + await dialog.getByRole("button", { name: "Add endpoint" }).click(); + const post = db.calls.filter((c) => c.method === "POST" && c.path === "/api/webhooks/endpoints").pop(); + expect(post?.body).toEqual({ url: LONG_URL, description: "Release dashboard", events: ["review.completed", "run.failed"], enabled: true }); + + const made = page.getByRole("dialog", { name: "Endpoint added" }); + await expect(made.getByTestId("new-webhook-secret")).toHaveText(SECRET); + await expect(made).toContainText("You won't see it again here"); + await shot(page, "webhooks-created"); + await made.getByRole("button", { name: "Done" }).click(); + await expect(page.getByText(SECRET)).toHaveCount(0); + await expect(page.getByRole("list", { name: "Webhook endpoints" }).getByTestId("webhook-endpoint")).toHaveCount(3); +}); + +test("an endpoint's page: test, reveal and rotate, resend and replay", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/settings/webhooks/?endpoint=ep_one"); + await expect(page.getByTestId("webhook-endpoint-page")).toBeVisible(); + + // A test event that the endpoint refuses shows the reason and the fix. + await page.getByRole("button", { name: "Send test event" }).click(); + const result = page.getByTestId("test-result"); + await expect(result).toHaveAttribute("data-status", "failed"); + await expect(result).toContainText("refused the event"); + await expect(result).toContainText("HTTP 401"); + await expect(result).toContainText("How to fix"); + + // Reveal, then rotate with the default 24 hour overlap. + await page.getByRole("button", { name: "Reveal" }).click(); + await expect(page.getByTestId("webhook-secret")).toHaveText(SECRET); + await page.getByRole("button", { name: "Rotate secret" }).click(); + await page.getByTestId("confirm-dialog").getByRole("button", { name: "Make a new secret" }).click(); + await expect(page.getByTestId("rotated-secret")).toContainText(ROTATED); + await expect(page.getByTestId("rotated-secret")).toContainText("keeps signing too until"); + expect(db.calls.find((c) => c.path.endsWith("/secret/rotate"))?.body).toEqual({ overlap_hours: 24 }); + + // Resend the failed delivery. + const failed = page.getByTestId("webhook-delivery").filter({ hasText: "run.failed" }); + await failed.getByRole("button", { name: "Attempts" }).click(); + await expect(failed).toContainText("Answered 401: bad signature"); + await shot(page, "webhooks-endpoint"); + await failed.getByRole("button", { name: "Resend" }).click(); + await expect(failed).toHaveAttribute("data-status", "handled"); + expect(db.calls.some((c) => c.method === "POST" && c.path === "/api/webhooks/endpoints/ep_one/deliveries/d2/resend")).toBe(true); + + // Replay the last day's missed events. + await page.getByRole("button", { name: "Replay", exact: true }).click(); + await expect(page.getByTestId("replay-result")).toContainText("3 events queued"); + const replay = db.calls.find((c) => c.path.endsWith("/replay")); + expect(replay?.body?.only_failed).toBe(true); + expect(typeof replay?.body?.since).toBe("string"); +}); + +test("turning a failing endpoint back on, and deleting one", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/settings/webhooks/?endpoint=ep_two"); + await expect(page.getByTestId("endpoint-health")).toContainText("5 days"); + await page.getByTestId("toggle-endpoint").click(); + await expect(page.getByTestId("endpoint-health")).toHaveCount(0); + expect(db.calls.find((c) => c.method === "PUT")?.body).toEqual({ enabled: true }); + await page.getByRole("button", { name: "More" }).click(); + await page.getByRole("menuitem", { name: "Delete endpoint" }).click(); + await page.getByTestId("confirm-dialog").getByRole("button", { name: "Delete endpoint" }).click(); + await expect(page).toHaveURL(/\/settings\/webhooks\/?$/); + expect(db.calls.some((c) => c.method === "DELETE" && c.path === "/api/webhooks/endpoints/ep_two")).toBe(true); +}); + +test("members can't open the page", async ({ page }) => { + await mockApi(page, { role: "member" }); + await page.goto("/settings/webhooks/"); + await expect(page.getByText("This page needs a different role")).toBeVisible(); + await expect(page.getByRole("button", { name: "Add endpoint" })).toHaveCount(0); +}); diff --git a/dashboard/e2e/wide-data/addresses.ts b/dashboard/e2e/wide-data/addresses.ts index 78274aca..0ef4fb3a 100644 --- a/dashboard/e2e/wide-data/addresses.ts +++ b/dashboard/e2e/wide-data/addresses.ts @@ -28,5 +28,7 @@ export const SAMPLE_QUERY: Record = { "/plugins/draft": `?id=${DRAFT_ID}`, "/plugins/runs": `?id=${PLUGIN_RUN_ID}`, // Not an item's page, but its fullest view is a delivery's details. + // Not an item's page, but its fullest view is one endpoint with its deliveries. + "/settings/webhooks": "?endpoint=ep_01jbendpt4a7b0c3d6e9f2g5h8widewide", "/settings/deliveries": `?id=${encodeURIComponent("github:4f1c2a9e-8b7d-6c5f-4e3d-2c1b0a9f8e7d6c5b4a39")}`, }; diff --git a/dashboard/e2e/wide-data/settings.ts b/dashboard/e2e/wide-data/settings.ts index 21edcf8f..088fc9fc 100644 --- a/dashboard/e2e/wide-data/settings.ts +++ b/dashboard/e2e/wide-data/settings.ts @@ -178,6 +178,30 @@ const WIDE_DELIVERY_ROW = { target: LONG_URL, status: "failed", outcome: TOKEN, reason: "handler_error", external_id: SHA, repo: REPO, pr: 12345, created_at: iso(31), duration_ms: 40_000, attempts: 2, next_retry_at: null, }; +export const WIDE_ENDPOINT = { + id: "ep_01jbendpt4a7b0c3d6e9f2g5h8widewide", + url: `${API_URL}/coderhelm/webhooks/receive-every-event-with-a-very-long-path-segment`, + description: `${SENTENCE} ${TOKEN}`, + events: ["run.created", "run.completed", "run.failed", "run.needs_input", "pull_request.opened", "review.completed", "ci_fix.started", "ci_fix.completed", "alert.received", "log_finding.created"], + enabled: true, + disabled_reason: "", + secret_hint: "whsec_…Q2c=", + previous_secret_expires_at: iso(-60 * 20), + failing_since: iso(60 * 30), + last_success_at: iso(60 * 31), + last_failure_at: iso(5), + created_at: iso(60 * 24 * 10), + created_by: EMAIL, + updated_at: iso(60), +}; + +const WIDE_EVENT_TYPES = [ + ["run.created", "Runs"], ["run.completed", "Runs"], ["run.failed", "Runs"], ["run.needs_input", "Runs"], + ["pull_request.opened", "Pull requests"], ["review.completed", "Reviews"], ["ci_fix.started", "CI fixes"], ["ci_fix.completed", "CI fixes"], + ["alert.received", "Alerts"], ["log_finding.created", "Logs"], ["log_finding.resolved", "Logs"], ["release_notes.published", "Releases"], + ["plan.approved", "Plans"], ["plugin.run.completed", "Plugins"], ["webhook.test", "Testing"], +].map(([type, group]) => ({ type, group, summary: SENTENCE, description: SENTENCE, subscribable: type !== "webhook.test", example: {} })); + export const settingsData: Handler = ({ method, path, url }) => { if (method !== "GET") return undefined; const p = decodeURIComponent(path); @@ -192,6 +216,19 @@ export const settingsData: Handler = ({ method, path, url }) => { can_redeliver: true, }; } + // Webhooks: a long address, a long description, every event and an unbroken error. + if (p === "/api/webhooks/endpoints") return { endpoints: [WIDE_ENDPOINT, { ...WIDE_ENDPOINT, id: "ep_wide2", enabled: false, disabled_reason: "failing", events: ["*"] }], max: 20, disable_after_days: 5, retention_days: 14 }; + if (p === "/api/webhooks/event-types") return { api_version: "2026-10-26", event_types: WIDE_EVENT_TYPES }; + if (p === `/api/webhooks/endpoints/${WIDE_ENDPOINT.id}`) return WIDE_ENDPOINT; + if (p === `/api/webhooks/endpoints/${WIDE_ENDPOINT.id}/deliveries`) { + return { deliveries: [{ + id: "01JWIDEDELIVERY0000000000001", event_id: "evt_01JBEVNT8M1N4P7Q0R3S6T9V2WWIDEWIDEWIDE", event: "run.needs_input", status: "failed", + outcome: "Refused (401)", reason: "webhook_refused", reason_message: SENTENCE, reason_fix: `${SENTENCE} ${LONG_URL}`, + attempts: [{ at: iso(30), code: 401, duration_ms: 112, error: TOKEN }, { at: iso(20), duration_ms: 10_000, error: SENTENCE }], + next_retry_at: iso(-60), created_at: iso(30), payload_preview: JSON.stringify({ data: { pr_url: LONG_URL, error: TOKEN } }, null, 2), + headers: { "webhook-id": "evt_01JBEVNT8M1N4P7Q0R3S6T9V2WWIDEWIDEWIDE", "webhook-signature": "[redacted]", "user-agent": LONG_URL }, + }] }; + } if (p === "/api/users") return { users: USERS }; // Sign-in (self-hosted): long domains, long names and an unbroken email. if (p === "/api/sign-in") { diff --git a/dashboard/src/app/settings/webhooks/page.tsx b/dashboard/src/app/settings/webhooks/page.tsx new file mode 100644 index 00000000..1c3617be --- /dev/null +++ b/dashboard/src/app/settings/webhooks/page.tsx @@ -0,0 +1,1130 @@ +"use client"; + +import Link from "next/link"; +import { useRouter, useSearchParams } from "next/navigation"; +import { Suspense, useCallback, useEffect, useId, useState, type FormEvent } from "react"; +import { RoleGuard } from "@/components/role-guard"; +import { Page, PageHeader, SectionHeading, cardClass } from "@/components/page"; +import { Callout } from "@/components/callout"; +import { Problem } from "@/components/problem"; +import { EmptyState } from "@/components/empty-state"; +import { Chip, List, ListRow, formatDate, formatMs, type Tone } from "@/components/list"; +import { RepeatIcon } from "@/components/icons"; +import { Field } from "@/components/field"; +import { Modal } from "@/components/modal"; +import { CopyButton } from "@/components/copy-button"; +import { CodeBlock } from "@/components/code-block"; +import { Disclosure } from "@/components/disclosure"; +import { Skeleton } from "@/components/skeleton"; +import { Select } from "@/components/select"; +import { Code } from "@/components/settings/code"; +import { useConfirm } from "@/components/confirm-dialog"; +import { useToast } from "@/components/toast"; +import { useCan } from "@/hooks/use-can"; +import { relativeTime } from "@/lib/team"; +import { + WEBHOOK_DOCS_URL, + WebhookError, + endpointHref, + eventsSummary, + groupEvents, + webhooksApi, + type EndpointInput, + type ReplayResult, + type WebhookDelivery, + type WebhookEndpoint, + type WebhookEndpointList, + type WebhookEventType, +} from "@/lib/webhooks"; +import { + buttonClass, + focusRing, + fullWidthOnPhone, + inputClass, + linkButton, + monoInputClass, + primaryButton, + secondaryButton, + smallSecondaryButton, +} from "@/components/ui"; + +export default function WebhooksPageGuarded() { + return ( + + + + + + ); +} + +function WebhooksRouter() { + const id = useSearchParams().get("endpoint") ?? ""; + return id ? : ; +} + +/** The host of an address, for a short name. */ +function hostOf(url: string): string { + try { + return new URL(url).host || url; + } catch { + return url; + } +} + +const errText = (e: unknown, fallback: string) => (e instanceof Error ? e.message : fallback); + +// ── Event types ───────────────────────────────────────────────────── + +function useEventTypes() { + const [types, setTypes] = useState(null); + const [error, setError] = useState(""); + useEffect(() => { + webhooksApi + .eventTypes() + .then((d) => setTypes(d.event_types)) + .catch((e) => setError(errText(e, "Could not load the event types."))); + }, []); + return { types, error }; +} + +/** Health in a few words, with a tone for the status dot. */ +function health(e: WebhookEndpoint, disableAfter: number): { tone: Tone; label: string; detail?: string } { + if (!e.enabled && e.disabled_reason === "failing") { + return { + tone: "danger", + label: "Turned off: kept failing", + detail: `Coderhelm turned it off after ${disableAfter} days in a row with no delivery getting through. Fix the endpoint, then turn it back on and replay the events it missed.`, + }; + } + if (!e.enabled) return { tone: "muted", label: "Off" }; + if (e.failing_since) { + return { + tone: "waiting", + label: `Failing since ${relativeTime(e.failing_since) ?? formatDate(e.failing_since)}`, + detail: `If nothing gets through for ${disableAfter} days in a row, Coderhelm turns it off and tells the team's admins.`, + }; + } + return { tone: "success", label: "On" }; +} + +// ── The list ──────────────────────────────────────────────────────── + +function EndpointsPage() { + const { can } = useCan(); + const [data, setData] = useState(null); + const [error, setError] = useState(""); + const [creating, setCreating] = useState(false); + const [made, setMade] = useState<{ endpoint: WebhookEndpoint; secret: string } | null>(null); + const { types, error: typesError } = useEventTypes(); + const canManage = can("webhooks"); + + const load = useCallback(() => { + webhooksApi + .list() + .then((d) => { + setData(d); + setError(""); + }) + .catch((e) => setError(errText(e, "The request failed."))); + }, []); + useEffect(load, [load]); + + const full = !!data && data.endpoints.length >= data.max; + const addButton = (size: "sm" | "md" = "md") => + canManage && data ? ( + + ) : undefined; + + return ( + + +

+ Coderhelm tells your own systems what it did: a run started or finished, a pull request opened, a review + posted, an alert came in. Add an address and pick the events; each request is signed so you can check it + came from Coderhelm. +

+

+ + Read the webhooks guide + + + See every delivery + +

+ + } + actions={addButton()} + /> + +
+ {error && ( + + Nothing has changed. Check your connection and try again. + + )} + {!data && !error && ( +
+ + +
+ )} + {data && ( +
+
+ + Endpoints + + {data.endpoints.length > 0 && addButton("sm")} +
+ {full && ( +

A team can have {data.max} endpoints. Delete one to add another.

+ )} + {data.endpoints.length === 0 ? ( + } title="No endpoints yet." action={addButton()}> + Add the address of a service that should hear about Coderhelm's work, such as a deploy bot or your + own dashboard. + + ) : ( + + {data.endpoints.map((e) => { + const h = health(e, data.disable_after_days); + return ( + {e.url}} + titleText={e.url} + href={endpointHref(e.id)} + meta={[ + e.description || undefined, + eventsSummary(e.events), + e.last_success_at ? `Last delivered ${relativeTime(e.last_success_at) ?? ""}` : "Nothing delivered yet", + ]} + summary={h.tone === "danger" || h.tone === "waiting" ? h.label : undefined} + summaryTone={h.tone} + chips={{h.tone === "success" ? "On" : h.tone === "waiting" ? "Failing" : h.tone === "danger" ? "Turned off" : "Off"}} + /> + ); + })} + + )} +
+ )} + + {data && ( +
+

+ How delivery works +

+
    +
  • + Each event is a POST with a JSON body and the Standard Webhooks headers{" "} + webhook-id, webhook-timestamp and webhook-signature. +
  • +
  • Answer with a 2xx within 10 seconds. Do the work afterwards.
  • +
  • + Timeouts, 5xx, 408 and 429 answers are tried again for about a day. Other 4xx answers are final. +
  • +
  • + An endpoint that fails for {data.disable_after_days} days in a row is turned off, and admins are told. +
  • +
  • Events and deliveries are kept {data.retention_days} days, so you can resend or replay them.
  • +
  • Addresses must be https and on the public internet; private and internal addresses are refused.
  • +
+
+ )} +
+ + {data && ( + { + setCreating(o); + if (!o) setMade(null); + }} + onMade={(m) => { + setMade(m); + load(); + }} + /> + )} +
+ ); +} + +// ── The events picker ─────────────────────────────────────────────── + +function EventsPicker({ + types, + error, + value, + onChange, + fieldError, +}: { + types: WebhookEventType[] | null; + error: string; + value: string[]; + onChange: (v: string[]) => void; + fieldError?: string; +}) { + const all = value.includes("*"); + const errId = useId(); + return ( +
+ Events + + {error &&

{error}

} + {!all && !types && !error && } + {!all && types && ( +
+ {groupEvents(types).map((g) => ( +
+

{g.group}

+
    + {g.types.map((t) => ( +
  • + +
  • + ))} +
+
+ ))} +
+ )} + {fieldError && ( + + )} +
+ ); +} + +// ── Create ────────────────────────────────────────────────────────── + +function CreateEndpointModal({ + open, + onOpenChange, + types, + typesError, + made, + onMade, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + types: WebhookEventType[] | null; + typesError: string; + made: { endpoint: WebhookEndpoint; secret: string } | null; + onMade: (m: { endpoint: WebhookEndpoint; secret: string }) => void; +}) { + const ids = useId(); + const [url, setUrl] = useState(""); + const [description, setDescription] = useState(""); + const [events, setEvents] = useState(["*"]); + const [enabled, setEnabled] = useState(true); + const [errors, setErrors] = useState>({}); + const [saving, setSaving] = useState(false); + + useEffect(() => { + if (!open) { + setUrl(""); + setDescription(""); + setEvents(["*"]); + setEnabled(true); + setErrors({}); + } + }, [open]); + + const submit = async (e: FormEvent) => { + e.preventDefault(); + if (!url.trim().startsWith("https://")) return setErrors({ url: "The address must start with https://" }); + if (events.length === 0) return setErrors({ events: "Pick at least one event, or all events." }); + setSaving(true); + setErrors({}); + try { + onMade(await webhooksApi.create({ url: url.trim(), description: description.trim(), events, enabled })); + } catch (err) { + const field = err instanceof WebhookError && err.field ? err.field : "form"; + setErrors({ [field]: errText(err, "Could not add the endpoint.") }); + } finally { + setSaving(false); + } + }; + + if (made) { + return ( + +
+

+ Events now go to {made.endpoint.url}. +

+ +

+ Your endpoint checks each request's signature with this secret. You won't see it again here, but + admins can reveal it later on the endpoint's page. +

+
+
+ + {made.secret} + + +
+
+ + Open the endpoint + + +
+
+
+ ); + } + + return ( + +
+ + {(p) => ( + setUrl(e.target.value)} + /> + )} + + + {(p) => setDescription(e.target.value)} />} + + + + {errors.form && ( + +

{errors.form}

+
+ )} +
+ + +
+ +
+ ); +} + +// ── One endpoint ──────────────────────────────────────────────────── + +function EndpointPage({ id }: { id: string }) { + const router = useRouter(); + const { toast } = useToast(); + const { confirm } = useConfirm(); + const [ep, setEp] = useState(null); + const [disableAfter, setDisableAfter] = useState(5); + const [error, setError] = useState(""); + const [editing, setEditing] = useState(false); + const [deliveriesKey, setDeliveriesKey] = useState(0); + const { types, error: typesError } = useEventTypes(); + + const load = useCallback(() => { + webhooksApi + .get(id) + .then((e) => { + setEp(e); + setError(""); + }) + .catch((e) => setError(errText(e, "The request failed."))); + webhooksApi + .list() + .then((l) => setDisableAfter(l.disable_after_days)) + .catch(() => {}); + }, [id]); + useEffect(load, [load]); + + const toggle = async () => { + if (!ep) return; + try { + setEp(await webhooksApi.update(ep.id, { enabled: !ep.enabled })); + toast(ep.enabled ? "Turned off. Nothing is sent until you turn it back on." : "Turned on."); + } catch (e) { + toast(errText(e, "Could not save."), "error"); + } + }; + + const remove = async () => { + if (!ep) return; + const ok = await confirm({ + title: "Delete this endpoint?", + message: "Coderhelm stops sending to it at once, including retries already waiting. This can't be undone.", + confirmLabel: "Delete endpoint", + destructive: true, + }); + if (ok !== "primary") return; + try { + await webhooksApi.remove(ep.id); + toast("Endpoint deleted."); + router.push("/settings/webhooks/"); + } catch (e) { + toast(errText(e, "Could not delete the endpoint."), "error"); + } + }; + + if (error) { + return ( + + +
+ + It may have been deleted.{" "} + + Back to Webhooks + + +
+
+ ); + } + if (!ep) { + return ( + +
+ + +
+
+ ); + } + + const h = health(ep, disableAfter); + return ( + + {h.tone === "success" ? "On" : h.tone === "waiting" ? "Failing" : h.tone === "danger" ? "Turned off" : "Off"}} + lead={ + + {ep.url} + + } + actions={ + <> + + + + } + more={[{ label: "Delete endpoint", onSelect: () => void remove(), danger: true }]} + /> + +
+ {h.detail && ( + +

{h.detail}

+
+ )} + +
+

+ Details +

+
+
Events
+
+ {ep.events.includes("*") ? ( + "All events" + ) : ( + + {ep.events.map((t) => ( + {t} + ))} + + )} +
+
Last delivered
+
{ep.last_success_at ? formatDate(ep.last_success_at, { time: true }) : "Not yet"}
+
Last failure
+
{ep.last_failure_at ? formatDate(ep.last_failure_at, { time: true }) : "None"}
+
Endpoint id
+
+ {ep.id} +
+
Added
+
+ + {formatDate(ep.created_at)} by {ep.created_by || "someone"} + +
+
+
+ + + setDeliveriesKey((k) => k + 1)} /> + + setDeliveriesKey((k) => k + 1)} /> +
+ + { + setEp(e); + setEditing(false); + toast("Saved."); + }} + /> +
+ ); +} + +function EditEndpointModal({ + open, + onOpenChange, + ep, + types, + typesError, + onSaved, +}: { + open: boolean; + onOpenChange: (o: boolean) => void; + ep: WebhookEndpoint; + types: WebhookEventType[] | null; + typesError: string; + onSaved: (e: WebhookEndpoint) => void; +}) { + const ids = useId(); + const [url, setUrl] = useState(ep.url); + const [description, setDescription] = useState(ep.description); + const [events, setEvents] = useState(ep.events); + const [errors, setErrors] = useState>({}); + const [saving, setSaving] = useState(false); + useEffect(() => { + if (open) { + setUrl(ep.url); + setDescription(ep.description); + setEvents(ep.events); + setErrors({}); + } + }, [open, ep]); + + const submit = async (e: FormEvent) => { + e.preventDefault(); + if (events.length === 0) return setErrors({ events: "Pick at least one event, or all events." }); + setSaving(true); + setErrors({}); + const body: EndpointInput = { url: url.trim(), description: description.trim(), events }; + try { + onSaved(await webhooksApi.update(ep.id, body)); + } catch (err) { + const field = err instanceof WebhookError && err.field ? err.field : "form"; + setErrors({ [field]: errText(err, "Could not save.") }); + } finally { + setSaving(false); + } + }; + + return ( + +
+ + {(p) => setUrl(e.target.value)} />} + + + {(p) => setDescription(e.target.value)} />} + + + {errors.form && ( + +

{errors.form}

+
+ )} +
+ + +
+ +
+ ); +} + +// ── Secret ────────────────────────────────────────────────────────── + +function SecretSection({ ep, onChanged }: { ep: WebhookEndpoint; onChanged: () => void }) { + const ids = useId(); + const { toast } = useToast(); + const { confirm } = useConfirm(); + const [shown, setShown] = useState(null); + const [rotated, setRotated] = useState<{ secret: string; until: string | null } | null>(null); + const [overlap, setOverlap] = useState("24"); + const [busy, setBusy] = useState(false); + + const reveal = async () => { + setBusy(true); + try { + setShown((await webhooksApi.reveal(ep.id)).secret); + } catch (e) { + toast(errText(e, "Could not reveal the secret."), "error"); + } finally { + setBusy(false); + } + }; + + const rotate = async () => { + const hours = Number(overlap); + const ok = await confirm({ + title: "Make a new signing secret?", + message: + hours > 0 + ? `For the next ${hours} hours every request carries two signatures, one with each secret, so your endpoint keeps working while you update it. Then only the new secret signs.` + : "The old secret stops signing at once. Requests fail to verify until your endpoint has the new secret.", + confirmLabel: "Make a new secret", + destructive: hours === 0, + }); + if (ok !== "primary") return; + setBusy(true); + try { + const r = await webhooksApi.rotate(ep.id, hours); + setShown(null); + setRotated({ secret: r.secret, until: r.previous_secret_expires_at }); + onChanged(); + } catch (e) { + toast(errText(e, "Could not make a new secret."), "error"); + } finally { + setBusy(false); + } + }; + + const previousLive = ep.previous_secret_expires_at && new Date(ep.previous_secret_expires_at).getTime() > Date.now(); + + return ( +
+ Signing secret +
+

+ Your endpoint uses this secret to check each request's webhook-signature header. Revealing it is + written to the team's log. +

+
+ + {shown ?? ep.secret_hint} + +
+ {shown ? ( + <> + + + + ) : ( + + )} +
+
+ {previousLive && !rotated && ( +

+ The previous secret also signs until {formatDate(ep.previous_secret_expires_at!, { time: true })}. +

+ )} + {rotated && ( + +
+ + {rotated.secret} + + +
+

+ {rotated.until + ? `The old secret keeps signing too until ${formatDate(rotated.until, { time: true })}.` + : "The old secret no longer signs."} +

+
+ )} +
+
+ + +
+ +
+
+
+ ); +} + +// ── Test ──────────────────────────────────────────────────────────── + +const STATUS: Record = { + handled: { label: "Delivered", tone: "success" }, + pending: { label: "Retrying", tone: "waiting" }, + failed: { label: "Failed", tone: "danger" }, + received: { label: "Queued", tone: "queued" }, + ignored: { label: "Skipped", tone: "muted" }, +}; + +function codeTone(code?: number | null): Tone { + if (!code) return "danger"; + return code >= 200 && code < 300 ? "success" : "danger"; +} + +function AttemptLine({ a }: { a: WebhookDelivery["attempts"][number] }) { + return ( +
  • + + {formatDate(a.at, { time: true })} + {a.code ? {`HTTP ${a.code}`} : No answer} + {a.duration_ms ? {formatMs(a.duration_ms)} : null} + + {a.error && ( + + {a.error} + + )} +
  • + ); +} + +function TestSection({ ep, onSent }: { ep: WebhookEndpoint; onSent: () => void }) { + const [busy, setBusy] = useState(false); + const [result, setResult] = useState(null); + const [error, setError] = useState(""); + const send = async () => { + setBusy(true); + setError(""); + try { + setResult(await webhooksApi.test(ep.id)); + onSent(); + } catch (e) { + setError(errText(e, "Could not send the test.")); + } finally { + setBusy(false); + } + }; + const last = result?.attempts[result.attempts.length - 1]; + const s = result ? STATUS[result.status] ?? STATUS.failed : null; + return ( +
    +
    + Test + +
    +

    + Sends one webhook.test event now, signed like every other event. It is tried once, even when the + endpoint is off. +

    + {error && ( +
    + +

    {error}

    +
    +
    + )} + {result && s && ( +
    + + {last && ( +
      + +
    + )} + {result.reason_fix && ( +

    + How to fix: + {result.reason_fix} +

    + )} +
    +
    + )} +
    + ); +} + +// ── Deliveries ────────────────────────────────────────────────────── + +function DeliveriesSection({ ep, refreshKey }: { ep: WebhookEndpoint; refreshKey: number }) { + const ids = useId(); + const { toast } = useToast(); + const [status, setStatus] = useState("all"); + const [rows, setRows] = useState(null); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(""); + + const load = useCallback(() => { + webhooksApi + .deliveries(ep.id, status) + .then((d) => { + setRows(d.deliveries); + setError(""); + }) + .catch((e) => setError(errText(e, "The request failed."))); + }, [ep.id, status]); + useEffect(load, [load, refreshKey]); + + const resend = async (d: WebhookDelivery) => { + setBusy(d.id); + try { + const r = await webhooksApi.resend(ep.id, d.id); + setRows((cur) => cur?.map((x) => (x.id === r.id ? r : x)) ?? null); + toast(r.status === "handled" ? "Sent again and delivered." : "Sent again; the endpoint didn't take it.", r.status === "handled" ? undefined : "error"); + } catch (e) { + toast(errText(e, "Could not send it again."), "error"); + } finally { + setBusy(""); + } + }; + + return ( +
    +
    + + Recent deliveries + +
    + + +
    +
    +
    + {error && ( + + Try again in a moment. + + )} + {!rows && !error && } + {rows && rows.length === 0 && ( +

    No deliveries{status === "all" ? " yet" : " like that"}. Send a test event to see one.

    + )} + {rows && rows.length > 0 && ( + + {rows.map((d) => { + const s = STATUS[d.status] ?? STATUS.failed; + return ( + {d.event}} + titleText={d.event} + meta={[ + {d.event_id}, + d.outcome || s.label, + d.attempts.length === 1 ? "1 attempt" : `${d.attempts.length} attempts`, + d.next_retry_at ? `Next try ${formatDate(d.next_retry_at, { time: true })}` : undefined, + ]} + summary={d.status === "failed" ? d.reason_message || undefined : undefined} + summaryTone="danger" + time={d.created_at} + chips={{s.label}} + actions={ + + } + detailsLabel="Attempts" + detailsFor={`attempts of ${d.event_id}`} + details={ +
    + {d.reason_fix && ( +

    + How to fix: + {d.reason_fix} +

    + )} +
      + {d.attempts.map((a, i) => ( + + ))} +
    + {d.headers && Object.keys(d.headers).length > 0 && ( + +
    + {Object.entries(d.headers).map(([k, v]) => ( +
    +
    {k}
    +
    + {v === "[redacted]" ? Hidden : {v}} +
    +
    + ))} +
    +
    + )} + {d.payload_preview && ( + + )} +
    + } + /> + ); + })} +
    + )} +
    +
    + ); +} + +// ── Replay ────────────────────────────────────────────────────────── + +/** A datetime-local value for `minsAgo` minutes ago, in the browser's time. */ +function localInput(minsAgo: number): string { + const d = new Date(Date.now() - minsAgo * 60_000); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; +} + +function ReplaySection({ ep, onQueued }: { ep: WebhookEndpoint; onQueued: () => void }) { + const ids = useId(); + const [since, setSince] = useState(() => localInput(24 * 60)); + const [until, setUntil] = useState(""); + const [onlyFailed, setOnlyFailed] = useState(true); + const [busy, setBusy] = useState(false); + const [result, setResult] = useState(null); + const [error, setError] = useState(""); + + const submit = async (e: FormEvent) => { + e.preventDefault(); + const s = new Date(since); + if (Number.isNaN(s.getTime())) return setError("Pick when to start."); + setBusy(true); + setError(""); + setResult(null); + try { + const u = until ? new Date(until) : null; + setResult( + await webhooksApi.replay(ep.id, { + since: s.toISOString(), + ...(u && !Number.isNaN(u.getTime()) ? { until: u.toISOString() } : {}), + only_failed: onlyFailed, + }), + ); + onQueued(); + } catch (err) { + setError(errText(err, "Could not replay.")); + } finally { + setBusy(false); + } + }; + + return ( +
    + Replay events +
    +

    + Sends the events of a time range to this endpoint again, oldest first, with their original ids so your endpoint + can skip ones it already handled. Events are kept 14 days. +

    +
    + + {(p) => setSince(e.target.value)} />} + + + {(p) => setUntil(e.target.value)} />} + +
    + + {!ep.enabled &&

    Turn the endpoint on before replaying events to it.

    } + {error && ( + +

    {error}

    +
    + )} + {result && ( + +

    + {result.found} kept {result.found === 1 ? "event" : "events"} in the range. + {result.capped ? " More matched than one replay sends (500): replay again from the last one." : ""} +

    +
    + )} +
    + +
    +
    +
    + ); +} diff --git a/dashboard/src/components/deliveries.tsx b/dashboard/src/components/deliveries.tsx index 61bed2b8..344c4d2e 100644 --- a/dashboard/src/components/deliveries.tsx +++ b/dashboard/src/components/deliveries.tsx @@ -11,13 +11,14 @@ import { type DeliveryStatusFilter, } from "@/lib/api"; import { HYBRID_HREF } from "@/lib/hybrid"; +import { endpointHref } from "@/lib/webhooks"; import { Callout } from "./callout"; import { CodeBlock } from "./code-block"; import { CopyButton } from "./copy-button"; import { Drawer } from "./drawer"; import { EmptyState } from "./empty-state"; import { FilterSelect } from "./data-source-activity"; -import { AtlassianIcon, BellIcon, ChatIcon, CloudIcon, GitHubIcon, MailIcon, PluginIcon, RepeatIcon, RetryIcon } from "./icons"; +import { AtlassianIcon, BellIcon, ChatIcon, CloudIcon, GitHubIcon, MailIcon, PluginIcon, RepeatIcon, RetryIcon, SendIcon } from "./icons"; import { Chip, ListEmpty, ListError, ListSkeleton, ListToolbar, StatusDot, TONES, formatDate, formatMs, statusWords, timeAgo, type Tone } from "./list"; import { SectionHeading } from "./page"; import { Code } from "./settings/code"; @@ -39,6 +40,7 @@ const SOURCE_NAME: Record = { teams: "Teams", email: "Email", hybrid: "Hybrid", + webhook: "Webhook", }; export function sourceName(source: string): string { @@ -56,6 +58,7 @@ function SourceIcon({ source }: { source: string }) { relay: , broker: , hybrid: , + webhook: , }; return (