feat(documenso-phase-2): webhook handler enhancement — cascade + completion fan-out

Closes the silence after the first signing invitation. Three real
improvements on top of the existing webhook plumbing, all aligned with
the Documenso v1.32 + v2 webhook payload shape (verified against the
official OpenAPI spec + Context7 docs):

1. Cascading "your turn" emails — when DOCUMENT_SIGNED / DOCUMENT_
   RECIPIENT_COMPLETED / RECIPIENT_SIGNED fires for a recipient,
   handleRecipientSigned now resolves the next pending signer in
   signing order and sends them the branded sendSigningInvitation()
   email with the embedded-host-wrapped URL. Stamps invitedAt so a
   duplicate webhook retry doesn't re-send.

2. On-completion PDF distribution — handleDocumentCompleted now re-
   reads the just-committed signedFileId, resolves all signers, and
   fires sendSigningCompleted() to every recipient with the signed
   PDF attached. resolveAttachments in lib/email already pulls bytes
   through getStorageBackend() so this works under both the s3/minio
   and filesystem backends without changes. Failures fall through to
   logger.error rather than throwing — the document is already marked
   completed and the admin can re-trigger manually.

3. Token-based recipient matching — Documenso v1 + v2 webhook recipients
   carry a `token` field (per the OpenAPI spec); same token appears in
   the document-create response. Captured at send time into the existing
   document_signers.signing_token column (already in schema from Phase 1)
   and used by handleRecipientSigned + handleDocumentOpened before
   falling back to email match. Robust against the case where one email
   serves multiple roles on a contract — which is the documented gap in
   the legacy nocodb-based handler.

Supporting changes:
- New helper module lib/services/documenso-signers.ts with
  extractSigningToken() (URL-tail fallback), DOC_TYPE_LABEL map, and
  nextPendingSigner() picker. 11 unit tests cover the token-regex,
  the helper picks the lowest pending signing-order, and rejects
  declined/signed correctly.
- documenso-client normalizeDocument now reads `token` from both
  `recipients[]` and the legacy capital-R `Recipient[]` array Documenso
  v1.32 sometimes ships in webhooks.
- documents.service signer-update at send time prefers the explicit
  token field, falling back to extractSigningToken(signingUrl) for any
  v2 deployment whose distribute response omits it.

Out of scope for Phase 2 (per the build plan):
- Custom-doc upload-to-Documenso path (Phase 3)
- Recipient + field-placement UI (Phase 4)
- DNS-rebinding hardening + circuit-breaker (deferred-refactor list)
- Auto-reminder cron — manual "Send reminder" button + auto-reminder
  toggle remain manual until Phase 6 polish

Tests: 1315/1315 vitest  + 11 new tests for documenso-signers ;
tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-13 13:47:33 +02:00
parent ebdd8408bf
commit 3dc4c6ff14
5 changed files with 389 additions and 21 deletions

View File

@@ -0,0 +1,61 @@
/**
* Small helpers shared between the document-signing flows and the
* Documenso webhook handlers. Kept in their own file so the two
* heavyweight callers (`documents.service.ts` + the webhook handler
* routes) don't have to depend on each other for a 30-line utility.
*/
import type { DocumentLabel } from '@/lib/services/document-signing-emails.service';
import type { DocumentSigner } from '@/lib/db/schema/documents';
/**
* Pull the per-recipient signing token out of a Documenso signing URL.
* Both v1.13 and v2 emit URLs of the form
* `https://signatures.example.com/sign/<token>`
* so the token is the last non-empty path segment. Returns null when
* the URL is empty / unparseable / doesn't carry a token-shaped tail.
*
* Used at document-send time to populate `document_signers.signing_token`
* so subsequent webhook deliveries can match recipients by token
* (more robust than email match when one address serves multiple roles).
*/
export function extractSigningToken(url: string | null | undefined): string | null {
if (!url) return null;
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return null;
}
const segments = parsed.pathname.split('/').filter(Boolean);
const last = segments[segments.length - 1];
if (!last) return null;
// A token must be at least 8 chars and contain only URL-safe chars —
// discriminates real tokens from generic words like "sign" or "embed"
// that some Documenso 2.x deployments append.
if (last.length < 8) return null;
if (!/^[A-Za-z0-9_-]+$/.test(last)) return null;
return last;
}
/** Map of internal documentType to the customer-facing label used in
* email subjects + body copy. Duplicated in send-invitation/route.ts
* but consolidated here so the webhook cascade picks up the same
* label without re-defining the map. */
export const DOC_TYPE_LABEL: Record<string, DocumentLabel> = {
eoi: 'Expression of Interest',
contract: 'Sales Contract',
reservation_agreement: 'Reservation Agreement',
};
/** Pick the next pending signer in signing order. Returns null when
* every signer in the list has signed (or declined). */
export function nextPendingSigner<T extends Pick<DocumentSigner, 'status' | 'signingOrder'>>(
signers: T[],
): T | null {
// signers list is assumed pre-sorted asc by signingOrder; we
// defensively pick the lowest-order pending row regardless.
const pending = signers.filter((s) => s.status === 'pending');
if (pending.length === 0) return null;
return pending.reduce((lo, s) => (s.signingOrder < lo.signingOrder ? s : lo));
}