Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add webhooks: outbox, signed delivery with retries, admin routes
Claude98fd4aeb80e9
diff --git a/db/migrations/20261118110000_webhooks.sql b/db/migrations/20261118110000_webhooks.sqlnew file mode 100644index 0000000..76cb22b--- /dev/null+++ b/db/migrations/20261118110000_webhooks.sql@@ -0,0 +1,75 @@+-- Webhooks: the install tells other apps when an envelope changes.+--+-- An administrator adds an endpoint (an https URL and the events it wants)+-- in Settings. Every envelope event that matches is written to+-- webhook_deliveries in the same transaction as its audit row, so a+-- delivery is never lost and never sent for a change that rolled back.+-- The app then POSTs it, signed the Standard Webhooks way, and tries again+-- later when the receiver does not answer 2xx.+--+-- webhook_endpoints+-- * secret_encrypted: the signing secret (whsec_...), sealed with AES-GCM+-- under a key derived from BETTER_AUTH_SECRET, so a copy of the database+-- alone cannot forge deliveries.+-- * previous_secret_*: after a rotation the old secret also signs for 24+-- hours, so a receiver can switch over without dropping anything.+-- * events: the event types it receives, such as 'envelope.completed'.+--+-- webhook_deliveries+-- * id: sent as the webhook-id header. The same on every try, so a+-- receiver can ignore a delivery it already handled.+-- * payload: the JSON body, as text. Null until the first try, which+-- builds it from the envelope as it stands once the change has+-- committed. Kept byte for byte from then on (jsonb would reorder its+-- keys), so a retry sends exactly what the first try sent and signed.+-- * status: pending (to send, or to try again at next_attempt_at),+-- delivered, or failed (gave up after the last try).+-- * locked_until: set while one function is sending it, so two never send+-- the same try at once.++create table if not exists public.webhook_endpoints (+ id text primary key,+ url text not null check (length(url) between 1 and 2048),+ description text not null default '' check (length(description) <= 200),+ secret_encrypted text not null,+ previous_secret_encrypted text,+ previous_secret_expires_at bigint,+ events text[] not null,+ enabled boolean not null default true,+ created_by text references public."user"(id) on delete set null,+ created_at bigint not null,+ updated_at bigint not null+);++create table if not exists public.webhook_deliveries (+ id text primary key,+ endpoint_id text not null references public.webhook_endpoints(id) on delete cascade,+ event_type text not null,+ envelope_id text,+ audit_event_id text,+ signer_id text,+ payload text,+ status text not null default 'pending'+ check (status in ('pending', 'delivered', 'failed')),+ attempts integer not null default 0,+ next_attempt_at bigint,+ locked_until bigint,+ last_status_code integer,+ last_error text,+ created_at bigint not null,+ delivered_at bigint,+ updated_at bigint not null+);++-- What the sender looks for: pending deliveries that are due.+create index if not exists webhook_deliveries_due_idx+ on public.webhook_deliveries (next_attempt_at)+ where status = 'pending';++-- The delivery log in Settings, newest first per endpoint.+create index if not exists webhook_deliveries_endpoint_idx+ on public.webhook_deliveries (endpoint_id, created_at desc);++-- The API's catch-up list, newest first across endpoints.+create index if not exists webhook_deliveries_created_idx+ on public.webhook_deliveries (created_at desc, id desc);diff --git a/src/app/api/admin/webhooks/[id]/deliveries/route.ts b/src/app/api/admin/webhooks/[id]/deliveries/route.tsnew file mode 100644index 0000000..953513c--- /dev/null+++ b/src/app/api/admin/webhooks/[id]/deliveries/route.ts@@ -0,0 +1,18 @@+import { NextResponse } from "next/server";++import { listEndpointDeliveries } from "@/lib/webhooks/log";+import { handleWebhookAdmin, noStore } from "@/lib/webhooks/admin-route";++type RouteContext = { params: Promise<{ id: string }> };++// The last 100 deliveries to one endpoint, newest first.+export function GET(request: Request, context: RouteContext) {+ return handleWebhookAdmin(request, "webhook_log_failure", async () => {+ const { id } = await context.params;++ return NextResponse.json(+ { deliveries: await listEndpointDeliveries(id) },+ { headers: noStore },+ );+ });+}diff --git a/src/app/api/admin/webhooks/[id]/rotate/route.ts b/src/app/api/admin/webhooks/[id]/rotate/route.tsnew file mode 100644index 0000000..1a9fb52--- /dev/null+++ b/src/app/api/admin/webhooks/[id]/rotate/route.ts@@ -0,0 +1,21 @@+import { NextResponse } from "next/server";++import { rotateWebhookSecret } from "@/lib/webhooks/endpoints";+import { handleWebhookAdmin, noStore } from "@/lib/webhooks/admin-route";++type RouteContext = { params: Promise<{ id: string }> };++// A new signing secret, shown once. The old one keeps signing for a day.+export function POST(request: Request, context: RouteContext) {+ return handleWebhookAdmin(+ request,+ "webhook_rotate_failure",+ async (actor) => {+ const { id } = await context.params;++ return NextResponse.json(await rotateWebhookSecret(actor, id), {+ headers: noStore,+ });+ },+ );+}diff --git a/src/app/api/admin/webhooks/[id]/route.ts b/src/app/api/admin/webhooks/[id]/route.tsnew file mode 100644index 0000000..0db586f--- /dev/null+++ b/src/app/api/admin/webhooks/[id]/route.ts@@ -0,0 +1,73 @@+import { NextResponse } from "next/server";++import {+ deleteWebhookEndpoint,+ parseWebhookDescription,+ updateWebhookEndpoint,+} from "@/lib/webhooks/endpoints";+import { parseWebhookEventTypes } from "@/lib/webhooks/events";+import {+ handleWebhookAdmin,+ noStore,+ readJsonObject,+} from "@/lib/webhooks/admin-route";++type RouteContext = { params: Promise<{ id: string }> };++// Changes or removes one webhook endpoint. Administrators only.++export function PATCH(request: Request, context: RouteContext) {+ return handleWebhookAdmin(+ request,+ "webhook_update_failure",+ async (actor) => {+ const { id } = await context.params;+ const body = await readJsonObject(request);+ const events =+ body.events === undefined+ ? undefined+ : parseWebhookEventTypes(body.events);+ const description =+ body.description === undefined+ ? undefined+ : parseWebhookDescription(body.description);++ if (+ events === null ||+ description === null ||+ (body.enabled !== undefined && typeof body.enabled !== "boolean")+ ) {+ return NextResponse.json(+ {+ error:+ "Choose at least one event, keep the description to 200 characters, and set enabled to true or false.",+ },+ { headers: noStore, status: 400 },+ );+ }++ const endpoint = await updateWebhookEndpoint(actor, id, {+ description,+ enabled: body.enabled as boolean | undefined,+ events,+ url: body.url,+ });++ return NextResponse.json({ endpoint }, { headers: noStore });+ },+ );+}++export function DELETE(request: Request, context: RouteContext) {+ return handleWebhookAdmin(+ request,+ "webhook_delete_failure",+ async (actor) => {+ const { id } = await context.params;++ await deleteWebhookEndpoint(actor, id);++ return NextResponse.json({ deleted: true }, { headers: noStore });+ },+ );+}diff --git a/src/app/api/admin/webhooks/[id]/test/route.ts b/src/app/api/admin/webhooks/[id]/test/route.tsnew file mode 100644index 0000000..0efca75--- /dev/null+++ b/src/app/api/admin/webhooks/[id]/test/route.ts@@ -0,0 +1,51 @@+import { NextResponse } from "next/server";++import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import { sendTestWebhook } from "@/lib/webhooks/deliver";+import { getWebhookEndpoint } from "@/lib/webhooks/endpoints";+import { handleWebhookAdmin, noStore } from "@/lib/webhooks/admin-route";++type RouteContext = { params: Promise<{ id: string }> };++// Sends one webhook.test event now and says how the endpoint answered.+export function POST(request: Request, context: RouteContext) {+ return handleWebhookAdmin(request, "webhook_test_failure", async (actor) => {+ const limited = await applyRateLimit({+ category: "webhook_test",+ key: buildRateLimitKey(["webhook-test", actor.userId]),+ limit: 20,+ request,+ userId: actor.userId,+ windowMs: 10 * 60 * 1000,+ });++ if (limited) {+ return limited;+ }++ const { id } = await context.params;+ const endpoint = await getWebhookEndpoint(id);++ if (!endpoint) {+ return NextResponse.json(+ { error: "That endpoint does not exist." },+ { headers: noStore, status: 404 },+ );+ }++ if (!endpoint.enabled) {+ return NextResponse.json(+ { error: "Turn the endpoint on first." },+ { headers: noStore, status: 409 },+ );+ }++ return NextResponse.json(+ { delivery: await sendTestWebhook(id) },+ { headers: noStore },+ );+ });+}diff --git a/src/app/api/admin/webhooks/deliveries/[id]/resend/route.ts b/src/app/api/admin/webhooks/deliveries/[id]/resend/route.tsnew file mode 100644index 0000000..f85b5ca--- /dev/null+++ b/src/app/api/admin/webhooks/deliveries/[id]/resend/route.ts@@ -0,0 +1,26 @@+import { NextResponse } from "next/server";++import { scheduleWebhookDrain } from "@/lib/webhooks/deliver";+import { resendWebhookDelivery } from "@/lib/webhooks/log";+import { handleWebhookAdmin, noStore } from "@/lib/webhooks/admin-route";++type RouteContext = { params: Promise<{ id: string }> };++// "Send again": the delivery goes back in line with a full set of tries,+// and is sent right after this response.+export function POST(request: Request, context: RouteContext) {+ return handleWebhookAdmin(request, "webhook_resend_failure", async () => {+ const { id } = await context.params;++ if (!(await resendWebhookDelivery(id))) {+ return NextResponse.json(+ { error: "That delivery does not exist, or is being sent right now." },+ { headers: noStore, status: 409 },+ );+ }++ scheduleWebhookDrain();++ return NextResponse.json({ queued: true }, { headers: noStore });+ });+}diff --git a/src/app/api/admin/webhooks/route.ts b/src/app/api/admin/webhooks/route.tsnew file mode 100644index 0000000..b2a9fc1--- /dev/null+++ b/src/app/api/admin/webhooks/route.ts@@ -0,0 +1,78 @@+import { NextResponse } from "next/server";++import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import {+ createWebhookEndpoint,+ listWebhookEndpoints,+ parseWebhookDescription,+} from "@/lib/webhooks/endpoints";+import {+ parseWebhookEventTypes,+ webhookEventTypes,+} from "@/lib/webhooks/events";+import {+ handleWebhookAdmin,+ noStore,+ readJsonObject,+} from "@/lib/webhooks/admin-route";++// Webhook endpoints for the whole install. Administrators only. The signing+// secret is in the response that creates an endpoint, and nowhere else.++export function GET(request: Request) {+ return handleWebhookAdmin(request, "webhook_list_failure", async () =>+ NextResponse.json(+ {+ endpoints: await listWebhookEndpoints(),+ eventTypes: webhookEventTypes,+ },+ { headers: noStore },+ ),+ );+}++export function POST(request: Request) {+ return handleWebhookAdmin(+ request,+ "webhook_create_failure",+ async (actor) => {+ const limited = await applyRateLimit({+ category: "webhook_create",+ key: buildRateLimitKey(["webhook-create", actor.userId]),+ limit: 10,+ request,+ userId: actor.userId,+ windowMs: 10 * 60 * 1000,+ });++ if (limited) {+ return limited;+ }++ const body = await readJsonObject(request);+ const events = parseWebhookEventTypes(body.events);+ const description = parseWebhookDescription(body.description);++ if (!events || description === null) {+ return NextResponse.json(+ {+ error:+ "Choose at least one event, and keep the description to 200 characters.",+ },+ { headers: noStore, status: 400 },+ );+ }++ const created = await createWebhookEndpoint(actor, {+ description,+ events,+ url: body.url,+ });++ return NextResponse.json(created, { headers: noStore, status: 201 });+ },+ );+}diff --git a/src/app/api/internal/webhooks/route.ts b/src/app/api/internal/webhooks/route.tsnew file mode 100644index 0000000..0e26393--- /dev/null+++ b/src/app/api/internal/webhooks/route.ts@@ -0,0 +1,61 @@+import { NextResponse } from "next/server";++import { identifyRetentionCaller } from "@/lib/retention-job";+import { logRouteError } from "@/lib/security/logging";+import { consumeRateLimit } from "@/lib/security/rate-limit";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { drainWebhookDeliveries } from "@/lib/webhooks/deliver";++// Sends webhook deliveries that are due for another try. Vercel's cron+// calls this once a day (see vercel.json), which is as often as Hobby+// allows; on Pro it can be every few minutes. Most tries never wait for+// it: they go out right after the change, or with the next request.+//+// It takes the same secret as the cleanup job. With none configured, an+// anonymous caller may run it once a minute and learns nothing: it only+// sends what was due anyway.++async function handle(request: Request) {+ const caller = identifyRetentionCaller(request.headers.get("authorization"));++ if (caller === "denied") {+ return NextResponse.json({ error: "Unauthorized." }, { status: 401 });+ }++ try {+ if (caller === "anonymous") {+ const ration = await consumeRateLimit({+ key: "job:webhooks",+ limit: 1,+ windowMs: 60 * 1000,+ });++ if (!ration.allowed) {+ return new NextResponse(null, { status: 204 });+ }+ }++ const summary = await drainWebhookDeliveries({ maxBatches: 8 });++ return caller === "authorized"+ ? NextResponse.json(summary)+ : new NextResponse(null, { status: 204 });+ } catch (error) {+ logRouteError(error, {+ category: "webhook_drain_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Sending webhook deliveries failed.",+ path: getRequestPathname(request),+ });++ return new NextResponse(null, { status: 500 });+ }+}++export function GET(request: Request) {+ return handle(request);+}++export function POST(request: Request) {+ return handle(request);+}diff --git a/src/app/api/v1/webhook-deliveries/route.ts b/src/app/api/v1/webhook-deliveries/route.tsnew file mode 100644index 0000000..16ecab8--- /dev/null+++ b/src/app/api/v1/webhook-deliveries/route.ts@@ -0,0 +1,61 @@+import { z } from "zod";++import { describeZodError } from "@/lib/api/envelopes";+import { apiError, apiJson } from "@/lib/api/http";+import { handleApi } from "@/lib/api/route";+import { webhookEventTypes } from "@/lib/webhooks/events";+import { listApiWebhookDeliveries } from "@/lib/webhooks/log";++// Webhook deliveries, newest first, with what each one carried. For an app+// that was down and wants to catch up: the payloads are the same ones its+// endpoint was sent. Deliveries are kept 30 days once delivered, 90 if not.++const querySchema = z.object({+ cursor: z.string().max(200).optional(),+ limit: z.coerce.number().int().min(1).max(100).default(25),+ since: z+ .string()+ .datetime({ offset: true })+ .transform((value) => Math.floor(Date.parse(value) / 1000))+ .optional(),+ status: z.enum(["delivered", "failed", "pending"]).optional(),+ type: z.enum(webhookEventTypes).optional(),+});++export async function GET(request: Request) {+ return handleApi(+ request,+ "read",+ "api_webhook_deliveries_failure",+ async () => {+ const url = new URL(request.url);+ const query = querySchema.safeParse({+ cursor: url.searchParams.get("cursor") ?? undefined,+ limit: url.searchParams.get("limit") ?? undefined,+ since: url.searchParams.get("since") ?? undefined,+ status: url.searchParams.get("status") ?? undefined,+ type: url.searchParams.get("type") ?? undefined,+ });++ if (!query.success) {+ return apiError(400, "invalid_request", describeZodError(query.error));+ }++ const page = await listApiWebhookDeliveries(query.data);++ if (!page) {+ return apiError(+ 400,+ "invalid_request",+ "cursor: not a cursor this API gave out.",+ );+ }++ return apiJson({+ data: page.data,+ nextCursor: page.nextCursor,+ object: "list",+ });+ },+ );+}diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsxindex 3e73080..b8f0e80 100644--- a/src/components/settings/security-panel.tsx+++ b/src/components/settings/security-panel.tsx@@ -47,6 +47,9 @@ const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {two_factor_enabled: "Two-step sign-in turned on",two_factor_requirement_changed: "Two-step sign-in requirement changed",two_factor_reset: "Two-step sign-in reset by an administrator",+ webhook_endpoint_changed: "Webhook endpoint changed",+ webhook_endpoint_created: "Webhook endpoint added",+ webhook_endpoint_deleted: "Webhook endpoint removed",};const SIGN_IN_FAILURE_REASONS: Record<string, string> = {@@ -107,6 +110,20 @@ function describeEvent(event: SystemAuditEvent): string {].filter(Boolean).join(", ");+ case "webhook_endpoint_created":+ case "webhook_endpoint_changed":+ case "webhook_endpoint_deleted":+ return [+ typeof metadata.url === "string" ? metadata.url : null,+ metadata.secretRotated === true ? "new signing secret" : null,+ metadata.enabled === false+ ? "turned off"+ : metadata.enabled === true+ ? "turned on"+ : null,+ ]+ .filter(Boolean)+ .join(", ");default:return target ?? "";}diff --git a/src/lib/api/envelope-view.ts b/src/lib/api/envelope-view.tsindex d126e7b..99d5074 100644--- a/src/lib/api/envelope-view.ts+++ b/src/lib/api/envelope-view.ts@@ -229,6 +229,43 @@ export async function getApiEnvelope(return toApiEnvelope(row, signers.get(row.id) ?? []);}+/**+ * An envelope with its owner, whoever that is, for webhook payloads, which+ * go to endpoints set up for the whole install. Null once it is deleted.+ */+export async function getApiEnvelopeWithOwner(+ envelopeId: string,+ database: DbExecutor = getDb(),+): Promise<{+ envelope: ApiEnvelope;+ owner: { email: string; id: string; name: string };+} | null> {+ const row = await queryOne<+ EnvelopeRow & { ownerEmail: string; ownerId: string; ownerName: string }+ >(+ database,+ `+ SELECT ${ENVELOPE_COLUMNS},+ u.id AS "ownerId", u.email AS "ownerEmail", u.name AS "ownerName"+ FROM envelopes e+ JOIN "user" u ON u.id = e.user_id+ WHERE e.id = $1+ `,+ [envelopeId],+ );++ if (!row) {+ return null;+ }++ const signers = await readSigners([row.id], database);++ return {+ envelope: toApiEnvelope(row, signers.get(row.id) ?? []),+ owner: { email: row.ownerEmail, id: row.ownerId, name: row.ownerName },+ };+}+export function encodeCursor(createdAt: number, id: string): string {return Buffer.from(`${String(createdAt)}:${id}`, "utf8").toString("base64url",diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.tsindex a4450e9..bf88a45 100644--- a/src/lib/api/openapi.ts+++ b/src/lib/api/openapi.ts@@ -2,6 +2,8 @@// openapi.test.ts checks that every route file has a path here and every// path here has a route file, so the two cannot drift apart.+import { webhookEventTypes } from "../webhooks/events.ts";+const errorResponse = {content: {"application/json": { schema: { $ref: "#/components/schemas/Error" } },@@ -501,6 +503,50 @@ export function buildOpenApiDocument(serverUrl: string) {summary: "Create an envelope from a template",},},+ "/webhook-deliveries": {+ get: {+ parameters: [+ {+ description: "Only deliveries made at or after this time.",+ in: "query",+ name: "since",+ schema: { format: "date-time", type: "string" },+ },+ {+ in: "query",+ name: "status",+ schema: {+ enum: ["delivered", "failed", "pending"],+ type: "string",+ },+ },+ {+ in: "query",+ name: "type",+ schema: { enum: [...webhookEventTypes], type: "string" },+ },+ {+ in: "query",+ name: "limit",+ schema: {+ default: 25,+ maximum: 100,+ minimum: 1,+ type: "integer",+ },+ },+ { in: "query", name: "cursor", schema: { type: "string" } },+ ],+ responses: {+ "200": {+ description:+ "Webhook deliveries to every endpoint, newest first, each with the payload it carried (null until its first try).",+ },+ ...errors,+ },+ summary: "List webhook deliveries, to catch up on missed events",+ },+ },"/uploads": {post: {responses: {diff --git a/src/lib/api/route.ts b/src/lib/api/route.tsindex c8e1c38..d42b0d2 100644--- a/src/lib/api/route.ts+++ b/src/lib/api/route.ts@@ -22,6 +22,7 @@ import {import { DocumentImportError } from "../services/document-import.ts";import { PendingUploadError } from "../services/pending-uploads.ts";import { TemplateError } from "../templates.ts";+import { scheduleWebhookDrainIfDue } from "../webhooks/deliver.ts";import { describeZodError, type ApiActor } from "./envelopes.ts";import { apiError, apiJson, codeForStatus } from "./http.ts";import {@@ -100,6 +101,10 @@ export async function handleApi(request,};+ // A request from an app is a good moment to send webhook retries that+ // are due, so they need not wait for the daily cron.+ scheduleWebhookDrainIfDue();+try {return withRateLimitHeaders(await handler(context), principal.rateLimit);} catch (error) {diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.tsindex a3c4805..ed414e5 100644--- a/src/lib/retention-job.ts+++ b/src/lib/retention-job.ts@@ -2,6 +2,7 @@ import { createHash, timingSafeEqual } from "node:crypto";import { deleteExpiredIdempotencyKeys } from "./api/idempotency.ts";import { getDb, type DbPool } from "./db/connection.ts";+import { deleteOldWebhookDeliveries } from "./webhooks/log.ts";import {envelopeScheduleFailed,runEnvelopeSchedule,@@ -179,6 +180,12 @@ export async function runRetentionJob({}});+ await deleteOldWebhookDeliveries(database).catch((error: unknown) => {+ if (!isMissingSchemaError(error)) {+ console.error("Clearing old webhook deliveries failed:", error);+ }+ });+const schedule = await runEnvelopeSchedule({database,emailService,diff --git a/src/lib/services/audit.ts b/src/lib/services/audit.tsindex ba46dc8..fafd821 100644--- a/src/lib/services/audit.ts+++ b/src/lib/services/audit.ts@@ -13,6 +13,7 @@ import {} from "../db/connection.ts";import { logAuditRecord } from "../security/logging.ts";import { canonicalJson } from "../utils/canonical-json.ts";+import { enqueueWebhookDeliveries } from "../webhooks/outbox.ts";export type AuditEventMetadata = Record<string, unknown> | null;@@ -259,6 +260,18 @@ async function insertChainedAuditEvent(logAuditRecord({ ...fields, rowHash, trail: "envelope" });});+ // In the same transaction, so a webhook exists exactly when its event does.+ await enqueueWebhookDeliveries(+ {+ auditEventId: id,+ createdAt,+ envelopeId: input.envelopeId,+ event: input.event,+ metadata: fields.metadata,+ },+ database,+ );+return auditEventRecordSchema.parse({actorEmail: fields.actorEmail,actorType: input.actorType,diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.tsindex 18ed1d3..ae5b5e4 100644--- a/src/lib/services/system-audit.ts+++ b/src/lib/services/system-audit.ts@@ -44,6 +44,9 @@ export const systemAuditEventTypes = ["email_domain_changed","api_key_created","api_key_revoked",+ "webhook_endpoint_created",+ "webhook_endpoint_changed",+ "webhook_endpoint_deleted",] as const;export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];diff --git a/src/lib/webhooks/admin-route.ts b/src/lib/webhooks/admin-route.tsnew file mode 100644index 0000000..cd4c8cb--- /dev/null+++ b/src/lib/webhooks/admin-route.ts@@ -0,0 +1,77 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "../auth/admin.ts";+import { logRouteError } from "../security/logging.ts";+import {+ getClientIpAddress,+ getRequestPathname,+ getRequestUserAgent,+} from "../security/request.ts";+import { getSettings } from "../settings.ts";+import { WebhookEndpointError, type WebhookActor } from "./endpoints.ts";++// What every /api/admin/webhooks route shares: administrators only, not on+// a hosted install, never cached, and known errors become plain messages.++export const noStore = { "cache-control": "private, no-store" };++export async function handleWebhookAdmin(+ request: Request,+ category: string,+ run: (actor: WebhookActor) => Promise<Response>,+): Promise<Response> {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ if ((await getSettings()).hosted) {+ return NextResponse.json(+ { error: "Webhooks are for self-hosted installs." },+ { headers: noStore, status: 400 },+ );+ }++ const actor: WebhookActor = {+ email: sessionResult.user.email,+ ipAddress: getClientIpAddress(request.headers),+ userAgent: getRequestUserAgent(request.headers),+ userId: sessionResult.user.id,+ };++ try {+ return await run(actor);+ } catch (error) {+ if (error instanceof WebhookEndpointError) {+ return NextResponse.json(+ { error: error.message },+ { headers: noStore, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category,+ ipAddress: actor.ipAddress ?? null,+ message: "Unexpected failure in a webhook settings request.",+ path: getRequestPathname(request),+ userId: actor.userId,+ });++ return NextResponse.json(+ { error: "Something went wrong. Try again." },+ { headers: noStore, status: 500 },+ );+ }+}++/** The JSON object in a request body, or an empty one. */+export async function readJsonObject(+ request: Request,+): Promise<Record<string, unknown>> {+ const parsed: unknown = await request.json().catch(() => null);++ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)+ ? (parsed as Record<string, unknown>)+ : {};+}diff --git a/src/lib/webhooks/deliver.ts b/src/lib/webhooks/deliver.tsnew file mode 100644index 0000000..cb8e75c--- /dev/null+++ b/src/lib/webhooks/deliver.ts@@ -0,0 +1,518 @@+import { randomUUID } from "node:crypto";++import { waitUntil } from "@vercel/functions";++import { getApiEnvelopeWithOwner } from "../api/envelope-view.ts";+import {+ getDb,+ queryMany,+ queryOne,+ type DbExecutor,+} from "../db/connection.ts";+import { isMissingSchemaError } from "../settings.ts";+import type { EnvSource } from "../utils/env.ts";+import { signingSecretsFor } from "./endpoints.ts";+import { WEBHOOK_TEST_EVENT } from "./events.ts";+import { postWebhook, type WebhookPostResult } from "./safe-post.ts";+import { webhookHeaders } from "./signing.ts";++// Sending deliveries. A drain claims the deliveries that are due, sends+// them, and records what happened: delivered on a 2xx answer, otherwise a+// next try on the schedule below, until the last try fails for good.+//+// Three things start a drain, all inside Vercel: a change that queued a+// delivery (kept alive with waitUntil), any later API request, and+// the daily cron (see /api/internal/webhooks). On Hobby, with no traffic,+// a retry can therefore wait until the next day.++/** Seconds to wait after try 1, 2, ... before the next. */+export const RETRY_DELAYS_SECONDS = [+ 60,+ 5 * 60,+ 30 * 60,+ 2 * 60 * 60,+ 8 * 60 * 60,+ 24 * 60 * 60,+ 24 * 60 * 60,+] as const;+/** Tries in all: the first, then one after each delay. */+export const MAX_ATTEMPTS = RETRY_DELAYS_SECONDS.length + 1;+const BATCH_SIZE = 25;+const PARALLEL_SENDS = 5;+/** How long one drain may hold a delivery before another may take it. */+const LEASE_SECONDS = 60;+const MAX_ERROR_LENGTH = 500;++/** When to try again after `attempts` tries, or null to give up. */+export function nextAttemptAt(attempts: number, now: number): number | null {+ const delay = RETRY_DELAYS_SECONDS[attempts - 1];++ return delay === undefined ? null : now + delay;+}++export type WebhookPayload = {+ data: Record<string, unknown>;+ timestamp: string;+ type: string;+};++type ClaimedDelivery = {+ attempts: number;+ auditCreatedAt: number | null;+ auditMetadata: Record<string, unknown> | null;+ createdAt: number;+ envelopeId: string | null;+ eventType: string;+ id: string;+ /** The body exactly as first sent, or null before the first try. */+ payload: string | null;+ previousSecretEncrypted: string | null;+ previousSecretExpiresAt: number | null;+ secretEncrypted: string;+ signerId: string | null;+ url: string;+};++function nowInSeconds() {+ return Math.floor(Date.now() / 1000);+}++/**+ * What a delivery says, built from the envelope as it is now. Null when+ * the envelope has since been deleted, so there is nothing left to say.+ */+export async function buildWebhookPayload(+ delivery: Pick<+ ClaimedDelivery,+ | "auditCreatedAt"+ | "auditMetadata"+ | "createdAt"+ | "envelopeId"+ | "eventType"+ | "signerId"+ >,+ database: DbExecutor = getDb(),+): Promise<WebhookPayload | null> {+ if (!delivery.envelopeId) {+ return null;+ }++ const found = await getApiEnvelopeWithOwner(delivery.envelopeId, database);++ if (!found) {+ return null;+ }++ const data: Record<string, unknown> = {+ envelope: found.envelope,+ owner: found.owner,+ };++ if (delivery.signerId) {+ data.signer =+ found.envelope.signers.find(+ (signer) => signer.id === delivery.signerId,+ ) ?? null;+ }++ const reason = delivery.auditMetadata?.reason;++ if (typeof reason === "string" && reason.length > 0) {+ data.reason = reason;+ }++ return {+ data,+ timestamp: new Date(+ (delivery.auditCreatedAt ?? delivery.createdAt) * 1000,+ ).toISOString(),+ type: delivery.eventType,+ };+}++/** Takes up to `limit` due deliveries for this drain alone. */+async function claimDueDeliveries(+ database: DbExecutor,+ now: number,+ limit: number,+ onlyId?: string,+): Promise<ClaimedDelivery[]> {+ return queryMany<ClaimedDelivery>(+ database,+ `+ WITH due AS (+ SELECT d.id+ FROM webhook_deliveries d+ JOIN webhook_endpoints e ON e.id = d.endpoint_id+ WHERE d.status = 'pending'+ AND d.next_attempt_at <= $1+ AND (d.locked_until IS NULL OR d.locked_until <= $1)+ AND e.enabled+ AND ($4::text IS NULL OR d.id = $4)+ ORDER BY d.next_attempt_at, d.id+ LIMIT $2+ FOR UPDATE OF d SKIP LOCKED+ ),+ claimed AS (+ UPDATE webhook_deliveries d+ SET locked_until = $1 + $3, attempts = d.attempts + 1, updated_at = $1+ FROM due+ WHERE d.id = due.id+ RETURNING d.*+ )+ SELECT+ c.id,+ c.event_type AS "eventType",+ c.envelope_id AS "envelopeId",+ c.signer_id AS "signerId",+ c.payload,+ c.attempts,+ c.created_at AS "createdAt",+ a.created_at AS "auditCreatedAt",+ a.metadata AS "auditMetadata",+ e.url,+ e.secret_encrypted AS "secretEncrypted",+ e.previous_secret_encrypted AS "previousSecretEncrypted",+ e.previous_secret_expires_at AS "previousSecretExpiresAt"+ FROM claimed c+ JOIN webhook_endpoints e ON e.id = c.endpoint_id+ LEFT JOIN audit_events a ON a.id = c.audit_event_id+ ORDER BY c.next_attempt_at, c.id+ `,+ [now, limit, LEASE_SECONDS, onlyId ?? null],+ );+}++function describeFailure(result: WebhookPostResult): string {+ if (result.status === null) {+ return result.error;+ }++ const body = result.body.trim();++ return `Answered ${String(result.status)}${body ? `: ${body}` : ""}`;+}++async function recordOutcome(+ database: DbExecutor,+ delivery: ClaimedDelivery,+ outcome:+ | { kind: "delivered"; status: number }+ | { error: string; kind: "failed"; status: number | null }+ | { kind: "dropped"; reason: string },+ now: number,+) {+ if (outcome.kind === "delivered") {+ await database.query(+ `+ UPDATE webhook_deliveries+ SET status = 'delivered', delivered_at = $2, last_status_code = $3,+ last_error = NULL, locked_until = NULL, next_attempt_at = NULL,+ updated_at = $2+ WHERE id = $1+ `,+ [delivery.id, now, outcome.status],+ );+ return;+ }++ if (outcome.kind === "dropped") {+ await database.query(+ `+ UPDATE webhook_deliveries+ SET status = 'failed', last_error = $3, locked_until = NULL,+ next_attempt_at = NULL, updated_at = $2+ WHERE id = $1+ `,+ [delivery.id, now, outcome.reason],+ );+ return;+ }++ const next = nextAttemptAt(delivery.attempts, now);++ await database.query(+ `+ UPDATE webhook_deliveries+ SET status = $3, next_attempt_at = $4, last_status_code = $5,+ last_error = $6, locked_until = NULL, updated_at = $2+ WHERE id = $1+ `,+ [+ delivery.id,+ now,+ next === null ? "failed" : "pending",+ next,+ outcome.status,+ outcome.error.slice(0, MAX_ERROR_LENGTH),+ ],+ );+}++async function sendOne(+ database: DbExecutor,+ delivery: ClaimedDelivery,+ env: EnvSource,+): Promise<"delivered" | "failed" | "dropped"> {+ let body = delivery.payload;++ if (body === null) {+ const payload = await buildWebhookPayload(delivery, database);++ if (!payload) {+ await recordOutcome(+ database,+ delivery,+ {+ kind: "dropped",+ reason: "The envelope was deleted before it was sent.",+ },+ nowInSeconds(),+ );+ return "dropped";+ }++ body = JSON.stringify(payload);+ // Kept, so every later try sends, and signs, the same bytes.+ await database.query(+ `UPDATE webhook_deliveries SET payload = $2 WHERE id = $1`,+ [delivery.id, body],+ );+ }++ const sentAt = nowInSeconds();+ const secrets = signingSecretsFor(delivery, sentAt, env);++ if (secrets.length === 0) {+ await recordOutcome(+ database,+ delivery,+ {+ error:+ "The signing secret can no longer be read (the auth secret changed). Rotate the endpoint's secret in Settings.",+ kind: "failed",+ status: null,+ },+ sentAt,+ );+ return "failed";+ }++ const result = await postWebhook(+ delivery.url,+ {+ body,+ headers: webhookHeaders(secrets, {+ body,+ id: delivery.id,+ timestamp: sentAt,+ }),+ },+ { env },+ );+ const finishedAt = nowInSeconds();++ if (result.ok) {+ await recordOutcome(+ database,+ delivery,+ { kind: "delivered", status: result.status },+ finishedAt,+ );+ return "delivered";+ }++ await recordOutcome(+ database,+ delivery,+ { error: describeFailure(result), kind: "failed", status: result.status },+ finishedAt,+ );+ return "failed";+}++export type DrainSummary = {+ delivered: number;+ dropped: number;+ failed: number;+};++/**+ * Sends what is due, a batch at a time, a few at once. Stops after+ * `maxBatches` so one function never runs for long.+ */+export async function drainWebhookDeliveries(+ options: {+ database?: DbExecutor;+ env?: EnvSource;+ maxBatches?: number;+ onlyId?: string;+ } = {},+): Promise<DrainSummary> {+ const database = options.database ?? getDb();+ const env = options.env ?? process.env;+ const summary: DrainSummary = { delivered: 0, dropped: 0, failed: 0 };++ for (let batch = 0; batch < (options.maxBatches ?? 4); batch += 1) {+ const claimed = await claimDueDeliveries(+ database,+ nowInSeconds(),+ BATCH_SIZE,+ options.onlyId,+ );++ if (claimed.length === 0) {+ break;+ }++ for (let start = 0; start < claimed.length; start += PARALLEL_SENDS) {+ const results = await Promise.all(+ claimed.slice(start, start + PARALLEL_SENDS).map((delivery) =>+ sendOne(database, delivery, env).catch((error: unknown) => {+ console.error(+ `[webhooks] Sending delivery ${delivery.id} failed:`,+ error,+ );+ return "failed" as const;+ }),+ ),+ );++ for (const result of results) {+ summary[result] += 1;+ }+ }++ if (claimed.length < BATCH_SIZE) {+ break;+ }+ }++ return summary;+}++/** Whether anything is waiting, so callers can skip a drain cheaply. */+export async function hasDueWebhookDeliveries(+ database: DbExecutor = getDb(),+ now: number = nowInSeconds(),+): Promise<boolean> {+ try {+ const row = await queryOne<{ due: boolean }>(+ database,+ `+ SELECT EXISTS (+ SELECT 1 FROM webhook_deliveries+ WHERE status = 'pending' AND next_attempt_at <= $1+ AND (locked_until IS NULL OR locked_until <= $1)+ ) AS due+ `,+ [now],+ );++ return row?.due ?? false;+ } catch (error) {+ if (isMissingSchemaError(error)) {+ return false;+ }++ throw error;+ }+}++async function drainQuietly() {+ try {+ await drainWebhookDeliveries();+ } catch (error) {+ console.error("[webhooks] Sending deliveries failed:", error);+ }+}++/**+ * Starts sending due deliveries without holding up the response.+ * waitUntil keeps a Vercel function alive until it is done; on a server+ * that stays up it is not needed, and the work simply runs.+ */+export function scheduleWebhookDrain() {+ waitUntil(drainQuietly());+}++/** Like scheduleWebhookDrain, but only when something is due. */+export function scheduleWebhookDrainIfDue() {+ waitUntil(+ (async () => {+ if (await hasDueWebhookDeliveries().catch(() => false)) {+ await drainQuietly();+ }+ })(),+ );+}++/**+ * Queues a webhook.test delivery for one endpoint and sends it at once.+ * Returns the delivery as it ended up.+ */+export async function sendTestWebhook(+ endpointId: string,+ options: { database?: DbExecutor; env?: EnvSource } = {},+): Promise<{+ id: string;+ lastError: string | null;+ lastStatusCode: number | null;+ status: string;+}> {+ const database = options.database ?? getDb();+ const now = nowInSeconds();+ const id = `msg_${randomUUID().replaceAll("-", "")}`;+ const payload: WebhookPayload = {+ data: { message: "A test event from SignuDoc. No envelope changed." },+ timestamp: new Date(now * 1000).toISOString(),+ type: WEBHOOK_TEST_EVENT,+ };++ await database.query(+ `+ INSERT INTO webhook_deliveries (+ id, endpoint_id, event_type, payload, status, attempts,+ next_attempt_at, created_at, updated_at+ ) VALUES ($1, $2, $3, $4, 'pending', $5, $6, $6, $6)+ `,+ // A test is tried once: it starts as if it were on its last try.+ [+ id,+ endpointId,+ WEBHOOK_TEST_EVENT,+ JSON.stringify(payload),+ MAX_ATTEMPTS - 1,+ now,+ ],+ );+ await drainWebhookDeliveries({+ database,+ env: options.env,+ maxBatches: 1,+ onlyId: id,+ });++ const row = await queryOne<{+ id: string;+ lastError: string | null;+ lastStatusCode: number | null;+ status: string;+ }>(+ database,+ `+ SELECT id, status, last_status_code AS "lastStatusCode", last_error AS "lastError"+ FROM webhook_deliveries WHERE id = $1+ `,+ [id],+ );++ return (+ row ?? {+ id,+ lastError: "Not sent.",+ lastStatusCode: null,+ status: "failed",+ }+ );+}diff --git a/src/lib/webhooks/endpoints.ts b/src/lib/webhooks/endpoints.tsnew file mode 100644index 0000000..5999f5a--- /dev/null+++ b/src/lib/webhooks/endpoints.ts@@ -0,0 +1,416 @@+import { randomUUID } from "node:crypto";++import {+ getDb,+ queryMany,+ queryOne,+ withTransaction,+ type DbExecutor,+ type DbPool,+} from "../db/connection.ts";+import {+ decryptPrivateKey,+ encryptPrivateKey,+ secretKeyFor,+} from "../services/seal-identity.ts";+import { recordSystemAuditEvent } from "../services/system-audit.ts";+import type { EnvSource } from "../utils/env.ts";+import { type WebhookEventType } from "./events.ts";+import { parseWebhookUrl, WebhookUrlError } from "./safe-post.ts";+import { generateWebhookSecret } from "./signing.ts";++// Webhook endpoints: where the install sends envelope events. They belong+// to the whole install, as the email domain does, so only administrators+// add, change or remove them, and each change is on the install's audit+// trail. The signing secret is shown once, when it is made, and kept+// encrypted.++export const MAX_WEBHOOK_ENDPOINTS = 10;+/** How long the old secret keeps signing after a rotation. */+export const SECRET_ROTATION_OVERLAP_SECONDS = 24 * 60 * 60;++const SECRET_CONTEXT = "signudoc/webhook-secret/v1";++export class WebhookEndpointError extends Error {+ readonly statusCode: number;++ constructor(message: string, statusCode: number) {+ super(message);+ this.name = "WebhookEndpointError";+ this.statusCode = statusCode;+ }+}++export type WebhookEndpoint = {+ createdAt: number;+ description: string;+ enabled: boolean;+ events: WebhookEventType[];+ id: string;+ /** When the secret before the last rotation stops signing, or null. */+ previousSecretExpiresAt: number | null;+ updatedAt: number;+ url: string;+};++export type WebhookActor = {+ email: string;+ ipAddress?: string | null;+ userAgent?: string | null;+ userId: string;+};++const ENDPOINT_COLUMNS = `+ id,+ url,+ description,+ events,+ enabled,+ previous_secret_expires_at AS "previousSecretExpiresAt",+ created_at AS "createdAt",+ updated_at AS "updatedAt"+`;++function nowInSeconds() {+ return Math.floor(Date.now() / 1000);+}++export function sealWebhookSecret(+ secret: string,+ env: EnvSource = process.env,+): string {+ return encryptPrivateKey(secret, secretKeyFor(SECRET_CONTEXT, env));+}++export function openWebhookSecret(+ value: string,+ env: EnvSource = process.env,+): string | null {+ return decryptPrivateKey(value, secretKeyFor(SECRET_CONTEXT, env));+}++export function parseWebhookDescription(value: unknown): string | null {+ if (value === undefined || value === null) {+ return "";+ }++ if (typeof value !== "string") {+ return null;+ }++ const description = value.trim().replace(/\s+/g, " ");++ return description.length <= 200 ? description : null;+}++async function requireAdmin(actor: WebhookActor, tx: DbExecutor) {+ // Locked, so a role removal that lands at the same moment is seen.+ const row = await queryOne<{ role: string }>(+ tx,+ `SELECT role FROM "user" WHERE id = $1 FOR UPDATE`,+ [actor.userId],+ );++ if (row?.role !== "admin") {+ throw new WebhookEndpointError("Only an administrator can do this.", 403);+ }+}++function auditFields(actor: WebhookActor) {+ return {+ actorEmail: actor.email,+ actorUserId: actor.userId,+ ipAddress: actor.ipAddress ?? null,+ userAgent: actor.userAgent ?? null,+ };+}++function checkedUrl(value: unknown, env: EnvSource): string {+ try {+ return parseWebhookUrl(value, env).toString();+ } catch (error) {+ if (error instanceof WebhookUrlError) {+ throw new WebhookEndpointError(error.message, 400);+ }++ throw error;+ }+}++export async function listWebhookEndpoints(+ database: DbExecutor = getDb(),+): Promise<WebhookEndpoint[]> {+ return queryMany<WebhookEndpoint>(+ database,+ `SELECT ${ENDPOINT_COLUMNS} FROM webhook_endpoints ORDER BY created_at, id`,+ );+}++export async function getWebhookEndpoint(+ id: string,+ database: DbExecutor = getDb(),+): Promise<WebhookEndpoint | null> {+ return queryOne<WebhookEndpoint>(+ database,+ `SELECT ${ENDPOINT_COLUMNS} FROM webhook_endpoints WHERE id = $1`,+ [id],+ );+}++/** Adds an endpoint. Returns its secret, which is never shown again. */+export async function createWebhookEndpoint(+ actor: WebhookActor,+ input: { description: string; events: WebhookEventType[]; url: unknown },+ options: { database?: DbPool; env?: EnvSource } = {},+): Promise<{ endpoint: WebhookEndpoint; secret: string }> {+ const env = options.env ?? process.env;+ const url = checkedUrl(input.url, env);+ const secret = generateWebhookSecret();+ const id = `we_${randomUUID().replaceAll("-", "")}`;+ const createdAt = nowInSeconds();++ const endpoint = await withTransaction(async (tx) => {+ await requireAdmin(actor, tx);+ // One at a time, so two requests cannot both slip under the limit.+ await tx.query(`LOCK TABLE webhook_endpoints IN SHARE ROW EXCLUSIVE MODE`);++ const count = await queryOne<{ count: number }>(+ tx,+ `SELECT count(*)::int AS count FROM webhook_endpoints`,+ );++ if ((count?.count ?? 0) >= MAX_WEBHOOK_ENDPOINTS) {+ throw new WebhookEndpointError(+ `An install can have up to ${String(MAX_WEBHOOK_ENDPOINTS)} webhook endpoints. Remove one first.`,+ 409,+ );+ }++ const created = await queryOne<WebhookEndpoint>(+ tx,+ `+ INSERT INTO webhook_endpoints (+ id, url, description, secret_encrypted, events, enabled,+ created_by, created_at, updated_at+ ) VALUES ($1, $2, $3, $4, $5, true, $6, $7, $7)+ RETURNING ${ENDPOINT_COLUMNS}+ `,+ [+ id,+ url,+ input.description,+ sealWebhookSecret(secret, env),+ input.events,+ actor.userId,+ createdAt,+ ],+ );++ await recordSystemAuditEvent(+ {+ ...auditFields(actor),+ createdAt,+ event: "webhook_endpoint_created",+ metadata: { endpointId: id, events: input.events, url },+ },+ tx,+ );++ return created!;+ }, options.database ?? getDb());++ return { endpoint, secret };+}++/** Changes an endpoint's URL, events, description or whether it is on. */+export async function updateWebhookEndpoint(+ actor: WebhookActor,+ id: string,+ input: {+ description?: string;+ enabled?: boolean;+ events?: WebhookEventType[];+ url?: unknown;+ },+ options: { database?: DbPool; env?: EnvSource } = {},+): Promise<WebhookEndpoint> {+ const env = options.env ?? process.env;+ const url = input.url === undefined ? undefined : checkedUrl(input.url, env);+ const updatedAt = nowInSeconds();++ return withTransaction(async (tx) => {+ await requireAdmin(actor, tx);++ const before = await queryOne<WebhookEndpoint>(+ tx,+ `SELECT ${ENDPOINT_COLUMNS} FROM webhook_endpoints WHERE id = $1 FOR UPDATE`,+ [id],+ );++ if (!before) {+ throw new WebhookEndpointError("That endpoint does not exist.", 404);+ }++ const after = await queryOne<WebhookEndpoint>(+ tx,+ `+ UPDATE webhook_endpoints+ SET url = $2, description = $3, events = $4, enabled = $5, updated_at = $6+ WHERE id = $1+ RETURNING ${ENDPOINT_COLUMNS}+ `,+ [+ id,+ url ?? before.url,+ input.description ?? before.description,+ input.events ?? before.events,+ input.enabled ?? before.enabled,+ updatedAt,+ ],+ );+ const changed: Record<string, unknown> = {};++ for (const key of ["url", "description", "enabled"] as const) {+ if (after![key] !== before[key]) {+ changed[key] = after![key];+ }+ }++ if (after!.events.join(",") !== before.events.join(",")) {+ changed.events = after!.events;+ }++ if (Object.keys(changed).length > 0) {+ await recordSystemAuditEvent(+ {+ ...auditFields(actor),+ createdAt: updatedAt,+ event: "webhook_endpoint_changed",+ metadata: { endpointId: id, url: after!.url, ...changed },+ },+ tx,+ );+ }++ return after!;+ }, options.database ?? getDb());+}++/**+ * Makes a new secret. The old one keeps signing for a day as well, so a+ * receiver can switch without dropping deliveries.+ */+export async function rotateWebhookSecret(+ actor: WebhookActor,+ id: string,+ options: { database?: DbPool; env?: EnvSource } = {},+): Promise<{ endpoint: WebhookEndpoint; secret: string }> {+ const env = options.env ?? process.env;+ const secret = generateWebhookSecret();+ const rotatedAt = nowInSeconds();++ return withTransaction(async (tx) => {+ await requireAdmin(actor, tx);++ const endpoint = await queryOne<WebhookEndpoint>(+ tx,+ `+ UPDATE webhook_endpoints+ SET previous_secret_encrypted = secret_encrypted,+ previous_secret_expires_at = $2,+ secret_encrypted = $3,+ updated_at = $4+ WHERE id = $1+ RETURNING ${ENDPOINT_COLUMNS}+ `,+ [+ id,+ rotatedAt + SECRET_ROTATION_OVERLAP_SECONDS,+ sealWebhookSecret(secret, env),+ rotatedAt,+ ],+ );++ if (!endpoint) {+ throw new WebhookEndpointError("That endpoint does not exist.", 404);+ }++ await recordSystemAuditEvent(+ {+ ...auditFields(actor),+ createdAt: rotatedAt,+ event: "webhook_endpoint_changed",+ metadata: { endpointId: id, secretRotated: true, url: endpoint.url },+ },+ tx,+ );++ return { endpoint, secret };+ }, options.database ?? getDb());+}++/** Removes an endpoint and its delivery log. */+export async function deleteWebhookEndpoint(+ actor: WebhookActor,+ id: string,+ database: DbPool = getDb(),+): Promise<void> {+ await withTransaction(async (tx) => {+ await requireAdmin(actor, tx);++ const removed = await queryOne<{ url: string }>(+ tx,+ `DELETE FROM webhook_endpoints WHERE id = $1 RETURNING url`,+ [id],+ );++ if (!removed) {+ throw new WebhookEndpointError("That endpoint does not exist.", 404);+ }++ await recordSystemAuditEvent(+ {+ ...auditFields(actor),+ event: "webhook_endpoint_deleted",+ metadata: { endpointId: id, url: removed.url },+ },+ tx,+ );+ }, database);+}++/**+ * The secrets that sign a delivery now: the current one, and the one+ * before it while the rotation overlap lasts. Empty when the auth secret+ * changed and they can no longer be read.+ */+export function signingSecretsFor(+ row: {+ previousSecretEncrypted: string | null;+ previousSecretExpiresAt: number | null;+ secretEncrypted: string;+ },+ now: number,+ env: EnvSource = process.env,+): string[] {+ const secrets: string[] = [];+ const current = openWebhookSecret(row.secretEncrypted, env);++ if (current) {+ secrets.push(current);+ }++ if (+ row.previousSecretEncrypted &&+ row.previousSecretExpiresAt !== null &&+ row.previousSecretExpiresAt > now+ ) {+ const previous = openWebhookSecret(row.previousSecretEncrypted, env);++ if (previous) {+ secrets.push(previous);+ }+ }++ return secrets;+}diff --git a/src/lib/webhooks/events.ts b/src/lib/webhooks/events.tsnew file mode 100644index 0000000..6155257--- /dev/null+++ b/src/lib/webhooks/events.ts@@ -0,0 +1,59 @@+import type { AuditEventType } from "../types/domain.ts";++// The events a webhook endpoint can receive, and the audit event each one+// comes from. Every one of them is already written to an envelope's audit+// trail, so a webhook says nothing the trail does not.++export const webhookEventTypes = [+ "envelope.sent",+ "signer.viewed",+ "signer.signed",+ "envelope.completed",+ "envelope.declined",+ "envelope.voided",+ "envelope.expired",+] as const;++export type WebhookEventType = (typeof webhookEventTypes)[number];++/** Sent only by the "Send test" button, never by an envelope. */+export const WEBHOOK_TEST_EVENT = "webhook.test";++const fromAuditEvent: Partial<Record<AuditEventType, WebhookEventType>> = {+ completed: "envelope.completed",+ declined: "envelope.declined",+ expired: "envelope.expired",+ sent: "envelope.sent",+ signed: "signer.signed",+ viewed: "signer.viewed",+ voided: "envelope.voided",+};++/** The webhook event an audit event becomes, or null for one that has none. */+export function webhookEventForAuditEvent(+ event: AuditEventType,+): WebhookEventType | null {+ return fromAuditEvent[event] ?? null;+}++export function isWebhookEventType(value: unknown): value is WebhookEventType {+ return (+ typeof value === "string" &&+ (webhookEventTypes as readonly string[]).includes(value)+ );+}++/** A list of event types from a request: known ones, each once, in order. */+export function parseWebhookEventTypes(+ value: unknown,+): WebhookEventType[] | null {+ if (!Array.isArray(value) || value.length === 0) {+ return null;+ }++ if (!value.every(isWebhookEventType)) {+ return null;+ }++ return webhookEventTypes.filter((type) => value.includes(type));+}diff --git a/src/lib/webhooks/log.ts b/src/lib/webhooks/log.tsnew file mode 100644index 0000000..8c9f52b--- /dev/null+++ b/src/lib/webhooks/log.ts@@ -0,0 +1,216 @@+import {+ getDb,+ queryMany,+ queryOne,+ type DbExecutor,+} from "../db/connection.ts";+import { isoTime } from "../api/envelope-view.ts";++// The delivery log: what Settings shows per endpoint, what the API's+// catch-up list returns, "Send again", and the daily cleanup.++/** Delivered rows are kept this long, failed ones longer for looking into. */+export const DELIVERED_RETENTION_SECONDS = 30 * 24 * 60 * 60;+export const FAILED_RETENTION_SECONDS = 90 * 24 * 60 * 60;+export const MAX_LOG_ROWS = 100;++export type WebhookDeliverySummary = {+ attempts: number;+ createdAt: number;+ deliveredAt: number | null;+ endpointId: string;+ envelopeId: string | null;+ eventType: string;+ id: string;+ lastError: string | null;+ lastStatusCode: number | null;+ nextAttemptAt: number | null;+ status: "delivered" | "failed" | "pending";+};++const SUMMARY_COLUMNS = `+ id,+ endpoint_id AS "endpointId",+ event_type AS "eventType",+ envelope_id AS "envelopeId",+ status,+ attempts,+ next_attempt_at AS "nextAttemptAt",+ last_status_code AS "lastStatusCode",+ last_error AS "lastError",+ created_at AS "createdAt",+ delivered_at AS "deliveredAt"+`;++/** The newest deliveries to one endpoint. */+export async function listEndpointDeliveries(+ endpointId: string,+ database: DbExecutor = getDb(),+): Promise<WebhookDeliverySummary[]> {+ return queryMany<WebhookDeliverySummary>(+ database,+ `+ SELECT ${SUMMARY_COLUMNS}+ FROM webhook_deliveries+ WHERE endpoint_id = $1+ ORDER BY created_at DESC, id DESC+ LIMIT $2+ `,+ [endpointId, MAX_LOG_ROWS],+ );+}++/**+ * Puts a delivery back in line to be sent now, with a full set of tries.+ * False when there is no such delivery or it is being sent this moment.+ */+export async function resendWebhookDelivery(+ id: string,+ database: DbExecutor = getDb(),+ now: number = Math.floor(Date.now() / 1000),+): Promise<boolean> {+ const result = await database.query(+ `+ UPDATE webhook_deliveries+ SET status = 'pending', attempts = 0, next_attempt_at = $2,+ locked_until = NULL, updated_at = $2+ WHERE id = $1 AND (locked_until IS NULL OR locked_until <= $2)+ `,+ [id, now],+ );++ return (result.rowCount ?? 0) === 1;+}++export type ApiWebhookDelivery = {+ attempts: number;+ createdAt: string;+ deliveredAt: string | null;+ endpointId: string;+ envelopeId: string | null;+ id: string;+ lastStatusCode: number | null;+ object: "webhook_delivery";+ payload: unknown;+ status: "delivered" | "failed" | "pending";+ type: string;+};++function encodeCursor(createdAt: number, id: string) {+ return Buffer.from(`${String(createdAt)}:${id}`, "utf8").toString(+ "base64url",+ );+}++function decodeCursor(+ cursor: string,+): { createdAt: number; id: string } | null {+ const decoded = Buffer.from(cursor, "base64url").toString("utf8");+ const separator = decoded.indexOf(":");+ const createdAt = Number(decoded.slice(0, separator));+ const id = decoded.slice(separator + 1);++ return separator > 0 && Number.isInteger(createdAt) && id.startsWith("msg_")+ ? { createdAt, id }+ : null;+}++/**+ * Deliveries for the API, newest first, for an app that wants to catch up+ * on what it missed. Envelope events only: tests are left out. Null for a+ * cursor this API did not give out.+ */+export async function listApiWebhookDeliveries(+ query: {+ cursor?: string;+ limit: number;+ since?: number;+ status?: "delivered" | "failed" | "pending";+ type?: string;+ },+ database: DbExecutor = getDb(),+): Promise<{ data: ApiWebhookDelivery[]; nextCursor: string | null } | null> {+ const after = query.cursor ? decodeCursor(query.cursor) : null;++ if (query.cursor && !after) {+ return null;+ }++ const rows = await queryMany<+ WebhookDeliverySummary & { payload: string | null }+ >(+ database,+ `+ SELECT ${SUMMARY_COLUMNS}, payload+ FROM webhook_deliveries+ WHERE event_type <> 'webhook.test'+ AND ($1::bigint IS NULL OR created_at >= $1)+ AND ($2::text IS NULL OR status = $2)+ AND ($3::text IS NULL OR event_type = $3)+ AND ($4::bigint IS NULL OR (created_at, id) < ($4, $5::text))+ ORDER BY created_at DESC, id DESC+ LIMIT $6+ `,+ [+ query.since ?? null,+ query.status ?? null,+ query.type ?? null,+ after?.createdAt ?? null,+ after?.id ?? null,+ query.limit + 1,+ ],+ );+ const page = rows.slice(0, query.limit);+ const last = page.at(-1);++ return {+ data: page.map((row) => ({+ attempts: row.attempts,+ createdAt: isoTime(row.createdAt) ?? new Date(0).toISOString(),+ deliveredAt: isoTime(row.deliveredAt),+ endpointId: row.endpointId,+ envelopeId: row.envelopeId,+ id: row.id,+ lastStatusCode: row.lastStatusCode,+ object: "webhook_delivery",+ payload:+ row.payload === null ? null : (JSON.parse(row.payload) as unknown),+ status: row.status,+ type: row.eventType,+ })),+ nextCursor:+ rows.length > query.limit && last+ ? encodeCursor(last.createdAt, last.id)+ : null,+ };+}++/** For the daily cleanup. */+export async function deleteOldWebhookDeliveries(+ database: DbExecutor = getDb(),+ now: number = Math.floor(Date.now() / 1000),+): Promise<number> {+ const result = await database.query(+ `+ DELETE FROM webhook_deliveries+ WHERE (status = 'delivered' AND created_at <= $1)+ OR (status <> 'delivered' AND created_at <= $2)+ `,+ [now - DELIVERED_RETENTION_SECONDS, now - FAILED_RETENTION_SECONDS],+ );++ return result.rowCount ?? 0;+}++export async function getWebhookDeliveryEndpointId(+ id: string,+ database: DbExecutor = getDb(),+): Promise<string | null> {+ const row = await queryOne<{ endpointId: string }>(+ database,+ `SELECT endpoint_id AS "endpointId" FROM webhook_deliveries WHERE id = $1`,+ [id],+ );++ return row?.endpointId ?? null;+}diff --git a/src/lib/webhooks/outbox.ts b/src/lib/webhooks/outbox.tsnew file mode 100644index 0000000..bc4d900--- /dev/null+++ b/src/lib/webhooks/outbox.ts@@ -0,0 +1,77 @@+import { afterCommit, type DbExecutor } from "../db/connection.ts";+import type { AuditEventType } from "../types/domain.ts";+import { scheduleWebhookDrain } from "./deliver.ts";+import { webhookEventForAuditEvent } from "./events.ts";++// The outbox: recordAuditEvent calls this with the transaction it writes+// the audit row in, so a delivery exists exactly when its event does. The+// payload is built later, by the first try, from the envelope as it stands+// after the commit (see deliver.ts).+//+// On an install without webhook endpoints this is one INSERT ... SELECT+// over an empty table, which costs nothing worth measuring.++type DrainScheduler = () => void;++let drainScheduler: DrainScheduler = scheduleWebhookDrain;++/**+ * Who starts sending once new deliveries have committed. Tests replace it+ * to send on their own terms; null puts the default back.+ */+export function setWebhookDrainScheduler(scheduler: DrainScheduler | null) {+ drainScheduler = scheduler ?? scheduleWebhookDrain;+}++export async function enqueueWebhookDeliveries(+ input: {+ auditEventId: string;+ createdAt: number;+ envelopeId: string;+ event: AuditEventType;+ metadata: Record<string, unknown> | null;+ },+ database: DbExecutor,+): Promise<number> {+ const type = webhookEventForAuditEvent(input.event);++ if (!type) {+ return 0;+ }++ const signerId =+ typeof input.metadata?.signerId === "string"+ ? input.metadata.signerId+ : null;+ const result = await database.query(+ `+ INSERT INTO webhook_deliveries (+ id, endpoint_id, event_type, envelope_id, audit_event_id, signer_id,+ status, attempts, next_attempt_at, created_at, updated_at+ )+ SELECT+ 'msg_' || replace(gen_random_uuid()::text, '-', ''),+ id, $1, $2, $3, $4, 'pending', 0, $5, $5, $5+ FROM webhook_endpoints+ WHERE enabled AND $1 = ANY(events)+ `,+ // Due now. The audit event's own time can be a second ahead, since+ // events on one envelope never share a second.+ [+ type,+ input.envelopeId,+ input.auditEventId,+ signerId,+ Math.min(input.createdAt, Math.floor(Date.now() / 1000)),+ ],+ );+ const queued = result.rowCount ?? 0;++ if (queued > 0) {+ afterCommit(database, () => {+ drainScheduler();+ });+ }++ return queued;+}diff --git a/src/lib/webhooks/safe-post.ts b/src/lib/webhooks/safe-post.tsnew file mode 100644index 0000000..1fcb03e--- /dev/null+++ b/src/lib/webhooks/safe-post.ts@@ -0,0 +1,232 @@+import { lookup as dnsLookup, type LookupAddress } from "node:dns";+import { request as httpRequest, type IncomingMessage } from "node:http";+import { request as httpsRequest } from "node:https";+import type { LookupFunction } from "node:net";++import { isPrivateAddress } from "../services/private-address.ts";+import type { EnvSource } from "../utils/env.ts";++// POSTs a webhook to a URL an administrator typed in, without letting that+// URL reach inside the network the app runs in: the name is resolved, the+// request is refused if any address it gives is private, loopback or+// link-local (cloud metadata lives there), and the connection goes to the+// address that was checked, so a second lookup cannot swap it. Redirects+// are not followed. Only the first few KB of the answer are read.++export const WEBHOOK_TIMEOUT_MS = 10_000;+const MAX_RESPONSE_BYTES = 4096;++export class WebhookUrlError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "WebhookUrlError";+ }+}++/**+ * Private and plain-http URLs, for a receiver on the same machine while+ * developing or testing. Never on Vercel, whatever the variable says.+ */+export function privateWebhookUrlsAllowed(+ env: EnvSource = process.env,+): boolean {+ return env.WEBHOOK_ALLOW_PRIVATE_URLS === "1" && !env.VERCEL;+}++/** The URL as stored, or an error that says what is wrong with it. */+export function parseWebhookUrl(+ value: unknown,+ env: EnvSource = process.env,+): URL {+ if (typeof value !== "string" || value.trim().length === 0) {+ throw new WebhookUrlError("Enter the URL to send events to.");+ }++ if (value.length > 2048) {+ throw new WebhookUrlError("The URL is too long.");+ }++ let url: URL;++ try {+ url = new URL(value.trim());+ } catch {+ throw new WebhookUrlError("That is not a URL.");+ }++ const allowPrivate = privateWebhookUrlsAllowed(env);++ if (+ url.protocol !== "https:" &&+ !(allowPrivate && url.protocol === "http:")+ ) {+ throw new WebhookUrlError("The URL must start with https://.");+ }++ if (url.username || url.password) {+ throw new WebhookUrlError(+ "Leave the user name and password out of the URL. Check the signature instead.",+ );+ }++ if (url.hash) {+ url.hash = "";+ }++ if (!allowPrivate && isPrivateAddress(url.hostname)) {+ throw new WebhookUrlError(+ "The URL points at a private or local address, which the app will not call.",+ );+ }++ return url;+}++type AddressLookup = (+ hostname: string,+ callback: (error: Error | null, addresses: LookupAddress[]) => void,+) => void;++const systemLookup: AddressLookup = (hostname, callback) => {+ dnsLookup(hostname, { all: true }, (error, addresses) => {+ callback(error, addresses ?? []);+ });+};++function guardedLookup(+ resolve: AddressLookup,+ allowPrivate: boolean,+): LookupFunction {+ return (hostname, options, callback) => {+ resolve(hostname, (error, found) => {+ const family = options.family === 6 ? 6 : options.family === 4 ? 4 : 0;+ const addresses = found.filter(+ (address) => family === 0 || address.family === family,+ );++ if (error || addresses.length === 0) {+ callback(+ error ?? new WebhookUrlError(`${hostname} has no address.`),+ "",+ );+ return;+ }++ const blocked = addresses.find((address) =>+ isPrivateAddress(address.address),+ );++ if (blocked && !allowPrivate) {+ callback(+ new WebhookUrlError(+ `Refused to call a private address (${hostname} is ${blocked.address}).`,+ ),+ "",+ );+ return;+ }++ if (options.all) {+ callback(null, addresses);+ } else {+ callback(null, addresses[0]!.address, addresses[0]!.family);+ }+ });+ };+}++export type WebhookPostResult =+ | { body: string; ok: boolean; status: number }+ | { error: string; ok: false; status: null };++/** POSTs once. Never throws: a failure comes back as a result to log. */+export function postWebhook(+ url: string,+ input: { body: string; headers: Record<string, string> },+ options: {+ env?: EnvSource;+ lookup?: AddressLookup;+ timeoutMs?: number;+ } = {},+): Promise<WebhookPostResult> {+ const env = options.env ?? process.env;+ let target: URL;++ try {+ target = parseWebhookUrl(url, env);+ } catch (error) {+ return Promise.resolve({+ error: error instanceof Error ? error.message : "Not a usable URL.",+ ok: false,+ status: null,+ });+ }++ const allowPrivate = privateWebhookUrlsAllowed(env);+ const body = Buffer.from(input.body, "utf8");++ return new Promise((resolve) => {+ let settled = false;+ const finish = (result: WebhookPostResult) => {+ if (!settled) {+ settled = true;+ resolve(result);+ }+ };+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;+ const outgoing = send(+ target,+ {+ // A fresh connection each time, so each one goes through the check.+ agent: false,+ headers: { ...input.headers, "content-length": String(body.length) },+ lookup: guardedLookup(options.lookup ?? systemLookup, allowPrivate),+ method: "POST",+ signal: AbortSignal.timeout(options.timeoutMs ?? WEBHOOK_TIMEOUT_MS),+ },+ (response: IncomingMessage) => {+ const status = response.statusCode ?? 0;+ const chunks: Buffer[] = [];+ let size = 0;++ response.on("data", (chunk: Buffer) => {+ if (size < MAX_RESPONSE_BYTES) {+ chunks.push(chunk);+ size += chunk.length;+ }++ if (size >= MAX_RESPONSE_BYTES) {+ response.destroy();+ done();+ }+ });++ const done = () => {+ finish({+ body: Buffer.concat(chunks)+ .subarray(0, MAX_RESPONSE_BYTES)+ .toString("utf8"),+ ok: status >= 200 && status < 300,+ status,+ });+ };++ response.on("end", done);+ response.on("error", done);+ response.on("close", done);+ },+ );++ outgoing.on("error", (error: Error) => {+ finish({+ error:+ error.name === "TimeoutError" || error.name === "AbortError"+ ? `No answer within ${String((options.timeoutMs ?? WEBHOOK_TIMEOUT_MS) / 1000)} seconds.`+ : error.message,+ ok: false,+ status: null,+ });+ });+ outgoing.end(body);+ });+}diff --git a/src/lib/webhooks/signing.test.ts b/src/lib/webhooks/signing.test.tsnew file mode 100644index 0000000..c2a80f4--- /dev/null+++ b/src/lib/webhooks/signing.test.ts@@ -0,0 +1,76 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ generateWebhookSecret,+ signWebhook,+ verifyWebhook,+ webhookHeaders,+} from "./signing.ts";++// The example from the Standard Webhooks specification, so receivers using+// any of its libraries accept what we send.+// https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md+test("signatures match the Standard Webhooks example", () => {+ assert.equal(+ signWebhook("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw", {+ body: '{"test": 2432232314}',+ id: "msg_p5jXN8AQM9LWM0D4loKWxJek",+ timestamp: 1614265330,+ }),+ "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=",+ );+});++test("a secret is whsec_ and 32 random bytes", () => {+ const secret = generateWebhookSecret();++ assert.match(secret, /^whsec_[A-Za-z0-9+/]{43}=$/);+ assert.notEqual(secret, generateWebhookSecret());+});++test("both secrets sign during a rotation, and either one verifies", () => {+ const current = generateWebhookSecret();+ const previous = generateWebhookSecret();+ const input = {+ body: '{"type":"envelope.sent"}',+ id: "msg_1",+ timestamp: 1000,+ };+ const headers = webhookHeaders([current, previous], input);++ assert.equal(headers["webhook-signature"]!.split(" ").length, 2);++ for (const secret of [current, previous]) {+ assert.ok(+ verifyWebhook(+ secret,+ { ...input, signatureHeader: headers["webhook-signature"]! },+ 1000,+ ),+ );+ }++ assert.ok(+ !verifyWebhook(+ generateWebhookSecret(),+ { ...input, signatureHeader: headers["webhook-signature"]! },+ 1000,+ ),+ );+});++test("a changed body, or an old timestamp, does not verify", () => {+ const secret = generateWebhookSecret();+ const input = { body: '{"a":1}', id: "msg_1", timestamp: 1000 };+ const signatureHeader = signWebhook(secret, input);++ assert.ok(+ !verifyWebhook(+ secret,+ { ...input, body: '{"a":2}', signatureHeader },+ 1000,+ ),+ );+ assert.ok(!verifyWebhook(secret, { ...input, signatureHeader }, 1000 + 301));+});diff --git a/src/lib/webhooks/signing.ts b/src/lib/webhooks/signing.tsnew file mode 100644index 0000000..11b8a0a--- /dev/null+++ b/src/lib/webhooks/signing.ts@@ -0,0 +1,86 @@+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";++// Signatures in the Standard Webhooks format+// (https://www.standardwebhooks.com), so a receiver can check them with an+// existing library instead of code written for us:+//+// webhook-id: the delivery's id, the same on every try+// webhook-timestamp: seconds since 1970, when this try was sent+// webhook-signature: "v1," + base64(HMAC-SHA256(secret, id.timestamp.body))+//+// The secret is "whsec_" + base64 of 32 random bytes; the HMAC key is those+// bytes. During a rotation both secrets sign, and the header carries both+// signatures separated by a space.++export const WEBHOOK_SECRET_PREFIX = "whsec_";++export function generateWebhookSecret(): string {+ return `${WEBHOOK_SECRET_PREFIX}${randomBytes(32).toString("base64")}`;+}++function secretBytes(secret: string): Buffer {+ const encoded = secret.startsWith(WEBHOOK_SECRET_PREFIX)+ ? secret.slice(WEBHOOK_SECRET_PREFIX.length)+ : secret;++ return Buffer.from(encoded, "base64");+}++/** One "v1,<base64>" signature of a delivery. */+export function signWebhook(+ secret: string,+ input: { body: string; id: string; timestamp: number },+): string {+ const signature = createHmac("sha256", secretBytes(secret))+ .update(`${input.id}.${String(input.timestamp)}.${input.body}`)+ .digest("base64");++ return `v1,${signature}`;+}++/** The three headers for one try, signed with every secret given. */+export function webhookHeaders(+ secrets: string[],+ input: { body: string; id: string; timestamp: number },+): Record<string, string> {+ return {+ "content-type": "application/json",+ "user-agent": "SignuDoc-Webhooks/1",+ "webhook-id": input.id,+ "webhook-signature": secrets+ .map((secret) => signWebhook(secret, input))+ .join(" "),+ "webhook-timestamp": String(input.timestamp),+ };+}++/**+ * Checks a delivery the way a receiver would. Used by the tests, and+ * documented in docs/api.md for receivers without a library.+ */+export function verifyWebhook(+ secret: string,+ input: {+ body: string;+ id: string;+ signatureHeader: string;+ timestamp: number;+ },+ now: number = Math.floor(Date.now() / 1000),+ toleranceSeconds = 5 * 60,+): boolean {+ if (Math.abs(now - input.timestamp) > toleranceSeconds) {+ return false;+ }++ const expected = Buffer.from(signWebhook(secret, input));++ return input.signatureHeader.split(" ").some((candidate) => {+ const presented = Buffer.from(candidate);++ return (+ presented.length === expected.length &&+ timingSafeEqual(presented, expected)+ );+ });+}diff --git a/src/lib/webhooks/webhooks.dbtest.ts b/src/lib/webhooks/webhooks.dbtest.tsnew file mode 100644index 0000000..149dc0e--- /dev/null+++ b/src/lib/webhooks/webhooks.dbtest.ts@@ -0,0 +1,614 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import { createServer, type IncomingHttpHeaders, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, afterEach, before, test } from "node:test";++import { PDFDocument } from "pdf-lib";+import type pg from "pg";++import { createApiKey } from "../api-keys.ts";+import {+ apiCreateEnvelopeSchema,+ createEnvelopeForApi,+ type ApiActor,+} from "../api/envelopes.ts";+import { withTransaction } from "../db/connection.ts";+import { openTestDatabase } from "../db/test-database.ts";+import { recordAuditEvent } from "../services/audit.ts";+import {+ drainWebhookDeliveries,+ MAX_ATTEMPTS,+ sendTestWebhook,+} from "./deliver.ts";+import {+ createWebhookEndpoint,+ deleteWebhookEndpoint,+ rotateWebhookSecret,+ updateWebhookEndpoint,+ WebhookEndpointError,+} from "./endpoints.ts";+import {+ deleteOldWebhookDeliveries,+ listApiWebhookDeliveries,+ resendWebhookDelivery,+} from "./log.ts";+import type { WebhookEventType } from "./events.ts";+import { setWebhookDrainScheduler } from "./outbox.ts";+import { verifyWebhook } from "./signing.ts";++// Webhooks against a real Postgres and a real HTTP receiver on this+// machine. Run with `npm run test:db`.++const SETTINGS = [+ "APP_URL",+ "DATABASE_URL",+ "EMAIL_CAPTURE_DIR",+ "EMAIL_DRIVER",+ "STORAGE_DRIVER",+ "STORAGE_LOCAL_DIR",+] as const;++type Received = { body: string; headers: IncomingHttpHeaders };++let database: pg.Pool;+let workDir: string;+let pdf: Uint8Array;+let server: Server;+let receiverUrl: string;+let answer: (received: Received) => number | Promise<number> = () => 200;+const received: Received[] = [];+const createdUsers: string[] = [];+const settingsBefore = new Map<string, string | undefined>();+let env: Record<string, string | undefined>;++before(async () => {+ database = await openTestDatabase();+ workDir = await mkdtemp(path.join(tmpdir(), "signudoc-webhooks-"));++ for (const name of SETTINGS) {+ settingsBefore.set(name, process.env[name]);+ }++ process.env.APP_URL = "http://localhost:3000";+ process.env.DATABASE_URL =+ process.env.E2E_DATABASE_URL ??+ "postgres://signudoc:[email protected]:5432/signudoc_e2e";+ process.env.EMAIL_CAPTURE_DIR = path.join(workDir, "outbox");+ process.env.EMAIL_DRIVER = "capture";+ process.env.STORAGE_DRIVER = "local";+ process.env.STORAGE_LOCAL_DIR = path.join(workDir, "storage");+ env = { ...process.env, VERCEL: undefined, WEBHOOK_ALLOW_PRIVATE_URLS: "1" };++ // The tests send when they choose to.+ setWebhookDrainScheduler(() => undefined);++ const document = await PDFDocument.create();++ document.addPage([612, 792]);+ pdf = await document.save();++ server = createServer((request, response) => {+ const chunks: Buffer[] = [];++ request.on("data", (chunk: Buffer) => chunks.push(chunk));+ request.on("end", () => {+ const entry = {+ body: Buffer.concat(chunks).toString("utf8"),+ headers: request.headers,+ };++ received.push(entry);+ void Promise.resolve(answer(entry)).then((status) => {+ response.writeHead(status, { "content-type": "text/plain" });+ response.end(status >= 300 ? "receiver says no" : "ok");+ });+ });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ receiverUrl = `http://127.0.0.1:${String((server.address() as AddressInfo).port)}/hooks`;+});++afterEach(async () => {+ await database.query(`delete from webhook_endpoints`);+ received.length = 0;+ answer = () => 200;+});++after(async () => {+ setWebhookDrainScheduler(null);+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();++ for (const [name, value] of settingsBefore) {+ if (value === undefined) {+ delete process.env[name];+ } else {+ process.env[name] = value;+ }+ }++ await rm(workDir, { force: true, recursive: true });+});++async function createAdmin(role = "admin"): Promise<ApiActor> {+ const userId = randomUUID();+ const email = `${userId}@example.test`;++ createdUsers.push(userId);+ await database.query(+ `+ insert into public."user" (id, name, email, role, "emailVerified")+ values ($1, 'Ops Admin', $2, $3, true)+ `,+ [userId, email, role],+ );++ if (role !== "admin") {+ return {+ apiKeyId: "",+ email,+ ipAddress: null,+ name: "Ops",+ userAgent: null,+ userId,+ };+ }++ const { summary } = await createApiKey(+ { email, userId },+ { expiresInDays: null, name: "Billing app", scope: "write" },+ database,+ );++ return {+ apiKeyId: summary.id,+ email,+ ipAddress: null,+ name: "Ops Admin",+ userAgent: null,+ userId,+ };+}++function createRequest(send = true) {+ return apiCreateEnvelopeSchema.parse({+ fields: [+ {+ height: 0.05,+ page: 1,+ signer: "client",+ type: "signature",+ width: 0.3,+ x: 0.1,+ y: 0.8,+ },+ ],+ metadata: { invoice: "INV-7" },+ signers: [+ { email: "[email protected]", name: "Casey Client", ref: "client" },+ ],+ title: "Service agreement",+ ...(send ? { send: { permittedUseConfirmed: true } } : {}),+ });+}++async function createEnvelope(actor: ApiActor, send = true) {+ return createEnvelopeForApi(+ actor,+ createRequest(send),+ { body: pdf, contentType: "application/pdf", filename: "a.pdf" },+ database,+ );+}++async function addEndpoint(+ actor: ApiActor,+ events: WebhookEventType[] = ["envelope.sent", "envelope.voided"],+) {+ return createWebhookEndpoint(+ actor,+ { description: "Billing", events, url: receiverUrl },+ { database, env },+ );+}++async function deliveriesFor(endpointId: string) {+ return (+ await database.query<{+ attempts: number;+ eventType: string;+ id: string;+ lastError: string | null;+ lastStatusCode: number | null;+ nextAttemptAt: number | null;+ payload: string | null;+ status: string;+ }>(+ `+ select id, event_type as "eventType", status, attempts, payload,+ next_attempt_at as "nextAttemptAt", last_status_code as "lastStatusCode",+ last_error as "lastError"+ from webhook_deliveries where endpoint_id = $1 order by created_at, id+ `,+ [endpointId],+ )+ ).rows;+}++test("only an administrator can add an endpoint, and its URL must be usable", async () => {+ const user = await createAdmin("user");++ await assert.rejects(+ createWebhookEndpoint(+ user,+ { description: "", events: ["envelope.sent"], url: receiverUrl },+ { database, env },+ ),+ (error: unknown) =>+ error instanceof WebhookEndpointError && error.statusCode === 403,+ );++ const admin = await createAdmin();++ await assert.rejects(+ createWebhookEndpoint(+ admin,+ { description: "", events: ["envelope.sent"], url: receiverUrl },+ // Without the development switch, a local URL is refused.+ { database, env: { ...env, WEBHOOK_ALLOW_PRIVATE_URLS: undefined } },+ ),+ (error: unknown) =>+ error instanceof WebhookEndpointError && error.statusCode === 400,+ );++ const { endpoint, secret } = await addEndpoint(admin);++ assert.match(secret, /^whsec_/);+ assert.equal(endpoint.url, receiverUrl);++ const trail = await database.query<{ event: string }>(+ `+ select event from system_audit_events+ where actor_user_id = $1 order by sequence+ `,+ [admin.userId],+ );++ assert.ok(trail.rows.some((row) => row.event === "webhook_endpoint_created"));+ // The secret is never stored in the clear.+ const stored = await database.query<{ secret: string }>(+ `select secret_encrypted as secret from webhook_endpoints where id = $1`,+ [endpoint.id],+ );++ assert.ok(!stored.rows[0]!.secret.includes(secret.slice(6)));+});++test("a delivery is written with its audit event, and not when that rolls back", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin, ["envelope.voided"]);+ const envelope = await createEnvelope(admin);++ // envelope.sent is not one of this endpoint's events.+ assert.equal((await deliveriesFor(endpoint.id)).length, 0);++ await assert.rejects(+ withTransaction(async (tx) => {+ await recordAuditEvent(+ {+ actorType: "sender",+ envelopeId: envelope.id,+ event: "voided",+ metadata: { reason: "never happened" },+ },+ tx,+ );+ throw new Error("roll back");+ }, database),+ );+ assert.equal((await deliveriesFor(endpoint.id)).length, 0);++ await recordAuditEvent(+ {+ actorType: "sender",+ envelopeId: envelope.id,+ event: "voided",+ metadata: { reason: "Wrong client" },+ },+ database,+ );++ const rows = await deliveriesFor(endpoint.id);++ assert.equal(rows.length, 1);+ assert.equal(rows[0]!.eventType, "envelope.voided");+ assert.equal(rows[0]!.status, "pending");+ assert.equal(rows[0]!.payload, null);++ // A disabled endpoint gets nothing new.+ await updateWebhookEndpoint(+ admin,+ endpoint.id,+ { enabled: false },+ { database, env },+ );+ await recordAuditEvent(+ { actorType: "sender", envelopeId: envelope.id, event: "voided" },+ database,+ );+ assert.equal((await deliveriesFor(endpoint.id)).length, 1);+});++test("a delivery is signed, carries the envelope, and is marked delivered", async () => {+ const admin = await createAdmin();+ const { endpoint, secret } = await addEndpoint(admin);+ const envelope = await createEnvelope(admin);+ const summary = await drainWebhookDeliveries({ database, env });++ assert.equal(summary.delivered, 1);+ assert.equal(received.length, 1);++ const [delivery] = received;+ const id = delivery!.headers["webhook-id"] as string;+ const timestamp = Number(delivery!.headers["webhook-timestamp"]);++ assert.match(id, /^msg_[0-9a-f]{32}$/);+ assert.ok(+ verifyWebhook(secret, {+ body: delivery!.body,+ id,+ signatureHeader: delivery!.headers["webhook-signature"] as string,+ timestamp,+ }),+ );++ const body = JSON.parse(delivery!.body) as {+ data: {+ envelope: { id: string; metadata: unknown; status: string };+ owner: { email: string; id: string };+ };+ type: string;+ };++ assert.equal(body.type, "envelope.sent");+ assert.equal(body.data.envelope.id, envelope.id);+ assert.equal(body.data.envelope.status, "sent");+ assert.deepEqual(body.data.envelope.metadata, { invoice: "INV-7" });+ assert.equal(body.data.owner.id, admin.userId);++ const [row] = await deliveriesFor(endpoint.id);++ assert.equal(row!.status, "delivered");+ assert.equal(row!.lastStatusCode, 200);+ assert.equal(row!.id, id);+});++test("a failed try is retried later with the same payload, then given up", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin);++ answer = () => 503;+ await createEnvelope(admin);+ await drainWebhookDeliveries({ database, env });++ let [row] = await deliveriesFor(endpoint.id);+ const now = Math.floor(Date.now() / 1000);++ assert.equal(row!.status, "pending");+ assert.equal(row!.attempts, 1);+ assert.equal(row!.lastStatusCode, 503);+ assert.match(row!.lastError ?? "", /503/);+ assert.ok(row!.nextAttemptAt! >= now + 55 && row!.nextAttemptAt! <= now + 65);++ // Not due yet: nothing is sent.+ await drainWebhookDeliveries({ database, env });+ assert.equal(received.length, 1);++ // The last try is due, and fails too.+ await database.query(+ `update webhook_deliveries set attempts = $2, next_attempt_at = 0 where id = $1`,+ [row!.id, MAX_ATTEMPTS - 1],+ );+ await drainWebhookDeliveries({ database, env });+ [row] = await deliveriesFor(endpoint.id);++ assert.equal(received.length, 2);+ assert.equal(received[0]!.body, received[1]!.body);+ assert.equal(+ received[0]!.headers["webhook-id"],+ received[1]!.headers["webhook-id"],+ );+ assert.equal(row!.status, "failed");+ assert.equal(row!.nextAttemptAt, null);++ // "Send again" gives it a full set of tries.+ answer = () => 204;+ assert.ok(await resendWebhookDelivery(row!.id, database));+ await drainWebhookDeliveries({ database, env });+ [row] = await deliveriesFor(endpoint.id);+ assert.equal(row!.status, "delivered");+ assert.equal(row!.attempts, 1);+});++test("two drains at once never send the same delivery twice", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin);++ for (let index = 0; index < 6; index += 1) {+ await createEnvelope(admin);+ }++ answer = () => new Promise((resolve) => setTimeout(() => resolve(200), 50));++ const [first, second] = await Promise.all([+ drainWebhookDeliveries({ database, env }),+ drainWebhookDeliveries({ database, env }),+ ]);++ assert.equal(first.delivered + second.delivered, 6);+ assert.equal(received.length, 6);+ assert.equal(+ new Set(received.map((entry) => entry.headers["webhook-id"])).size,+ 6,+ );+ assert.ok(+ (await deliveriesFor(endpoint.id)).every(+ (row) => row.status === "delivered",+ ),+ );+});++test("a delivery for an envelope deleted before its first try is dropped", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin);+ const envelope = await createEnvelope(admin);++ await database.query(`delete from envelopes where id = $1`, [envelope.id]);+ assert.deepEqual(await drainWebhookDeliveries({ database, env }), {+ delivered: 0,+ dropped: 1,+ failed: 0,+ });+ assert.equal(received.length, 0);+ assert.equal((await deliveriesFor(endpoint.id))[0]!.status, "failed");+});++test("after a rotation both secrets sign, and an unreadable secret says so", async () => {+ const admin = await createAdmin();+ const { endpoint, secret: oldSecret } = await addEndpoint(admin);+ const { secret: newSecret } = await rotateWebhookSecret(admin, endpoint.id, {+ database,+ env,+ });++ await createEnvelope(admin);+ await drainWebhookDeliveries({ database, env });++ const [delivery] = received;+ const check = (secret: string) =>+ verifyWebhook(secret, {+ body: delivery!.body,+ id: delivery!.headers["webhook-id"] as string,+ signatureHeader: delivery!.headers["webhook-signature"] as string,+ timestamp: Number(delivery!.headers["webhook-timestamp"]),+ });++ assert.ok(check(newSecret));+ assert.ok(check(oldSecret));++ // As if BETTER_AUTH_SECRET had changed since.+ await createEnvelope(admin);+ await drainWebhookDeliveries({+ database,+ env: {+ ...env,+ BETTER_AUTH_SECRET: "a-different-secret-entirely-0123456789",+ },+ });++ const rows = await deliveriesFor(endpoint.id);++ assert.equal(received.length, 1);+ assert.match(+ rows.find((row) => row.status !== "delivered")?.lastError ?? "",+ /Rotate/,+ );+});++test("a test event is sent at once, tried once, and left out of the API list", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin);++ answer = () => 500;++ const result = await sendTestWebhook(endpoint.id, { database, env });++ assert.equal(result.status, "failed");+ assert.equal(result.lastStatusCode, 500);+ assert.equal(JSON.parse(received[0]!.body).type, "webhook.test");++ answer = () => 200;+ await createEnvelope(admin);+ await drainWebhookDeliveries({ database, env });++ const page = await listApiWebhookDeliveries({ limit: 100 }, database);++ assert.ok(page);+ assert.ok(page.data.every((delivery) => delivery.type !== "webhook.test"));+ assert.ok(+ page.data.some(+ (delivery) =>+ delivery.endpointId === endpoint.id &&+ delivery.type === "envelope.sent" &&+ delivery.status === "delivered",+ ),+ );+ assert.equal(+ await listApiWebhookDeliveries({ cursor: "nonsense", limit: 10 }, database),+ null,+ );+});++test("the API list pages with a cursor", async () => {+ const admin = await createAdmin();++ await addEndpoint(admin);++ for (let index = 0; index < 3; index += 1) {+ await createEnvelope(admin);+ }++ const first = await listApiWebhookDeliveries(+ { limit: 2, type: "envelope.sent" },+ database,+ );++ assert.ok(first?.nextCursor);++ const second = await listApiWebhookDeliveries(+ { cursor: first.nextCursor, limit: 2, type: "envelope.sent" },+ database,+ );++ assert.ok(second);++ const ids = [...first.data, ...second.data].map((delivery) => delivery.id);++ assert.equal(new Set(ids).size, ids.length);+ assert.ok(ids.length >= 3);+});++test("old deliveries are cleared, failed ones kept longer, and endpoints removed with their log", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin);++ await createEnvelope(admin);+ await createEnvelope(admin);++ const [delivered, failed] = await deliveriesFor(endpoint.id);+ const now = Math.floor(Date.now() / 1000);+ const day = 24 * 60 * 60;++ await database.query(+ `update webhook_deliveries set status = 'delivered', created_at = $2 where id = $1`,+ [delivered!.id, now - 31 * day],+ );+ await database.query(+ `update webhook_deliveries set status = 'failed', created_at = $2 where id = $1`,+ [failed!.id, now - 31 * day],+ );+ assert.equal(await deleteOldWebhookDeliveries(database, now), 1);+ assert.equal((await deliveriesFor(endpoint.id)).length, 1);+ assert.equal(await deleteOldWebhookDeliveries(database, now + 60 * day), 1);++ await createEnvelope(admin);+ await deleteWebhookEndpoint(admin, endpoint.id, database);+ assert.equal((await deliveriesFor(endpoint.id)).length, 0);+});diff --git a/src/lib/webhooks/webhooks.test.ts b/src/lib/webhooks/webhooks.test.tsnew file mode 100644index 0000000..f3e77c2--- /dev/null+++ b/src/lib/webhooks/webhooks.test.ts@@ -0,0 +1,79 @@+import assert from "node:assert/strict";+import test from "node:test";++import { MAX_ATTEMPTS, nextAttemptAt } from "./deliver.ts";+import { parseWebhookEventTypes, webhookEventForAuditEvent } from "./events.ts";+import { parseWebhookUrl, privateWebhookUrlsAllowed } from "./safe-post.ts";++test("retries back off and stop after the last try", () => {+ assert.equal(MAX_ATTEMPTS, 8);+ assert.equal(nextAttemptAt(1, 0), 60);+ assert.equal(nextAttemptAt(2, 0), 300);+ assert.equal(nextAttemptAt(5, 0), 8 * 60 * 60);+ assert.equal(nextAttemptAt(7, 0), 24 * 60 * 60);+ assert.equal(nextAttemptAt(8, 0), null);+});++test("audit events map to webhook events, and others to none", () => {+ assert.equal(webhookEventForAuditEvent("sent"), "envelope.sent");+ assert.equal(webhookEventForAuditEvent("viewed"), "signer.viewed");+ assert.equal(webhookEventForAuditEvent("completed"), "envelope.completed");+ assert.equal(webhookEventForAuditEvent("email_sent"), null);+ assert.equal(webhookEventForAuditEvent("consented"), null);+});++test("event lists keep known types once, in a fixed order", () => {+ assert.deepEqual(+ parseWebhookEventTypes([+ "envelope.completed",+ "envelope.sent",+ "envelope.sent",+ ]),+ ["envelope.sent", "envelope.completed"],+ );+ assert.equal(parseWebhookEventTypes([]), null);+ assert.equal(parseWebhookEventTypes(["envelope.deleted"]), null);+ assert.equal(parseWebhookEventTypes("envelope.sent"), null);+});++test("webhook URLs must be public https", () => {+ const env = {};++ assert.equal(+ parseWebhookUrl("https://hooks.example.com/signudoc#x", env).toString(),+ "https://hooks.example.com/signudoc",+ );++ for (const bad of [+ "http://hooks.example.com/",+ "https://127.0.0.1/",+ "https://localhost:3000/",+ "https://169.254.169.254/latest/meta-data",+ "https://[::1]/",+ "https://10.0.0.5/hook",+ "https://user:[email protected]/",+ "ftp://hooks.example.com/",+ "not a url",+ "",+ ]) {+ assert.throws(() => parseWebhookUrl(bad, env), bad);+ }+});++test("private URLs are allowed only when asked for, and never on Vercel", () => {+ assert.equal(+ privateWebhookUrlsAllowed({ WEBHOOK_ALLOW_PRIVATE_URLS: "1" }),+ true,+ );+ assert.equal(+ privateWebhookUrlsAllowed({ VERCEL: "1", WEBHOOK_ALLOW_PRIVATE_URLS: "1" }),+ false,+ );+ assert.equal(privateWebhookUrlsAllowed({}), false);+ assert.equal(+ parseWebhookUrl("http://127.0.0.1:4000/hook", {+ WEBHOOK_ALLOW_PRIVATE_URLS: "1",+ }).toString(),+ "http://127.0.0.1:4000/hook",+ );+});diff --git a/vercel.json b/vercel.jsonindex 2e3caf2..694ee09 100644--- a/vercel.json+++ b/vercel.json@@ -9,6 +9,10 @@{"path": "/api/internal/backup","schedule": "0 8 * * *"+ },+ {+ "path": "/api/internal/webhooks",+ "schedule": "30 9 * * *"}]}