feat(deps): @next/bundle-analyzer + ts-pattern exhaustive webhook
Two adoption candidates from the audit's section-35 package matrix:
1. @next/bundle-analyzer wraps next.config.ts. Run
`ANALYZE=true pnpm build` to get treemaps of client + server bundles.
Companion to the recharts dynamic-import work the audit flagged —
gives us the tool to verify the dashboard chart bundle only ships on
the dashboard surface, not routes that don't render charts. Dev-only
dependency, zero runtime impact.
2. ts-pattern replaces the 13-case event-type switch in the Documenso
webhook with `match(event).with(...).exhaustive()`. The 13 known
event types are codified as a `KnownDocumensoEvent` union with an
`isKnownEvent()` type guard so:
- Unknown events still get the informational catch-all log (so
Documenso 2.x adding a new event doesn't 500).
- The match itself is compile-time exhaustive — adding a new
event to KnownDocumensoEvent without handling it in the
match() fails the build.
This is the bug class the multi-agent audit flagged ("webhook
silently drops new event types"). Same pattern can be rolled out
to the 19-case search dispatcher and the 12-case client-restore
service when those files are next touched.
Verified: tsc clean, vitest 1293/1293 (webhook tests green).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createHash } from 'crypto';
|
||||
import { match } from 'ts-pattern';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { verifyDocumensoSecret } from '@/lib/services/documenso-webhook';
|
||||
@@ -27,6 +28,46 @@ function canonicalizeEvent(event: string): string {
|
||||
return event.toUpperCase().replace(/\./g, '_');
|
||||
}
|
||||
|
||||
// Discriminated union of every Documenso event we know how to react to.
|
||||
// Adding a new event type forces a compile error in the `match(...)`
|
||||
// below via `.exhaustive()` — so we can't ship a Documenso 2.x bump
|
||||
// without consciously deciding how to handle each new event. Anything
|
||||
// not in this list falls through to the structured-log catch-all below.
|
||||
type KnownDocumensoEvent =
|
||||
| 'DOCUMENT_SIGNED'
|
||||
| 'DOCUMENT_RECIPIENT_COMPLETED'
|
||||
| 'RECIPIENT_SIGNED'
|
||||
| 'DOCUMENT_OPENED'
|
||||
| 'RECIPIENT_VIEWED'
|
||||
| 'DOCUMENT_COMPLETED'
|
||||
| 'DOCUMENT_REJECTED'
|
||||
| 'DOCUMENT_DECLINED'
|
||||
| 'DOCUMENT_CANCELLED'
|
||||
| 'DOCUMENT_EXPIRED'
|
||||
| 'DOCUMENT_REMINDER_SENT'
|
||||
| 'DOCUMENT_CREATED'
|
||||
| 'DOCUMENT_SENT';
|
||||
|
||||
const KNOWN_DOCUMENSO_EVENTS: ReadonlySet<KnownDocumensoEvent> = new Set<KnownDocumensoEvent>([
|
||||
'DOCUMENT_SIGNED',
|
||||
'DOCUMENT_RECIPIENT_COMPLETED',
|
||||
'RECIPIENT_SIGNED',
|
||||
'DOCUMENT_OPENED',
|
||||
'RECIPIENT_VIEWED',
|
||||
'DOCUMENT_COMPLETED',
|
||||
'DOCUMENT_REJECTED',
|
||||
'DOCUMENT_DECLINED',
|
||||
'DOCUMENT_CANCELLED',
|
||||
'DOCUMENT_EXPIRED',
|
||||
'DOCUMENT_REMINDER_SENT',
|
||||
'DOCUMENT_CREATED',
|
||||
'DOCUMENT_SENT',
|
||||
]);
|
||||
|
||||
function isKnownEvent(event: string): event is KnownDocumensoEvent {
|
||||
return KNOWN_DOCUMENSO_EVENTS.has(event as KnownDocumensoEvent);
|
||||
}
|
||||
|
||||
type DocumensoRecipient = {
|
||||
email: string;
|
||||
signingStatus?: string;
|
||||
@@ -144,123 +185,101 @@ export async function POST(req: NextRequest): Promise<NextResponse> {
|
||||
const portScope = matchedPortId ? { portId: matchedPortId } : {};
|
||||
|
||||
try {
|
||||
switch (event) {
|
||||
case 'DOCUMENT_SIGNED':
|
||||
case 'DOCUMENT_RECIPIENT_COMPLETED':
|
||||
case 'RECIPIENT_SIGNED': {
|
||||
// v1.13 fires DOCUMENT_SIGNED per recipient sign;
|
||||
// 2.x fires DOCUMENT_RECIPIENT_COMPLETED for the same semantics.
|
||||
// Some 2.x deployments emit RECIPIENT_SIGNED as a v2-flavoured alias —
|
||||
// log when we see it (telemetry) and route to the same handler so v2
|
||||
// deployments don't silently drop per-recipient signs.
|
||||
if (event === 'RECIPIENT_SIGNED') {
|
||||
logger.info(
|
||||
{ event, documensoId },
|
||||
'Documenso v2 RECIPIENT_SIGNED received — routing to recipient-signed handler',
|
||||
if (!isKnownEvent(event)) {
|
||||
// New / unknown Documenso event — structured log catches the
|
||||
// shape so we can add a handler before the next webhook lands.
|
||||
logger.info({ event }, 'Unhandled Documenso webhook event type');
|
||||
} else {
|
||||
await match(event)
|
||||
.with('DOCUMENT_SIGNED', 'DOCUMENT_RECIPIENT_COMPLETED', 'RECIPIENT_SIGNED', async (e) => {
|
||||
// v1.13 fires DOCUMENT_SIGNED per recipient sign;
|
||||
// 2.x fires DOCUMENT_RECIPIENT_COMPLETED for the same semantics.
|
||||
// Some 2.x deployments emit RECIPIENT_SIGNED as a v2-flavoured alias
|
||||
// — log when we see it (telemetry) and route to the same handler so
|
||||
// v2 deployments don't silently drop per-recipient signs.
|
||||
if (e === 'RECIPIENT_SIGNED') {
|
||||
logger.info(
|
||||
{ event: e, documensoId },
|
||||
'Documenso v2 RECIPIENT_SIGNED received — routing to recipient-signed handler',
|
||||
);
|
||||
}
|
||||
const signedRecipients = recipients.filter(
|
||||
(r) => r.signingStatus === 'SIGNED' || Boolean(r.signedAt),
|
||||
);
|
||||
}
|
||||
const signedRecipients = recipients.filter(
|
||||
(r) => r.signingStatus === 'SIGNED' || Boolean(r.signedAt),
|
||||
);
|
||||
for (const r of signedRecipients) {
|
||||
await handleRecipientSigned({
|
||||
for (const r of signedRecipients) {
|
||||
await handleRecipientSigned({
|
||||
documentId: documensoId,
|
||||
recipientEmail: r.email,
|
||||
signatureHash: `${signatureHash}:signed:${r.email}`,
|
||||
...portScope,
|
||||
});
|
||||
}
|
||||
})
|
||||
.with('DOCUMENT_OPENED', 'RECIPIENT_VIEWED', async (e) => {
|
||||
// Documenso v1 sends `readStatus: 'OPENED'`; v2 has used both
|
||||
// upper and lower case across releases and may omit the field
|
||||
// entirely (the event itself signals the open). Treat the event
|
||||
// as the signal: dispatch a per-recipient open for every
|
||||
// recipient on the document so v2 deployments stop silently
|
||||
// dropping opens.
|
||||
if (e === 'RECIPIENT_VIEWED') {
|
||||
logger.info(
|
||||
{ event: e, documensoId },
|
||||
'Documenso v2 RECIPIENT_VIEWED received — routing to document-opened handler',
|
||||
);
|
||||
}
|
||||
const openedRecipients = recipients.filter(
|
||||
(r) => !r.readStatus || String(r.readStatus).toUpperCase() === 'OPENED',
|
||||
);
|
||||
for (const r of openedRecipients) {
|
||||
await handleDocumentOpened({
|
||||
documentId: documensoId,
|
||||
recipientEmail: r.email,
|
||||
signatureHash: `${signatureHash}:opened:${r.email}`,
|
||||
...portScope,
|
||||
});
|
||||
}
|
||||
})
|
||||
.with('DOCUMENT_COMPLETED', async () => {
|
||||
await handleDocumentCompleted({ documentId: documensoId, ...portScope });
|
||||
})
|
||||
.with('DOCUMENT_REJECTED', 'DOCUMENT_DECLINED', async () => {
|
||||
// v2 distinguishes Decline (recipient refuses to sign) from
|
||||
// Reject (admin cancels). Both currently map to the same
|
||||
// "rejected" terminal state in our domain.
|
||||
const rejecting = recipients.find(
|
||||
(r) => r.signingStatus === 'REJECTED' || r.signingStatus === 'DECLINED',
|
||||
);
|
||||
await handleDocumentRejected({
|
||||
documentId: documensoId,
|
||||
recipientEmail: r.email,
|
||||
signatureHash: `${signatureHash}:signed:${r.email}`,
|
||||
recipientEmail: rejecting?.email,
|
||||
signatureHash,
|
||||
...portScope,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'DOCUMENT_OPENED':
|
||||
case 'RECIPIENT_VIEWED': {
|
||||
// Documenso v1 sends `readStatus: 'OPENED'`; v2 has used both
|
||||
// upper and lower case across releases and may omit the field
|
||||
// entirely (the event itself signals the open). Treat the event
|
||||
// as the signal: dispatch a per-recipient open for every
|
||||
// recipient on the document so v2 deployments stop silently
|
||||
// dropping opens.
|
||||
//
|
||||
// RECIPIENT_VIEWED is the v2-flavoured alias for the same semantics
|
||||
// — log when we see it (telemetry) and route to the same handler.
|
||||
if (event === 'RECIPIENT_VIEWED') {
|
||||
})
|
||||
.with('DOCUMENT_CANCELLED', async () => {
|
||||
await handleDocumentCancelled({ documentId: documensoId, signatureHash, ...portScope });
|
||||
})
|
||||
.with('DOCUMENT_EXPIRED', async () => {
|
||||
await handleDocumentExpired({ documentId: documensoId, ...portScope });
|
||||
})
|
||||
.with('DOCUMENT_REMINDER_SENT', async () => {
|
||||
// Auto-reminder — informational only, no state change.
|
||||
logger.info(
|
||||
{ event, documensoId },
|
||||
'Documenso v2 RECIPIENT_VIEWED received — routing to document-opened handler',
|
||||
{
|
||||
documensoId,
|
||||
recipients: recipients.map((r) => r.email),
|
||||
...portScope,
|
||||
},
|
||||
'Documenso auto-reminder sent',
|
||||
);
|
||||
}
|
||||
const openedRecipients = recipients.filter(
|
||||
(r) => !r.readStatus || String(r.readStatus).toUpperCase() === 'OPENED',
|
||||
);
|
||||
for (const r of openedRecipients) {
|
||||
await handleDocumentOpened({
|
||||
documentId: documensoId,
|
||||
recipientEmail: r.email,
|
||||
signatureHash: `${signatureHash}:opened:${r.email}`,
|
||||
...portScope,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'DOCUMENT_COMPLETED':
|
||||
await handleDocumentCompleted({ documentId: documensoId, ...portScope });
|
||||
break;
|
||||
|
||||
case 'DOCUMENT_REJECTED':
|
||||
case 'DOCUMENT_DECLINED': {
|
||||
// Documenso v2 distinguishes Decline (recipient refuses to sign) from
|
||||
// Reject (admin cancels). Both currently map to the same "rejected"
|
||||
// terminal state in our domain — `handleDocumentRejected` records who
|
||||
// refused and freezes the workflow. Product may later refine
|
||||
// downstream UX (different audit tags / notifications), but the
|
||||
// storage shape is identical for now so they share a handler.
|
||||
const rejecting = recipients.find(
|
||||
(r) => r.signingStatus === 'REJECTED' || r.signingStatus === 'DECLINED',
|
||||
);
|
||||
await handleDocumentRejected({
|
||||
documentId: documensoId,
|
||||
recipientEmail: rejecting?.email,
|
||||
signatureHash,
|
||||
...portScope,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'DOCUMENT_CANCELLED':
|
||||
await handleDocumentCancelled({ documentId: documensoId, signatureHash, ...portScope });
|
||||
break;
|
||||
|
||||
case 'DOCUMENT_EXPIRED':
|
||||
await handleDocumentExpired({ documentId: documensoId, ...portScope });
|
||||
break;
|
||||
|
||||
case 'DOCUMENT_REMINDER_SENT':
|
||||
// Documenso auto-reminded a recipient. We don't mutate state — the
|
||||
// reminder is informational. Structured log line is enough for
|
||||
// telemetry without polluting the audit_logs table on every
|
||||
// auto-reminder Documenso sends across all ports.
|
||||
logger.info(
|
||||
{
|
||||
documensoId,
|
||||
recipients: recipients.map((r) => r.email),
|
||||
...portScope,
|
||||
},
|
||||
'Documenso auto-reminder sent',
|
||||
);
|
||||
break;
|
||||
|
||||
case 'DOCUMENT_CREATED':
|
||||
case 'DOCUMENT_SENT':
|
||||
// Created + sent are informational — we initiated these from our
|
||||
// side so the state is already authoritative in our DB. Log for
|
||||
// forward-compat / out-of-band-creation telemetry.
|
||||
logger.info({ event, documensoId, ...portScope }, 'Documenso lifecycle event');
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.info({ event }, 'Unhandled Documenso webhook event type');
|
||||
})
|
||||
.with('DOCUMENT_CREATED', 'DOCUMENT_SENT', async (e) => {
|
||||
// We initiated these from our side; log for forward-compat /
|
||||
// out-of-band-creation telemetry.
|
||||
logger.info({ event: e, documensoId, ...portScope }, 'Documenso lifecycle event');
|
||||
})
|
||||
.exhaustive();
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err, event }, 'Error processing Documenso webhook');
|
||||
|
||||
Reference in New Issue
Block a user