Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Read webhook payloads on one snapshot, and fix eight webhook details
Claude44e0ffca5089
diff --git a/docs/api.md b/docs/api.mdindex 97bd091..2e47548 100644--- a/docs/api.md+++ b/docs/api.md@@ -376,8 +376,10 @@ again.### 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+Store or queue the event first, then answer with any `2xx` within 10+seconds and do the slow work after. A `2xx` counts as delivered, so an+event your app answered but did not keep is not sent again. Any other+answer, a redirect, or no answer counts as a failure, and the deliveryis tried again 1 minute, 5 minutes, 30 minutes, 2 hours, 8 hours, 24 hoursand 24 hours later, about two and a half days in all. After the eighth tryit is marked failed. A delivery whose envelope has since been deleted is@@ -392,8 +394,10 @@ 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. Times are kept to the second, so a-`since` with a fraction counts from the start of its second, and you may+it missed, with the same payloads. `since` counts from when each delivery+was queued, which is when its event happened, not when it was sent: give+the time of the last event your app has. Times are kept to the second, so+a `since` with a fraction counts from the start of its second, and you mayget a delivery you already have: skip it by its `webhook-id`. Deliveriesare kept 30 days after they are delivered, and otherwise 90 days aftertheir last try or "Send again".diff --git a/src/components/settings/webhooks-panel.tsx b/src/components/settings/webhooks-panel.tsxindex 567df87..9061685 100644--- a/src/components/settings/webhooks-panel.tsx+++ b/src/components/settings/webhooks-panel.tsx@@ -292,6 +292,27 @@ export function WebhooksPanel() {};}, [revision]);+ // Wakes the panel when the earliest switch-over ends, so its New secret+ // button comes back without reloading the page.+ useEffect(() => {+ const ends = (endpoints ?? [])+ .map((endpoint) => endpoint.previousSecretExpiresAt)+ .filter((at): at is number => at !== null && at > now);++ if (ends.length === 0) {+ return;+ }++ const waitMs = (Math.min(...ends) - Math.floor(Date.now() / 1000)) * 1000;+ const timer = window.setTimeout(+ () => setNow(Math.floor(Date.now() / 1000)),+ // Past the end by a second, and never longer than a timer can wait.+ Math.min(Math.max(waitMs, 0) + 1000, 2_147_483_647),+ );++ return () => window.clearTimeout(timer);+ }, [endpoints, now]);+function showSecret(secret: string, endpointUrl: string) {setNewSecret({ secret, url: endpointUrl });setCopied(false);@@ -299,8 +320,9 @@ export function WebhooksPanel() {async function createEndpoint() {// A secret on screen stays until Done, so it is never lost to a second- // endpoint, made or not.- if (newSecret) {+ // endpoint, made or not. Nor while a new secret is on its way: both+ // answers would be shown, and the first would be lost.+ if (newSecret || pendingId !== null) {return;}@@ -334,8 +356,9 @@ export function WebhooksPanel() {endpoint: WebhookEndpoint,action: "delete" | "disable" | "enable" | "rotate" | "test",) {- // The same for a new secret: it would take the place of one on screen.- if (action === "rotate" && newSecret) {+ // The same for a new secret: it would take the place of one on screen,+ // or of a new endpoint's secret still on its way.+ if (action === "rotate" && (newSecret || isCreating)) {return;}@@ -491,6 +514,7 @@ export function WebhooksPanel() {className="btn-quiet min-h-12 px-5 text-sm"disabled={isCreating ||+ pendingId !== null ||newSecret !== null ||url.trim().length === 0 ||events.length === 0@@ -628,6 +652,7 @@ export function WebhooksPanel() {className="btn-quiet"disabled={pendingId !== null ||+ isCreating ||newSecret !== null ||(endpoint.previousSecretExpiresAt !== null &&endpoint.previousSecretExpiresAt > now)diff --git a/src/lib/api/envelope-view.ts b/src/lib/api/envelope-view.tsindex b652874..0e1d944 100644--- a/src/lib/api/envelope-view.ts+++ b/src/lib/api/envelope-view.ts@@ -5,6 +5,7 @@ import {queryMany,queryOne,type DbExecutor,+ type DbPool,} from "../db/connection.ts";import { signingStepOf } from "../signing-steps.ts";import type { EnvelopeStatus, SignerStatus } from "../types/domain.ts";@@ -237,9 +238,44 @@ export async function getApiEnvelope(return toApiEnvelope(row, signers.get(row.id) ?? []);}+function isPool(database: DbExecutor): database is DbPool {+ return "connect" in database && "totalCount" in database;+}++/**+ * Runs `read` on one snapshot of the database, so reads that belong+ * together cannot straddle a change that commits between them. Given a+ * client, the caller's own transaction decides.+ */+async function readOnOneSnapshot<T>(+ database: DbExecutor,+ read: (executor: DbExecutor) => Promise<T>,+): Promise<T> {+ if (!isPool(database)) {+ return read(database);+ }++ const client = await database.connect();++ try {+ await client.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY");+ const result = await read(client);+ await client.query("COMMIT");+ return result;+ } catch (error) {+ await client.query("ROLLBACK").catch(() => undefined);+ throw error;+ } finally {+ client.release();+ }+}+/*** 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.+ * The envelope and its signers are read on one snapshot: a payload is kept+ * for every retry, so it must never show a completion half-way, such as a+ * sent envelope whose signers have all signed.*/export async function getApiEnvelopeWithOwner(envelopeId: string,@@ -247,6 +283,18 @@ export async function getApiEnvelopeWithOwner(): Promise<{envelope: ApiEnvelope;owner: { email: string; id: string; name: string };+} | null> {+ return readOnOneSnapshot(database, (snapshot) =>+ readApiEnvelopeWithOwner(envelopeId, snapshot),+ );+}++async function readApiEnvelopeWithOwner(+ envelopeId: string,+ database: DbExecutor,+): Promise<{+ envelope: ApiEnvelope;+ owner: { email: string; id: string; name: string };} | null> {const row = await queryOne<EnvelopeRow & { ownerEmail: string; ownerId: string; ownerName: string }diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.tsindex 284e072..738845f 100644--- a/src/lib/api/openapi.ts+++ b/src/lib/api/openapi.ts@@ -357,7 +357,7 @@ export function buildOpenApiDocument(object: { const: "webhook_delivery", type: "string" },payload: {description:- "The JSON body it was sent with, or null before its first try.",+ "The JSON body it carries: made at its first try and sent unchanged on every later one. Null before its first try. A delivery that failed because its signing secret could not be read has one but was never sent.",type: ["object", "null"],},status: {@@ -730,7 +730,7 @@ export function buildOpenApiDocument(parameters: [{description:- "Only deliveries made at or after this time. Times are kept to the second, so a time with a fraction counts from the start of its second.",+ "Only deliveries queued at or after this time, which is when their event happened, not when they were sent. Times are kept to the second, so a time with a fraction counts from the start of its second.",in: "query",name: "since",schema: { format: "date-time", type: "string" },diff --git a/src/lib/webhooks/admin-route.ts b/src/lib/webhooks/admin-route.tsindex b8b25eb..93d10e6 100644--- a/src/lib/webhooks/admin-route.ts+++ b/src/lib/webhooks/admin-route.ts@@ -20,28 +20,33 @@ export async function handleWebhookAdmin(category: string,run: (actor: WebhookActor) => Promise<Response>,): Promise<Response> {- const sessionResult = await requireAdminSession(request);+ const ipAddress = getClientIpAddress(request.headers);+ // Known once the session is checked; a failure before that (the+ // database is down) is logged and answered the same way, just without it.+ let userId: string | null = null;- if (sessionResult instanceof Response) {- return sessionResult;- }+ try {+ const sessionResult = await requireAdminSession(request);- if ((await getSettings()).hosted) {- return NextResponse.json(- { error: "Webhooks are for self-hosted installs." },- { headers: noStore, status: 400 },- );- }+ if (sessionResult instanceof Response) {+ return sessionResult;+ }- const actor: WebhookActor = {- email: sessionResult.user.email,- ipAddress: getClientIpAddress(request.headers),- userAgent: getRequestUserAgent(request.headers),- userId: sessionResult.user.id,- };+ userId = sessionResult.user.id;- try {- return await run(actor);+ if ((await getSettings()).hosted) {+ return NextResponse.json(+ { error: "Webhooks are for self-hosted installs." },+ { headers: noStore, status: 400 },+ );+ }++ return await run({+ email: sessionResult.user.email,+ ipAddress,+ userAgent: getRequestUserAgent(request.headers),+ userId: sessionResult.user.id,+ });} catch (error) {if (error instanceof WebhookEndpointError) {return NextResponse.json(@@ -52,10 +57,10 @@ export async function handleWebhookAdmin(logRouteError(error, {category,- ipAddress: actor.ipAddress ?? null,+ ipAddress: ipAddress ?? null,message: "Unexpected failure in a webhook settings request.",path: getRequestPathname(request),- userId: actor.userId,+ userId,});return NextResponse.json(diff --git a/src/lib/webhooks/webhooks.dbtest.ts b/src/lib/webhooks/webhooks.dbtest.tsindex 4227212..827828c 100644--- a/src/lib/webhooks/webhooks.dbtest.ts+++ b/src/lib/webhooks/webhooks.dbtest.ts@@ -16,6 +16,7 @@ import {createEnvelopeForApi,type ApiActor,} from "../api/envelopes.ts";+import { getApiEnvelopeWithOwner } from "../api/envelope-view.ts";import { withTransaction } from "../db/connection.ts";import { openTestDatabase, waitUntilBlockedBy } from "../db/test-database.ts";import { recordAuditEvent } from "../services/audit.ts";@@ -317,9 +318,19 @@ test("a delivery is written with its audit event, and not when that rolls back",},tx,);+ // Queued inside the transaction...+ const inside = await tx.query(+ `select 1 from webhook_deliveries where endpoint_id = $1`,+ [endpoint.id],+ );++ assert.equal(inside.rowCount, 1);throw new Error("roll back");}, database),+ // ...and only this deliberate failure undoes it, not another one.+ (error: unknown) => error instanceof Error && error.message === "roll back",);+ // ...and gone with it.assert.equal((await deliveriesFor(endpoint.id)).length, 0);await recordAuditEvent(@@ -404,6 +415,65 @@ test("an endpoint removed while an event is recorded is skipped, and the changeassert.equal(voided.rowCount, 1);});+test("a payload reads the envelope and its signers on one snapshot", async () => {+ const admin = await createAdmin();+ const envelope = await createEnvelope(admin);+ let signedBetween = false;++ // Right after the envelope row is read, the signer signs and that+ // commits on another connection, before the signers are read.+ const signAfterEnvelopeRead = <T extends object>(executor: T): T =>+ new Proxy(executor, {+ get(target, property, receiver) {+ const value: unknown = Reflect.get(target, property, receiver);++ if (property === "query" && typeof value === "function") {+ return async (...args: unknown[]) => {+ const result: unknown = await (+ value as (...queryArgs: unknown[]) => Promise<unknown>+ ).apply(target, args);+ const text = typeof args[0] === "string" ? args[0] : "";++ if (+ !signedBetween &&+ text.includes('JOIN "user" u ON u.id = e.user_id')+ ) {+ signedBetween = true;+ await database.query(+ `update signers set status = 'signed', signed_at = $2 where envelope_id = $1`,+ [envelope.id, Math.floor(Date.now() / 1000)],+ );+ }++ return result;+ };+ }++ if (property === "connect" && typeof value === "function") {+ return async () =>+ signAfterEnvelopeRead(+ await (value as () => Promise<pg.PoolClient>).apply(target),+ );+ }++ return typeof value === "function" ? value.bind(target) : value;+ },+ });++ const found = await getApiEnvelopeWithOwner(+ envelope.id,+ signAfterEnvelopeRead(database),+ );++ assert.equal(signedBetween, true);+ assert.equal(found?.envelope.status, "sent");+ // The signing committed after the snapshot, so it is not half in it.+ assert.deepEqual(+ found?.envelope.signers.map((signer) => signer.status),+ ["notified"],+ );+});+test("a delivery is signed, carries the envelope, and is marked delivered", async () => {const admin = await createAdmin();const { endpoint, secret } = await addEndpoint(admin);@@ -770,31 +840,48 @@ test("a test event is sent at once, tried once, and left out of the API list", atest("the API list pages with a cursor", async () => {const admin = await createAdmin();-- await addEndpoint(admin);+ const { endpoint } = await addEndpoint(admin);for (let index = 0; index < 3; index += 1) {await createEnvelope(admin);}- const first = await listApiWebhookDeliveries(- { limit: 2, type: "envelope.sent" },- database,- );+ const ours = (await deliveriesFor(endpoint.id)).map((row) => row.id);- assert.ok(first?.nextCursor);+ assert.equal(ours.length, 3);- const second = await listApiWebhookDeliveries(- { cursor: first.nextCursor, limit: 2, type: "envelope.sent" },- database,- );+ // The list is install-wide, so other tests' deliveries are in it too:+ // page through all of it. Every page has something, a page that points+ // to another is full, and the last points nowhere.+ const seen: string[] = [];+ let cursor: string | undefined;+ let pages = 0;++ do {+ const page = await listApiWebhookDeliveries(+ { cursor, limit: 2, type: "envelope.sent" },+ database,+ );++ assert.ok(page);+ assert.ok(page.data.length > 0, "a page came back empty");- assert.ok(second);+ if (page.nextCursor) {+ assert.equal(page.data.length, 2);+ }++ seen.push(...page.data.map((delivery) => delivery.id));+ cursor = page.nextCursor ?? undefined;+ pages += 1;+ } while (cursor !== undefined && pages < 10_000);- const ids = [...first.data, ...second.data].map((delivery) => delivery.id);+ assert.equal(cursor, undefined);+ assert.ok(pages >= 2);+ assert.equal(new Set(seen).size, seen.length);- assert.equal(new Set(ids).size, ids.length);- assert.ok(ids.length >= 3);+ for (const id of ours) {+ assert.ok(seen.includes(id), `delivery ${id} was not listed`);+ }});test("old deliveries are cleared, failed ones kept longer, and endpoints removed with their log", async () => {