fix(audit): comprehensive 2026-05-15 audit fix wave + Documenso v2 polish

Bundles the prior session's 50-task fix sweep (Documenso v2 + EOI/signing-
progress redesign + env-to-admin migration + dev-mode banner) with the
2026-05-18 audit fix wave (3 CRITICAL, 14 HIGH, 28 MEDIUM, 6 LOW).

CRITICAL (3):
 - C-01 interest-berths INNER JOIN -> LEFT JOIN so hard-deleted berths
   no longer silently drop interest links
 - C-02 /setup added to PUBLIC_PATHS; fresh-deploy bootstrap loop fixed
 - C-03 generic PATCH /interests/[id] no longer accepts pipelineStage —
   callers must go through /stage with the override-guard chain

HIGH (14/15):
 - H-01 explicit ON DELETE on previously-implicit NO ACTION FKs across
   interests/documents/reservations/reminders/invoices (migration 0070)
 - H-02 login page reads ?redirect= param with same-origin guard
 - H-03 CRM invite token moves to URL fragment so it never lands in
   nginx access logs / Referer headers
 - H-04 Retry-After header on sign-in-by-identifier 429 (RFC 6585 §4)
 - H-05 toggleAccount writes an audit row
 - H-06 upsertSetting masks any value whose key ends with _encrypted
 - H-07 archiveClient cascade fires per-interest audit rows
 - H-08 createSalesTransporter applies SMTP_TIMEOUTS
 - H-09 AppShell stable children — viewport flip across breakpoint no
   longer destroys in-progress form drafts
 - H-10 portal documents page swaps Unicode glyph status icons for
   Lucide CheckCircle2/XCircle/Circle + aria-labels
 - H-12 list components swap alert(...) for toast.warning(...)
 - H-13 5 icon-only buttons gain aria-label
 - H-14 parseBody treats empty bodies as {}
 - H-15 admin layout renders a 403 panel instead of silent bounce
 - H-11 not applicable — mobile-search-overlay IS a mobile bottom-sheet

MEDIUM (28+):
 - M-MT01-05 defense-in-depth port_id/parent-id filters on UPDATE/DELETE
   WHEREs across custom-fields, notes (all 6 entity types x update +
   delete), client-contacts, yacht ownerClient lookup, webhook reads
 - M-D01 documents-hub realtime event-name typo (file:created -> uploaded)
 - M-EM01 portal-auth emails thread through portId
 - M-EM02 sendEmail accepts cc/bcc params
 - M-EM04 notification_digest catalog key
 - M-IN01 portal presigned download URLs use 4h TTL
 - M-IN02 OpenAI client lazy-instantiated
 - M-IN04 stale pdfme refs updated to pdf-lib AcroForm
 - M-IN05 umami.testConnection returns tagged union
 - M-L01 reservations tenure_type unified with berths
 - M-L02 report-generators canonicalize stage values
 - M-AU01 audit log placeholder copy fixed
 - M-AU04 outcome_set / outcome_cleared distinct audit verbs
 - M-NEW-2 activity feed entity name+type separator
 - M-R01 portal allowlist narrowed + portal_session backstop in proxy
 - M-SC02 companies archived partial index
 - M-SC04 audit_logs.searchText documented as DB-managed
 - M-S01 storage_s3_access_key_encrypted admin field
 - M-U01 audit log empty state uses <EmptyState>
 - M-U09 invoice delete dialog -> <AlertDialog>
 - M-U10 toast.success on ClientForm + InterestForm create/edit
 - M-U11 settings-form-card logo preview alt text
 - M-U14 mobile topbar title on clients/yachts/interests/berths
 - M-U15 Invoices in mobile More-sheet

LOW (6/8):
 - L-AU01 severity defaults for security-relevant verbs
 - L-AU02 +13 missing actions in admin audit filter
 - L-AU03 +7 missing entity types in admin audit filter
 - L-AU04 dead listAuditLogs stubbed
 - L-D02 CLAUDE.md Owner-wins chain tightened

