Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add the webhooks Settings panel, catch-up endpoint, cron, docs and tests
Claudeba4965c519a5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bfdca00..935a6db 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,9 +22,18 @@ release says when it does.delete; list and read envelopes and their audit trail; download the signedPDF and the certificate; start an envelope from a template; upload PDFsover 4 MB straight to Blob. `GET /api/v1/openapi.json` describes it all.--This changes the database: the new `api_keys` and `api_idempotency` tables-and three new columns are added by the migrations that run on deploy.+- Webhooks: an administrator can add endpoints under Settings,+ Organization, Webhooks, to be told when an envelope is sent, viewed,+ signed, completed, declined, voided or expires. Deliveries are signed the+ Standard Webhooks way, written in the same transaction as the change they+ report, and retried for about two and a half days. Settings shows a+ delivery log with "Send again", a test button and secret rotation;+ `GET /api/v1/webhook-deliveries` lets an app catch up. A new daily cron+ job, `/api/internal/webhooks`, sends retries that are due.++This changes the database: the new `api_keys`, `api_idempotency`,+`webhook_endpoints` and `webhook_deliveries` tables and three new columns+are added by the migrations that run on deploy.## [0.3.0] - 2026-11-16diff --git a/docs/api.md b/docs/api.mdindex e60496d..c22265b 100644--- a/docs/api.md+++ b/docs/api.md@@ -230,28 +230,152 @@ Every endpoint that returns an envelope returns the same object:completion once it is completed, declined or voided.To know when something happens without asking again and again, use-webhooks (coming in the next release).+[webhooks](#webhooks).## Endpoints-| Method and path | Access | What it does |-| ---------------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `GET /api/v1/me` | read | Which key this is and whom it acts as. |-| `POST /api/v1/envelopes` | write | Creates an envelope, and sends it if asked. |-| `GET /api/v1/envelopes` | read | Lists envelopes, newest first: `?status=`, `?limit=` (up to 100, 25 by default), and `?cursor=` with the `nextCursor` of the page before. |-| `GET /api/v1/envelopes/{id}` | read | One envelope. |-| `POST /api/v1/envelopes/{id}/send` | write | Sends a draft. Body: the `send` options above. |-| `POST /api/v1/envelopes/{id}/void` | write | Voids a sent envelope. Body: `{"reason": "…"}`, required on Part 11 installs. |-| `POST /api/v1/envelopes/{id}/remind` | write | Emails the signer whose turn it is a reminder, at most once a day as in the web app. |-| `DELETE /api/v1/envelopes/{id}` | write | Deletes a draft. |-| `GET /api/v1/envelopes/{id}/events` | read | The audit trail, oldest first. |-| `GET /api/v1/envelopes/{id}/files/signed` | read | The signed PDF. |-| `GET /api/v1/envelopes/{id}/files/certificate` | read | The certificate of completion. |-| `POST /api/v1/uploads` | write | An upload URL for a PDF over 4 MB. |-| `GET /api/v1/templates` | read | Saved templates, with their roles in signing order. |-| `POST /api/v1/templates/{id}/envelopes` | write | An envelope from a template: `title`, `signers` (`name`, `email`, one per role in order), and optionally `metadata` and `send`. Takes an `Idempotency-Key`. |-| `GET /api/v1/openapi.json` | none | The OpenAPI 3.1 description of all of this, for code generators and API tools. |+| Method and path | Access | What it does |+| ---------------------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `GET /api/v1/me` | read | Which key this is and whom it acts as. |+| `POST /api/v1/envelopes` | write | Creates an envelope, and sends it if asked. |+| `GET /api/v1/envelopes` | read | Lists envelopes, newest first: `?status=`, `?limit=` (up to 100, 25 by default), and `?cursor=` with the `nextCursor` of the page before. |+| `GET /api/v1/envelopes/{id}` | read | One envelope. |+| `POST /api/v1/envelopes/{id}/send` | write | Sends a draft. Body: the `send` options above. |+| `POST /api/v1/envelopes/{id}/void` | write | Voids a sent envelope. Body: `{"reason": "…"}`, required on Part 11 installs. |+| `POST /api/v1/envelopes/{id}/remind` | write | Emails the signer whose turn it is a reminder, at most once a day as in the web app. |+| `DELETE /api/v1/envelopes/{id}` | write | Deletes a draft. |+| `GET /api/v1/envelopes/{id}/events` | read | The audit trail, oldest first. |+| `GET /api/v1/envelopes/{id}/files/signed` | read | The signed PDF. |+| `GET /api/v1/envelopes/{id}/files/certificate` | read | The certificate of completion. |+| `POST /api/v1/uploads` | write | An upload URL for a PDF over 4 MB. |+| `GET /api/v1/templates` | read | Saved templates, with their roles in signing order. |+| `POST /api/v1/templates/{id}/envelopes` | write | An envelope from a template: `title`, `signers` (`name`, `email`, one per role in order), and optionally `metadata` and `send`. Takes an `Idempotency-Key`. |+| `GET /api/v1/webhook-deliveries` | read | Webhook deliveries, newest first, with the payload each carried: `?since=` (ISO time), `?type=`, `?status=`, `?limit=`, `?cursor=`. See [Webhooks](#webhooks). |+| `GET /api/v1/openapi.json` | none | The OpenAPI 3.1 description of all of this, for code generators and API tools. |Envelopes made through the API are ordinary envelopes: they show in the key'sadministrator's documents, can be followed and voided there, and their audittrail records the key that sent them.++## Webhooks++A webhook tells your app the moment an envelope changes, so it does not+have to ask. An administrator adds an endpoint under Settings,+Organization, Webhooks: an `https://` URL, the events it wants, and an+optional description. The signing secret (`whsec_…`) is shown once, then.+"Send test" sends a `webhook.test` event at once and says how your app+answered.++Endpoints belong to the whole install: each one gets events for every+envelope, whoever sent it. `data.owner` says whose envelope it is, so an app+can ignore the ones that are not its own. An install can have 10 endpoints.++### Events++| Event | When |+| -------------------- | -------------------------------------------------------------------------------------------- |+| `envelope.sent` | The envelope was sent. `data.signer` is the first signer, now invited. |+| `signer.viewed` | A signer opened it for the first time. |+| `signer.signed` | A signer signed. `data.signer` is who. |+| `envelope.completed` | Everyone signed. The signed PDF and the certificate are ready to download when this arrives. |+| `envelope.declined` | A signer declined. `data.reason` is the reason they gave, if any. |+| `envelope.voided` | The sender voided it. `data.reason` is why, if given. |+| `envelope.expired` | Its deadline passed before everyone signed. |++### What arrives++Each event is a `POST` with a JSON body:++```json+{+ "type": "signer.signed",+ "timestamp": "2026-11-18T09:14:03.000Z",+ "data": {+ "envelope": { "object": "envelope", "id": "…", "status": "sent", "…": "…" },+ "owner": { "id": "…", "email": "[email protected]", "name": "Ops" },+ "signer": { "id": "…", "ref": "client", "status": "signed", "…": "…" }+ }+}+```++`data.envelope` is the same [envelope](#the-envelope) the API returns, as it+was when the event was first sent.++### Checking the signature++Deliveries follow [Standard Webhooks](https://www.standardwebhooks.com), so+you can check them with one of its libraries instead of your own code. Each+carries three headers:++- `webhook-id`: the delivery's id (`msg_…`). The same on every try, so use+ it to ignore a delivery you already handled.+- `webhook-timestamp`: when this try was sent, in seconds since 1970.+ Refuse one more than five minutes old.+- `webhook-signature`: `v1,` and the base64 HMAC-SHA256 of+ `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the secret's bytes+ (the base64 after `whsec_`). Check it against the raw body, before you+ parse it.++Without a library, in Node.js:++```js+import { createHmac, timingSafeEqual } from "node:crypto";++function isFromSignuDoc(headers, rawBody, secret) {+ const id = headers["webhook-id"];+ const timestamp = headers["webhook-timestamp"];++ if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) {+ return false;+ }++ const key = Buffer.from(secret.slice("whsec_".length), "base64");+ const expected = Buffer.from(+ `v1,${createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest("base64")}`,+ );++ // During a secret rotation there are two signatures, space separated.+ return headers["webhook-signature"].split(" ").some((signature) => {+ const given = Buffer.from(signature);++ return given.length === expected.length && timingSafeEqual(given, expected);+ });+}+```++"New secret" in Settings makes a new secret and shows it once. For 24 hours+after that, deliveries are signed with both the old and the new one, so you+can switch without missing any.++### Answers and retries++Answer with any `2xx` within 10 seconds, and do the slow work after. Any+other answer, a redirect, or no answer counts as a failure, and the delivery+is tried again 1 minute, 5 minutes, 30 minutes, 2 hours, 8 hours, 24 hours+and 24 hours later, about two and a half days in all. After the eighth try+it is marked failed. The delivery log in Settings shows the last 100+deliveries per endpoint, with your app's answer, and "Send again" puts a+delivered or failed one back in line.++Retries go out when something wakes the install: the next change to any+envelope, the next API call, or the daily cron job. On Vercel's Hobby plan+crons run once a day, so on a quiet install a retry can wait until the next+day. On Pro you can run it more often by changing the schedule of+`/api/internal/webhooks` in `vercel.json`, for example to `*/5 * * * *`.++If your app was down, `GET /api/v1/webhook-deliveries?since=…` lists what+it missed, with the same payloads. Deliveries are kept 30 days once+delivered and 90 days otherwise.++### Safety++The URL must be `https://` and must not point at a private, loopback or+link-local address. The address is checked each time a delivery is sent,+and the request goes to the address that was checked. Redirects are not+followed. For a receiver on your own machine while developing, set+`WEBHOOK_ALLOW_PRIVATE_URLS=1`; it allows `http://` and local addresses,+and is ignored on Vercel.++Signing secrets are stored encrypted with a key derived from+`BETTER_AUTH_SECRET`. If that secret changes, deliveries fail with a note+to make a new secret in Settings.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex b37b1da..157d42e 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -180,6 +180,10 @@ These cover the people with an account (senders and administrators). Signers whoAnother app can create and send envelopes through the [SignuDoc API](api.md). An administrator makes a key for it under Settings, Organization, API keys. The key is shown once and only its hash is stored. It acts as the administrator who made it, skips two-step sign-in (it is for servers, not people), and stops working when it is revoked, expires, or its administrator stops being one. Making and revoking keys is in the site audit trail.+### Webhooks++An administrator can add webhook endpoints under Settings, Organization, Webhooks, so another app hears when an envelope is sent, viewed, signed, completed, declined, voided or expires. Deliveries are signed, retried for about two and a half days, and listed in a delivery log. Adding, changing and removing endpoints is in the site audit trail. Retries that are due are sent by the next request that changes an envelope, the next API call, or a daily cron job on `/api/internal/webhooks`, which takes the same `CRON_SECRET` as the daily cleanup. See [Webhooks](api.md#webhooks).+### Send the audit trail to your SIEMEvery row added to the site audit trail or to a document's audit trail is also written to the function logs, once it is saved, as one line of JSON. So are refused requests and failures worth a look. A Vercel log drain (team Settings, Drains, or an observability integration from the Vercel Marketplace such as Datadog, Axiom or Better Stack) then delivers them to your SIEM as fields it can search and alert on. Log drains are a paid Vercel feature; see Vercel's pricing page for which plans have them.diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.tsindex 9dfd886..107a546 100644--- a/e2e/signing-flow.spec.ts+++ b/e2e/signing-flow.spec.ts@@ -5,6 +5,10 @@ import { e2eDatabaseUrl, e2eSetupToken } from "../playwright.config";import { extractLink, extractLinks, waitForEmail } from "./support/outbox";import { totpCode } from "./support/totp";import { writeSamplePdf } from "./support/sample-pdf";+import {+ hasValidSignature,+ startWebhookReceiver,+} from "./support/webhook-receiver";const PASSWORD = "correct horse battery staple 42";// The ampersand is on purpose: the name goes into HTML emails and page titles.@@ -1216,7 +1220,7 @@ test("a signer signs with a qualified signature in their own name, through the s});});-test("an administrator makes an API key, an app sends and downloads an envelope with it, and revoking it stops it", async ({+test("an administrator makes an API key and a webhook, an app sends and downloads an envelope and hears each step, and revoking the key stops it", async ({baseURL,browser,page,@@ -1285,6 +1289,40 @@ test("an administrator makes an API key, an app sends and downloads an envelope});});+ const receiver = await startWebhookReceiver();+ let webhookSecret = "";++ await test.step("a webhook endpoint is added in Settings, and its test event arrives signed", async () => {+ await page+ .getByPlaceholder("https://app.example.com/webhooks/signudoc")+ .fill(receiver.url);+ await page+ .getByPlaceholder("What this endpoint is for")+ .fill("Billing app");+ await page.getByRole("button", { name: "Add endpoint" }).click();++ webhookSecret =+ (await page+ .getByTestId("new-webhook-secret")+ .locator("code")+ .textContent()) ?? "";+ expect(webhookSecret).toMatch(/^whsec_/);+ await page+ .getByTestId("new-webhook-secret")+ .getByRole("button", { name: "Done" })+ .click();++ const endpoints = page.getByRole("list", { name: "Webhook endpoints" });++ await expect(endpoints.getByText(receiver.url)).toBeVisible();+ await endpoints.getByRole("button", { name: "Send test" }).click();+ await expect(page.getByText("The test event was delivered")).toBeVisible();+ expect(receiver.received.map((webhook) => webhook.json.type)).toEqual([+ "webhook.test",+ ]);+ expect(hasValidSignature(receiver.received[0]!, webhookSecret)).toBe(true);+ });+await test.step("an app creates and sends an envelope, a signer signs, and the app downloads it", async () => {const auth = { authorization: `Bearer ${key}` };const signerEmail = `api-signer+${String(Date.now())}@example.com`;@@ -1432,6 +1470,50 @@ test("an administrator makes an API key, an app sends and downloads an envelopeexpect(list.data.map((item) => item.id)).toContain(envelope.id);+ // Each step reached the app, signed, carrying the envelope.+ await expect+ .poll(() =>+ receiver.received+ .filter((webhook) => webhook.json.type !== "webhook.test")+ .map((webhook) => webhook.json.type)+ .sort(),+ )+ .toEqual([+ "envelope.completed",+ "envelope.sent",+ "signer.signed",+ "signer.viewed",+ ]);++ for (const webhook of receiver.received) {+ expect(hasValidSignature(webhook, webhookSecret)).toBe(true);+ }++ const completedHook = receiver.received.find(+ (webhook) => webhook.json.type === "envelope.completed",+ );++ expect(completedHook?.json.data).toMatchObject({+ envelope: {+ files: { signed: `/api/v1/envelopes/${envelope.id}/files/signed` },+ id: envelope.id,+ metadata: { invoice: "INV-1042" },+ status: "completed",+ },+ owner: { email: adminEmail },+ });++ const deliveries = (await (+ await api.get("/api/v1/webhook-deliveries?type=envelope.completed", {+ headers: auth,+ })+ ).json()) as { data: Array<{ envelopeId: string; status: string }> };++ expect(deliveries.data[0]).toMatchObject({+ envelopeId: envelope.id,+ status: "delivered",+ });+const openapi = await api.get("/api/v1/openapi.json");expect(openapi.status()).toBe(200);@@ -1455,6 +1537,7 @@ test("an administrator makes an API key, an app sends and downloads an envelope});await api.dispose();+ await receiver.close();});test("two-step sign-in: an administrator sets it up and requires it of everyone", async ({diff --git a/e2e/support/webhook-receiver.ts b/e2e/support/webhook-receiver.tsnew file mode 100644index 0000000..2f59aaa--- /dev/null+++ b/e2e/support/webhook-receiver.ts@@ -0,0 +1,57 @@+import { createHmac } from "node:crypto";+import { createServer, type IncomingHttpHeaders } from "node:http";+import type { AddressInfo } from "node:net";++// A stand-in for an app that receives SignuDoc's webhooks: it keeps every+// request, and checks signatures the way the Standard Webhooks spec says a+// receiver should.++export type ReceivedWebhook = {+ body: string;+ headers: IncomingHttpHeaders;+ json: { data: Record<string, unknown>; type: string };+};++export async function startWebhookReceiver() {+ const received: ReceivedWebhook[] = [];+ const server = createServer((request, response) => {+ const chunks: Buffer[] = [];++ request.on("data", (chunk: Buffer) => chunks.push(chunk));+ request.on("end", () => {+ const body = Buffer.concat(chunks).toString("utf8");++ received.push({+ body,+ headers: request.headers,+ json: JSON.parse(body) as ReceivedWebhook["json"],+ });+ response.writeHead(204);+ response.end();+ });+ });++ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));++ const { port } = server.address() as AddressInfo;++ return {+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),+ received,+ url: `http://127.0.0.1:${String(port)}/signudoc`,+ };+}++/** Whether a received webhook carries a valid signature for `secret`. */+export function hasValidSignature(webhook: ReceivedWebhook, secret: string) {+ const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");+ const id = String(webhook.headers["webhook-id"]);+ const timestamp = String(webhook.headers["webhook-timestamp"]);+ const expected = `v1,${createHmac("sha256", key)+ .update(`${id}.${timestamp}.${webhook.body}`)+ .digest("base64")}`;++ return String(webhook.headers["webhook-signature"])+ .split(" ")+ .includes(expected);+}diff --git a/playwright.config.ts b/playwright.config.tsindex c1245f8..73d925c 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -74,6 +74,8 @@ export default defineConfig({// a real Vercel Blob store, direct browser upload included.STORAGE_DRIVER: process.env.E2E_STORAGE_DRIVER ?? "local",STORAGE_LOCAL_DIR: path.join(e2eDataDir, "storage"),+ // The webhook receiver in the test listens on 127.0.0.1.+ WEBHOOK_ALLOW_PRIVATE_URLS: "1",},reuseExistingServer: false,timeout: 300_000,diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsxindex 63f61d2..f7a5c21 100644--- a/src/components/settings/organization-settings.tsx+++ b/src/components/settings/organization-settings.tsx@@ -10,6 +10,7 @@ import { Part11Panel } from "@/components/settings/part11-panel";import { PeoplePanel } from "@/components/settings/people-panel";import { SecurityPanel } from "@/components/settings/security-panel";import { SignerDataPanel } from "@/components/settings/signer-data-panel";+import { WebhooksPanel } from "@/components/settings/webhooks-panel";import type { EmailDnsRecord, EmailStatus } from "@/lib/email-status";import type {OrganizationSettingsField,@@ -416,6 +417,8 @@ export function OrganizationSettings({{!values.hosted ? <ApiKeysPanel /> : null}+ {!values.hosted ? <WebhooksPanel /> : null}+<SignerDataPanel /></div></section>diff --git a/src/components/settings/webhooks-panel.tsx b/src/components/settings/webhooks-panel.tsxnew file mode 100644index 0000000..e4c936b--- /dev/null+++ b/src/components/settings/webhooks-panel.tsx@@ -0,0 +1,632 @@+"use client";++import { useEffect, useState } from "react";++import type { WebhookEndpoint } from "@/lib/webhooks/endpoints";+import {+ webhookEventTypes,+ type WebhookEventType,+} from "@/lib/webhooks/events";+import type { WebhookDeliverySummary } from "@/lib/webhooks/log";++// Webhook endpoints: where the install tells other apps that an envelope+// changed. Administrators only. A signing secret is shown once, right after+// it is made, and never again.++const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";+const WEBHOOK_DOCS_URL =+ "https://github.com/NYLLON-SOFTWARE/SignuDoc/blob/main/docs/api.md#webhooks";++const EVENT_LABELS: Record<WebhookEventType, string> = {+ "envelope.completed": "Completed",+ "envelope.declined": "Declined",+ "envelope.expired": "Expired",+ "envelope.sent": "Sent",+ "envelope.voided": "Voided",+ "signer.signed": "Signer signed",+ "signer.viewed": "Signer opened it",+};++const timeFormatter = new Intl.DateTimeFormat("en-US", {+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ month: "short",+});++function formatTime(seconds: number | null) {+ return seconds === null+ ? null+ : timeFormatter.format(new Date(seconds * 1000));+}++type ApiPayload = {+ delivery?: {+ lastError: string | null;+ lastStatusCode: number | null;+ status: string;+ };+ deliveries?: WebhookDeliverySummary[];+ endpoint?: WebhookEndpoint;+ endpoints?: WebhookEndpoint[];+ error?: string;+ secret?: string;+} | null;++async function call(+ url: string,+ init?: RequestInit,+): Promise<{ ok: boolean; payload: ApiPayload }> {+ const response = await fetch(url, {+ cache: "no-store",+ ...init,+ headers: init?.body ? { "content-type": "application/json" } : undefined,+ });++ return {+ ok: response.ok,+ payload: (await response.json().catch(() => null)) as ApiPayload,+ };+}++function deliveryTone(status: WebhookDeliverySummary["status"]) {+ return status === "delivered"+ ? "pill-success"+ : status === "failed"+ ? "pill-danger"+ : "pill-warning";+}++function DeliveryLog({ endpointId }: { endpointId: string }) {+ const [deliveries, setDeliveries] = useState<WebhookDeliverySummary[] | null>(+ null,+ );+ const [error, setError] = useState<string | null>(null);+ const [revision, setRevision] = useState(0);+ const [pendingId, setPendingId] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;++ void (async () => {+ try {+ const { ok, payload } = await call(+ `/api/admin/webhooks/${encodeURIComponent(endpointId)}/deliveries`,+ );++ if (!cancelled) {+ if (ok && payload?.deliveries) {+ setDeliveries(payload.deliveries);+ } else {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ }+ }+ } catch {+ if (!cancelled) {+ setError(GENERIC_ERROR_MESSAGE);+ }+ }+ })();++ return () => {+ cancelled = true;+ };+ }, [endpointId, revision]);++ async function resend(id: string) {+ setPendingId(id);+ setError(null);++ try {+ const { ok, payload } = await call(+ `/api/admin/webhooks/deliveries/${encodeURIComponent(id)}/resend`,+ { method: "POST" },+ );++ if (!ok) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ // Give the send a moment before reading the log again.+ await new Promise((resolve) => setTimeout(resolve, 1500));+ setRevision((value) => value + 1);+ } catch {+ setError(GENERIC_ERROR_MESSAGE);+ } finally {+ setPendingId(null);+ }+ }++ if (error) {+ return (+ <p className="notice notice-danger" role="alert">+ {error}+ </p>+ );+ }++ if (deliveries === null) {+ return <p className="text-sm text-(--secondary)">Loading...</p>;+ }++ if (deliveries.length === 0) {+ return <p className="text-sm text-(--secondary)">Nothing sent yet.</p>;+ }++ return (+ <div className="grid gap-2">+ <div className="flex justify-end">+ <button+ className="btn-quiet"+ onClick={() => setRevision((value) => value + 1)}+ type="button"+ >+ Refresh+ </button>+ </div>+ <ul aria-label="Recent deliveries" className="grid gap-2">+ {deliveries.map((delivery) => (+ <li+ className="grid gap-1 rounded-lg border border-(--border) px-3 py-2 text-sm"+ key={delivery.id}+ >+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-mono text-(--fg)">+ {delivery.eventType}+ </span>+ <span className={`pill ${deliveryTone(delivery.status)}`}>+ {delivery.status === "pending" && delivery.attempts > 0+ ? "Retrying"+ : delivery.status === "pending"+ ? "Waiting"+ : delivery.status === "delivered"+ ? "Delivered"+ : "Failed"}+ </span>+ <span className="text-(--secondary)">+ {formatTime(delivery.createdAt)}+ {delivery.attempts > 1+ ? `, ${String(delivery.attempts)} tries`+ : ""}+ {delivery.lastStatusCode !== null+ ? `, answered ${String(delivery.lastStatusCode)}`+ : ""}+ </span>+ </div>+ {delivery.status !== "delivered" && delivery.lastError ? (+ <p className="break-all text-(--secondary)">+ {delivery.lastError}+ {delivery.status === "pending" && delivery.nextAttemptAt+ ? ` Next try around ${formatTime(delivery.nextAttemptAt) ?? ""}.`+ : ""}+ </p>+ ) : null}+ {delivery.status !== "pending" &&+ delivery.eventType !== "webhook.test" ? (+ <div>+ <button+ className="btn-quiet"+ disabled={pendingId !== null}+ onClick={() => void resend(delivery.id)}+ type="button"+ >+ {pendingId === delivery.id ? "Sending..." : "Send again"}+ </button>+ </div>+ ) : null}+ </li>+ ))}+ </ul>+ </div>+ );+}++export function WebhooksPanel() {+ const [endpoints, setEndpoints] = useState<WebhookEndpoint[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const [url, setUrl] = useState("");+ const [description, setDescription] = useState("");+ const [events, setEvents] = useState<WebhookEventType[]>([+ ...webhookEventTypes,+ ]);+ const [isCreating, setIsCreating] = useState(false);+ const [newSecret, setNewSecret] = useState<{+ secret: string;+ url: string;+ } | null>(null);+ const [copied, setCopied] = useState(false);+ const [pendingId, setPendingId] = useState<string | null>(null);+ const [removingId, setRemovingId] = useState<string | null>(null);+ const [openLogId, setOpenLogId] = useState<string | null>(null);+ const [revision, setRevision] = useState(0);++ useEffect(() => {+ let cancelled = false;++ void (async () => {+ try {+ const { ok, payload } = await call("/api/admin/webhooks");++ if (cancelled) {+ return;+ }++ if (!ok || !payload?.endpoints) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ setEndpoints(payload.endpoints);+ } catch {+ if (!cancelled) {+ setError(GENERIC_ERROR_MESSAGE);+ }+ }+ })();++ return () => {+ cancelled = true;+ };+ }, [revision]);++ function showSecret(secret: string, endpointUrl: string) {+ setNewSecret({ secret, url: endpointUrl });+ setCopied(false);+ }++ async function createEndpoint() {+ setIsCreating(true);+ setError(null);+ setNotice(null);+ setNewSecret(null);++ try {+ const { ok, payload } = await call("/api/admin/webhooks", {+ body: JSON.stringify({ description, events, url }),+ method: "POST",+ });++ if (!ok || !payload?.secret || !payload.endpoint) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ showSecret(payload.secret, payload.endpoint.url);+ setUrl("");+ setDescription("");+ setRevision((value) => value + 1);+ } catch {+ setError(GENERIC_ERROR_MESSAGE);+ } finally {+ setIsCreating(false);+ }+ }++ async function act(+ endpoint: WebhookEndpoint,+ action: "delete" | "disable" | "enable" | "rotate" | "test",+ ) {+ setPendingId(endpoint.id);+ setError(null);+ setNotice(null);++ const base = `/api/admin/webhooks/${encodeURIComponent(endpoint.id)}`;++ try {+ const { ok, payload } =+ action === "delete"+ ? await call(base, { method: "DELETE" })+ : action === "rotate"+ ? await call(`${base}/rotate`, { method: "POST" })+ : action === "test"+ ? await call(`${base}/test`, { method: "POST" })+ : await call(base, {+ body: JSON.stringify({ enabled: action === "enable" }),+ method: "PATCH",+ });++ if (!ok) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ if (action === "rotate" && payload?.secret) {+ showSecret(payload.secret, endpoint.url);+ }++ if (action === "test" && payload?.delivery) {+ const { delivery } = payload;++ setNotice(+ delivery.status === "delivered"+ ? `The test event was delivered (answered ${String(delivery.lastStatusCode)}).`+ : `The test event was not delivered: ${delivery.lastError ?? "no answer"}.`,+ );+ }++ setRemovingId(null);+ setRevision((value) => value + 1);+ } catch {+ setError(GENERIC_ERROR_MESSAGE);+ } finally {+ setPendingId(null);+ }+ }++ async function copySecret() {+ if (!newSecret) {+ return;+ }++ try {+ await navigator.clipboard.writeText(newSecret.secret);+ setCopied(true);+ } catch {+ setCopied(false);+ }+ }++ function toggleEvent(type: WebhookEventType) {+ setEvents((current) =>+ current.includes(type)+ ? current.filter((value) => value !== type)+ : webhookEventTypes.filter(+ (value) => value === type || current.includes(value),+ ),+ );+ }++ return (+ <div className="space-y-5 border-t border-(--border) pt-8">+ <div className="space-y-2">+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">+ Webhooks+ </h3>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ Tell another app when an envelope is sent, opened, signed, completed,+ declined, voided or expires. Each event is POSTed to the URL as JSON+ and signed with the endpoint's secret, the{" "}+ <a+ className="font-semibold text-(--accent) underline-offset-4 hover:underline"+ href={WEBHOOK_DOCS_URL}+ rel="noreferrer"+ target="_blank"+ >+ Standard Webhooks+ </a>{" "}+ way. Endpoints get events for every envelope on this install. If the+ app does not answer, the event is tried again for about two days.+ </p>+ </div>++ <div className="grid max-w-xl gap-4">+ <label className="grid gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ URL+ </span>+ <input+ autoComplete="off"+ className="field-input"+ disabled={isCreating}+ inputMode="url"+ maxLength={2048}+ name="webhook-url"+ onChange={(event) => setUrl(event.target.value)}+ placeholder="https://app.example.com/webhooks/signudoc"+ value={url}+ />+ </label>+ <label className="grid gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Description (optional)+ </span>+ <input+ autoComplete="off"+ className="field-input"+ disabled={isCreating}+ maxLength={200}+ name="webhook-description"+ onChange={(event) => setDescription(event.target.value)}+ placeholder="What this endpoint is for"+ value={description}+ />+ </label>+ <fieldset className="grid gap-2">+ <legend className="mb-1.5 text-[0.8125rem] font-semibold text-(--secondary)">+ Events+ </legend>+ <div className="grid gap-2 sm:grid-cols-2">+ {webhookEventTypes.map((type) => (+ <label+ className="flex items-center gap-2 text-sm text-(--fg)"+ key={type}+ >+ <input+ checked={events.includes(type)}+ disabled={isCreating}+ name={`webhook-event-${type}`}+ onChange={() => toggleEvent(type)}+ type="checkbox"+ />+ {EVENT_LABELS[type]}+ </label>+ ))}+ </div>+ </fieldset>+ <div>+ <button+ className="btn-quiet min-h-12 px-5 text-sm"+ disabled={+ isCreating || url.trim().length === 0 || events.length === 0+ }+ onClick={() => void createEndpoint()}+ type="button"+ >+ {isCreating ? "Adding..." : "Add endpoint"}+ </button>+ </div>+ </div>++ {newSecret ? (+ <div+ className="well grid max-w-2xl gap-3 p-4"+ data-testid="new-webhook-secret"+ role="status"+ >+ <p className="text-sm font-semibold text-(--fg)">+ Copy the signing secret for {newSecret.url} now. It is not shown+ again.+ </p>+ <code className="block overflow-x-auto rounded-lg border border-(--border) bg-(--paper) px-3 py-2 font-mono text-sm break-all text-(--fg)">+ {newSecret.secret}+ </code>+ <div className="flex flex-wrap gap-2">+ <button+ className="btn-quiet"+ onClick={() => void copySecret()}+ type="button"+ >+ {copied ? "Copied" : "Copy"}+ </button>+ <button+ className="btn-quiet"+ onClick={() => setNewSecret(null)}+ type="button"+ >+ Done+ </button>+ </div>+ </div>+ ) : null}++ {notice ? (+ <p className="notice notice-accent max-w-2xl" role="status">+ {notice}+ </p>+ ) : null}++ {error ? (+ <p className="notice notice-danger max-w-2xl" role="alert">+ {error}+ </p>+ ) : null}++ {endpoints === null ? null : endpoints.length === 0 ? (+ <p className="text-sm text-(--secondary)">No endpoints yet.</p>+ ) : (+ <ul aria-label="Webhook endpoints" className="grid max-w-2xl gap-3">+ {endpoints.map((endpoint) => (+ <li className="well grid gap-2 p-4" key={endpoint.id}>+ <div className="flex flex-wrap items-center gap-2">+ <p className="font-mono text-sm font-bold break-all text-(--fg)">+ {endpoint.url}+ </p>+ <span+ className={`pill ${endpoint.enabled ? "pill-success" : "pill-neutral"}`}+ >+ {endpoint.enabled ? "On" : "Off"}+ </span>+ </div>+ {endpoint.description ? (+ <p className="text-sm text-(--secondary)">+ {endpoint.description}+ </p>+ ) : null}+ <p className="text-sm text-(--secondary)">+ {endpoint.events.length === webhookEventTypes.length+ ? "All events."+ : `${endpoint.events.map((type) => EVENT_LABELS[type]).join(", ")}.`}+ {endpoint.previousSecretExpiresAt+ ? ` The old secret also signs until ${formatTime(endpoint.previousSecretExpiresAt) ?? ""}.`+ : ""}+ </p>+ <div className="flex flex-wrap items-center gap-2">+ {removingId === endpoint.id ? (+ <>+ <span className="text-sm text-(--secondary)">+ Remove this endpoint and its delivery log?+ </span>+ <button+ className="btn-quiet btn-quiet-danger"+ disabled={pendingId !== null}+ onClick={() => void act(endpoint, "delete")}+ type="button"+ >+ {pendingId === endpoint.id ? "Removing..." : "Remove"}+ </button>+ <button+ className="btn-quiet"+ disabled={pendingId !== null}+ onClick={() => setRemovingId(null)}+ type="button"+ >+ Cancel+ </button>+ </>+ ) : (+ <>+ <button+ className="btn-quiet"+ disabled={pendingId !== null || !endpoint.enabled}+ onClick={() => void act(endpoint, "test")}+ type="button"+ >+ {pendingId === endpoint.id ? "Working..." : "Send test"}+ </button>+ <button+ className="btn-quiet"+ disabled={pendingId !== null}+ onClick={() =>+ void act(+ endpoint,+ endpoint.enabled ? "disable" : "enable",+ )+ }+ type="button"+ >+ {endpoint.enabled ? "Turn off" : "Turn on"}+ </button>+ <button+ className="btn-quiet"+ disabled={pendingId !== null}+ onClick={() => void act(endpoint, "rotate")}+ type="button"+ >+ New secret+ </button>+ <button+ aria-expanded={openLogId === endpoint.id}+ className="btn-quiet"+ onClick={() =>+ setOpenLogId((current) =>+ current === endpoint.id ? null : endpoint.id,+ )+ }+ type="button"+ >+ {openLogId === endpoint.id ? "Hide log" : "Delivery log"}+ </button>+ <button+ aria-label={`Remove ${endpoint.url}`}+ className="btn-quiet btn-quiet-danger"+ disabled={pendingId !== null}+ onClick={() => setRemovingId(endpoint.id)}+ type="button"+ >+ Remove+ </button>+ </>+ )}+ </div>+ {openLogId === endpoint.id ? (+ <DeliveryLog endpointId={endpoint.id} key={revision} />+ ) : null}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}