Files
pn-new-crm/src/app/api/webhooks/documenso/route.ts
Matt Ciaccio 588f8bc43c fix(audit): security HIGHs — rate-limit hard-delete codes, collapse error msgs, doc bad-secret per-IP
H1: hard-delete-request and bulk-hard-delete-request endpoints had no
rate limit; an admin's compromised account could email-bomb the
operator's inbox or use the endpoints as a client-id oracle. Added a
new `hardDeleteCode` limiter (5 per hour per user).

H3: hard-delete error messages distinguished "no code requested" from
"wrong code", letting an attacker brute-force the 4-digit space with
~5k attempts (vs the full 10k). Both single + bulk paths now return
the same 'Invalid or expired confirmation code' message.

H5: invalid Documenso webhook secret submissions are now rate-limited
per-IP (10 per 15min) and only audit-logged inside the cap, so a slow
enumeration can't fill the audit log silently. Real Documenso traffic
won't fail the secret check, so any traffic beyond the cap is
brute-force.

1175/1175 vitest passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 22:06:40 +02:00

218 lines
7.4 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { createHash } from 'crypto';
import { db } from '@/lib/db';
import { verifyDocumensoSecret } from '@/lib/services/documenso-webhook';
import { listDocumensoWebhookSecrets } from '@/lib/services/port-config';
import {
handleRecipientSigned,
handleDocumentCompleted,
handleDocumentExpired,
handleDocumentOpened,
handleDocumentRejected,
handleDocumentCancelled,
} from '@/lib/services/documents.service';
import { logger } from '@/lib/logger';
import { createAuditLog } from '@/lib/audit';
import { checkRateLimit, rateLimiters } from '@/lib/rate-limit';
// BR-024: Dedup via signatureHash unique index on documentEvents
// Always return 200 from webhook (webhook best practice)
// Documenso emits Prisma enum names on the wire (e.g. "DOCUMENT_SIGNED").
// The UI displays them as lowercase-dotted ("document.signed") but the JSON
// body uses the enum value as-is. Normalize both forms in case 2.x ever flips.
function canonicalizeEvent(event: string): string {
return event.toUpperCase().replace(/\./g, '_');
}
type DocumensoRecipient = {
email: string;
signingStatus?: string;
readStatus?: string;
signedAt?: string | null;
};
type DocumensoWebhookBody = {
event: string;
payload: {
id: number | string;
recipients?: DocumensoRecipient[];
};
};
export async function POST(req: NextRequest): Promise<NextResponse> {
let rawBody: string;
try {
rawBody = await req.text();
} catch {
return NextResponse.json({ ok: false }, { status: 200 });
}
// Documenso v1.13 + 2.x send the secret in plaintext via X-Documenso-Secret.
// Resolve the matching port by trying each configured per-port secret
// (plus the global env fallback) with timing-safe comparison. The
// resolved portId, when non-null, is threaded into handleDocumentExpired
// so two ports sharing a documensoId can't cross-mutate (auditor-D §22).
const providedSecret = req.headers.get('x-documenso-secret') ?? '';
const secrets = await listDocumensoWebhookSecrets();
let matchedPortId: string | null = null;
let matched = false;
for (const entry of secrets) {
if (verifyDocumensoSecret(providedSecret, entry.secret)) {
matched = true;
matchedPortId = entry.portId;
break;
}
}
if (!matched) {
const callerIp =
req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
req.headers.get('x-real-ip') ??
'unknown';
// Rate-limit per IP. Real Documenso traffic won't fail the secret
// check, so any traffic here is enumeration / brute-force; we cap
// it sharply to keep audit-log volume bounded too.
const rl = await checkRateLimit(callerIp, rateLimiters.webhookBadSecret);
logger.warn(
{ providedLen: providedSecret.length, ip: callerIp, allowed: rl.allowed },
'Invalid Documenso webhook secret',
);
if (rl.allowed) {
void createAuditLog({
userId: null,
portId: null,
action: 'webhook_failed',
entityType: 'webhook_inbound',
entityId: 'documenso',
metadata: {
reason: 'invalid_secret',
providedLen: providedSecret.length,
},
ipAddress: callerIp,
userAgent: req.headers.get('user-agent') ?? '',
severity: 'warning',
source: 'webhook',
});
}
// Always return 200 (webhook best-practice — don't leak signal).
return NextResponse.json({ ok: false, error: 'Invalid secret' }, { status: 200 });
}
// Compute deduplication hash
const signatureHash = createHash('sha256').update(rawBody).digest('hex');
let parsed: DocumensoWebhookBody;
try {
parsed = JSON.parse(rawBody) as DocumensoWebhookBody;
} catch {
logger.warn('Failed to parse Documenso webhook payload');
return NextResponse.json({ ok: false }, { status: 200 });
}
// Replay guard: if any event with this hash already exists, skip.
try {
const existing = await db.query.documentEvents.findFirst({
where: (de, { eq }) => eq(de.signatureHash, signatureHash),
});
if (existing) {
logger.info({ signatureHash }, 'Duplicate Documenso webhook - skipping');
return NextResponse.json({ ok: true }, { status: 200 });
}
} catch (err) {
logger.error({ err }, 'Failed to check duplicate webhook');
}
const event = canonicalizeEvent(parsed.event);
const documensoId = String(parsed.payload?.id ?? '');
const recipients = parsed.payload?.recipients ?? [];
if (!documensoId) {
logger.warn({ event }, 'Documenso webhook missing payload.id');
return NextResponse.json({ ok: true }, { status: 200 });
}
// Every handler accepts an optional `portId` and refuses to mutate when
// the lookup is ambiguous across multiple ports without one. Forward
// the secret-resolved portId everywhere — not just the expired path —
// so signed/completed/opened/rejected/cancelled events can't flip a
// foreign-tenant document via documensoId reuse.
const portScope = matchedPortId ? { portId: matchedPortId } : {};
try {
switch (event) {
case 'DOCUMENT_SIGNED':
case 'DOCUMENT_RECIPIENT_COMPLETED': {
// v1.13 fires DOCUMENT_SIGNED per recipient sign;
// 2.x fires DOCUMENT_RECIPIENT_COMPLETED for the same semantics.
const signedRecipients = recipients.filter(
(r) => r.signingStatus === 'SIGNED' || Boolean(r.signedAt),
);
for (const r of signedRecipients) {
await handleRecipientSigned({
documentId: documensoId,
recipientEmail: r.email,
signatureHash: `${signatureHash}:signed:${r.email}`,
...portScope,
});
}
break;
}
case 'DOCUMENT_OPENED': {
// 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.
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': {
const rejecting = recipients.find((r) => r.signingStatus === 'REJECTED');
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;
default:
logger.info({ event }, 'Unhandled Documenso webhook event type');
}
} catch (err) {
logger.error({ err, event }, 'Error processing Documenso webhook');
}
return NextResponse.json({ ok: true }, { status: 200 });
}