Bonus — Document detail polish (#67 partial, 3/6 deliverables):
 - state-aware action button per signer
 - watcher Add UI with display-name resolution
 - cleanSignerName cleanup

Prior session work bundled in:
 - Documenso v2 webhook + envelope-ID normalization + sequential signing
 - SigningProgress UI redesign (avatars, per-signer state, timestamps)
 - env->admin settings registry + RegistryDrivenForm + encrypted creds
 - Embedded-signing card + Test connection + setup help
 - Dev-mode EMAIL_REDIRECT_TO banner
 - Pipeline rules admin page
 - Sales email config card
 - Audit log details Sheet
 - EOI tab: Finalising badge, absolute timestamps, sequential indicator
 - Notes pipeline_stage_at_creation (migration 0069)
 - Documenso numeric ID dual-key webhook (migration 0068)
 - Dimensions criterion copy (migration 0067)

Tests: 1374/1374 vitest pass. tsc clean. lint clean.

See docs/AUDIT-FIX-WAVE-2026-05-18.md for the full progress report and
the user-input items still pending.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-18 13:28:50 +02:00
parent 397dbd1490
commit 4b5f85cb7d
158 changed files with 12255 additions and 1303 deletions

View File

@@ -2,7 +2,7 @@ import { and, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { formatDate } from '@/lib/utils/format-date';
import { documentTemplates, documents, files } from '@/lib/db/schema/documents';
import { documentTemplates, documents, documentSigners, files } from '@/lib/db/schema/documents';
import type { File as DbFile, Document as DbDocument } from '@/lib/db/schema/documents';
import { clients, clientContacts } from '@/lib/db/schema/clients';
import { interests } from '@/lib/db/schema/interests';
@@ -483,13 +483,16 @@ async function generateEoiFromSourcePdf(
portId: string,
context: GenerateInput,
meta: AuditMeta,
options?: { dimensionUnit?: 'ft' | 'm' },
): Promise<{ document: DbDocument; file: DbFile }> {
if (!context.interestId) {
throw new ValidationError('interestId is required for EOI template generation');
}
const eoiContext = await buildEoiContext(context.interestId, portId);
const pdfBytes = await generateEoiPdfFromTemplate(eoiContext);
const pdfBytes = await generateEoiPdfFromTemplate(eoiContext, {
dimensionUnit: options?.dimensionUnit ?? eoiContext.yacht?.lengthUnit ?? 'ft',
});
const port = await db.query.ports.findFirst({ where: eq(ports.id, portId) });
@@ -569,9 +572,9 @@ async function generateEoiFromSourcePdf(
/**
* BR-142: EOI / NDA signing. Dual pathway:
* - `inapp`: produce the PDF locally (EOI templates fill the same source
* PDF as Documenso via pdf-lib; other template types fall back to the
* HTML→pdfme path), upload to MinIO, then upload to Documenso and send
* for signing.
* PDF as Documenso via pdf-lib AcroForm; other template types fall
* back to the @react-pdf/renderer path), upload to MinIO, then upload
* to Documenso and send for signing.
* - `documenso-template`: skip our PDF generation entirely; call Documenso's
* template-generate endpoint with the shared EOI context. Documenso owns
* the PDF. We still record a `documents` row for tracking.
@@ -583,14 +586,15 @@ export async function generateAndSign(
signers: GenerateAndSignInput['signers'],
pathway: 'inapp' | 'documenso-template',
meta: AuditMeta,
options?: { dimensionUnit?: 'ft' | 'm' },
) {
if (pathway === 'documenso-template') {
return generateAndSignViaDocumensoTemplate(portId, context, meta);
return generateAndSignViaDocumensoTemplate(portId, context, meta, options);
}
if (!templateId) {
throw new ValidationError('templateId is required for inapp pathway');
}
return generateAndSignViaInApp(templateId, portId, context, signers, meta);
return generateAndSignViaInApp(templateId, portId, context, signers, meta, options);
}
async function generateAndSignViaInApp(
@@ -599,6 +603,7 @@ async function generateAndSignViaInApp(
context: GenerateInput,
signers: GenerateAndSignInput['signers'],
meta: AuditMeta,
options?: { dimensionUnit?: 'ft' | 'm' },
) {
const template = await getTemplateById(templateId, portId);
@@ -656,6 +661,7 @@ async function generateAndSignViaInApp(
portId,
context,
meta,
options,
);
// Fetch PDF bytes from the active storage backend to send to Documenso.
@@ -688,6 +694,7 @@ async function generateAndSignViaInApp(
.update(documents)
.set({
documensoId: documensoDoc.id,
documensoNumericId: documensoDoc.numericId,
status: 'sent',
updatedAt: new Date(),
})
@@ -721,6 +728,7 @@ async function generateAndSignViaDocumensoTemplate(
portId: string,
context: GenerateInput,
meta: AuditMeta,
options?: { dimensionUnit?: 'ft' | 'm' },
) {
if (!context.interestId) {
throw new ValidationError('interestId is required for documenso-template pathway');
@@ -734,21 +742,39 @@ async function generateAndSignViaDocumensoTemplate(
// platform to one Documenso instance per CRM process.
const docCfg = await getPortDocumensoConfig(portId);
const payload = buildDocumensoPayload(eoiContext, {
interestId: context.interestId,
clientRecipientId: docCfg.clientRecipientId,
developerRecipientId: docCfg.developerRecipientId,
approvalRecipientId: docCfg.approvalRecipientId,
developerName: signers.developer.name,
developerEmail: signers.developer.email,
approverName: signers.approver.name,
approverEmail: signers.approver.email,
// Prefer per-port post-signing redirect (typically marketing-site
// /sign/success on v2). Falls back to APP_URL on v1 / when unset.
redirectUrl: docCfg.redirectUrl ?? env.APP_URL,
// v2-only signing-order enforcement. v1 instances ignore this key.
...(docCfg.signingOrder ? { signingOrder: docCfg.signingOrder } : {}),
});
// v2 prefillFields-by-ID emission requires a field-name → field-ID map
// populated by the admin "Sync from Documenso" button. Absent (or partial)
// map → payload skips prefillFields and v2 accepts the legacy formValues
// shape via backward compat.
const { getEoiFieldMap } = await import('@/lib/services/documenso-template-sync.service');
const fieldMap = await getEoiFieldMap(portId);
// Pick which side of the yacht's stored dimensions ships to Documenso.
// The drawer's toggle drives this; if the caller omitted it, default to
// whichever unit the rep originally typed in (yacht.lengthUnit). Legacy
// yachts without a unit column default to 'ft'.
const dimensionUnit: 'ft' | 'm' = options?.dimensionUnit ?? eoiContext.yacht?.lengthUnit ?? 'ft';
const payload = buildDocumensoPayload(
eoiContext,
{
interestId: context.interestId,
clientRecipientId: docCfg.clientRecipientId,
developerRecipientId: docCfg.developerRecipientId,
approvalRecipientId: docCfg.approvalRecipientId,
developerName: signers.developer.name,
developerEmail: signers.developer.email,
approverName: signers.approver.name,
approverEmail: signers.approver.email,
// Prefer per-port post-signing redirect (typically marketing-site
// /sign/success on v2). Falls back to APP_URL on v1 / when unset.
redirectUrl: docCfg.redirectUrl ?? env.APP_URL,
// v2-only signing-order enforcement. v1 instances ignore this key.
...(docCfg.signingOrder ? { signingOrder: docCfg.signingOrder } : {}),
dimensionUnit,
},
fieldMap,
);
const documensoDoc = await documensoGenerateFromTemplate(
docCfg.eoiTemplateId,
@@ -768,11 +794,73 @@ async function generateAndSignViaDocumensoTemplate(
title: payload.title,
status: 'sent',
documensoId: documensoDoc.id,
documensoNumericId: documensoDoc.numericId,
isManualUpload: false,
createdBy: meta.userId,
})
.returning();
// Persist the per-recipient signer rows from Documenso's create response.
// Without these the EOI tab's "Signing progress" panel shows
// "No signers loaded" forever (the webhook handler only updates existing
// rows by token / email). Each row maps a Documenso recipient slot to
// a CRM document-signer record.
if (documensoDoc.recipients.length > 0) {
await db.insert(documentSigners).values(
documensoDoc.recipients.map((r) => {
// Strip the `(was: <email>)` suffix that `applyRecipientRedirect`
// bakes into recipient names when EMAIL_REDIRECT_TO is on. Without
// this, every downstream surface (email greeting, signing-progress
// card, document-detail page) leaks "Matt Ciaccio (was: matt@...)"
// into reps' faces. Display-only cleanup; the original email is
// still recoverable via the redirect helper.
const cleanName = (r.name || r.email)
.replace(/\s*\(was:[^)]*\)/i, '')
.replace(/\s*\(placeholder\)/i, '')
.replace(/\s*\(placeholder\b[^)]*\)/i, '')
.trim();
// signingOrder 1 with role SIGNER is always the CLIENT in our trio
// (Client → Developer → Approver). Without this special-case the
// role gets stored as 'signer' for the client too, and the email
// template's `isClient` branch wrongly tells the client "you're
// the next signer; the client has already signed."
const role =
r.role.toUpperCase() === 'SIGNER' && r.signingOrder === 1
? 'client'
: normalizeSignerRole(r.role);
return {
documentId: documentRecord!.id,
signerName: cleanName || r.email,
signerEmail: r.email,
signerRole: role,
signingOrder: r.signingOrder,
status: 'pending' as const,
signingUrl: r.signingUrl ?? null,
embeddedUrl: r.embeddedUrl ?? null,
signingToken: r.token ?? null,
// invitedAt deliberately left null at create time. The
// send-invitation route stamps it once the branded invite goes
// out. Pre-stamping would mis-label the signer card as
// "Invited just now" in manual send mode.
invitedAt: null,
};
}),
);
}
// Stamp the interest's EOI milestone so the Overview tab flips the
// "Generate EOI" prompt to the "EOI sent / awaiting signatures" state
// immediately. Cache-invalidation on the client picks the new shape up
// via the document-templates POST's onSuccess.
await db
.update(interests)
.set({
eoiDocStatus: 'sent',
dateEoiSent: new Date(),
updatedAt: new Date(),
})
.where(eq(interests.id, context.interestId));
void createAuditLog({
userId: meta.userId,
portId,
@@ -794,3 +882,20 @@ async function generateAndSignViaDocumensoTemplate(
return { document: documentRecord!, file: null };
}
/**
* Documenso recipient roles arrive as ALL-CAPS strings ('SIGNER' | 'APPROVER'
* | 'CC' | 'VIEWER'); the CRM's `document_signers.signer_role` column uses
* the lowercase domain vocabulary ('client' | 'developer' | 'approver' |
* 'cc' | 'viewer' | 'other'). Map them so the UI's progress panel renders
* the right label per row. SIGNER → developer is a safe default because
* the client slot is identified positionally elsewhere (signingOrder=1
* always).
*/
function normalizeSignerRole(documensoRole: string): string {
const r = documensoRole.toUpperCase();
if (r === 'APPROVER') return 'approver';
if (r === 'CC') return 'cc';
if (r === 'VIEWER') return 'viewer';
return 'signer';
}