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,9 @@ import { and, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { user, userProfiles } from '@/lib/db/schema/users';
import type { EoiContext } from '@/lib/services/eoi-context';
import { readSetting, SETTING_KEYS } from '@/lib/services/port-config';
export interface DocumensoTemplatePayload {
title: string;
@@ -20,6 +22,10 @@ export interface DocumensoTemplatePayload {
*/
signingOrder?: 'PARALLEL' | 'SEQUENTIAL';
};
/**
* Legacy v1 path: form-field values keyed by field NAME. Documenso v1.13.x
* accepts only this shape. v2 instances accept it via backward compat too.
*/
formValues: {
Name: string;
Email: string;
@@ -41,13 +47,37 @@ export interface DocumensoTemplatePayload {
Lease_10: boolean;
Purchase: boolean;
};
/**
* v2-native path: prefill values keyed by field ID. Generated by mapping
* each `formValues` entry through the cached `documenso_eoi_field_map`
* (name → ID) discovered via the admin's "Sync from Documenso" button.
* v1 instances ignore this field; v2 instances accept either prefillFields
* OR formValues but prefillFields-by-ID is the canonical modern path.
*/
prefillFields?: Array<{
id: number;
type: 'text' | 'number' | 'date' | 'checkbox' | 'dropdown';
value: string;
}>;
recipients: Array<{
id: number;
name: string;
email: string;
role: 'SIGNER' | 'APPROVER';
role: 'SIGNER' | 'APPROVER' | 'CC' | 'VIEWER';
signingOrder: number;
}>;
/**
* Extra recipients beyond the canonical client + developer + approver trio.
* Used by the "send a copy to my manager" workflow: pass CC slots here and
* they'll be appended to the recipients array at send time.
*/
extraRecipients?: Array<{
id: number;
name: string;
email: string;
role: 'CC' | 'VIEWER';
signingOrder?: number;
}>;
}
export interface DocumensoPayloadOptions {
@@ -69,12 +99,28 @@ export interface DocumensoPayloadOptions {
* Set via per-port `documenso_signing_order` system_settings key.
*/
signingOrder?: 'PARALLEL' | 'SEQUENTIAL';
/**
* Optional extra recipients beyond the canonical client+developer+approver
* trio. Used by the "send a copy to my manager" workflow. CC = receives a
* copy of the signed PDF; VIEWER = can view but not sign. Slot IDs must
* exist on the Documenso template (CRM operator adds them in the template
* editor first). v2-only on v2 instances; v1 ignores unknown roles.
*/
extraRecipients?: Array<{
id: number;
name: string;
email: string;
role: 'CC' | 'VIEWER';
signingOrder?: number;
}>;
/**
* Which side of the yacht's stored dimensions (ft|m) flows into the EOI's
* Length/Width/Draft formValues. Defaults to 'ft' when omitted for legacy
* call sites; the EOI-generate drawer always supplies the rep's choice.
*/
dimensionUnit?: 'ft' | 'm';
}
const DEFAULT_DEVELOPER_NAME = 'David Mizrahi';
const DEFAULT_DEVELOPER_EMAIL = 'dm@portnimara.com';
const DEFAULT_APPROVER_NAME = 'Abbie May';
const DEFAULT_APPROVER_EMAIL = 'sales@portnimara.com';
const DEFAULT_REDIRECT_URL = 'https://portnimara.com';
export interface EoiSignerConfig {
@@ -82,9 +128,9 @@ export interface EoiSignerConfig {
approver: { name: string; email: string };
}
const DEFAULT_EOI_SIGNERS: EoiSignerConfig = {
developer: { name: DEFAULT_DEVELOPER_NAME, email: DEFAULT_DEVELOPER_EMAIL },
approver: { name: DEFAULT_APPROVER_NAME, email: DEFAULT_APPROVER_EMAIL },
const EMPTY_SIGNERS: EoiSignerConfig = {
developer: { name: '', email: '' },
approver: { name: '', email: '' },
};
function isSignerEntry(v: unknown): v is { name: string; email: string } {
@@ -98,27 +144,89 @@ function isSignerEntry(v: unknown): v is { name: string; email: string } {
);
}
/** Read the per-port `eoi_signers` setting, fall back to legacy hardcoded
* defaults if missing or malformed. The fallback exists to keep older
* ports working until an admin saves the setting; once saved, the DB row
* always wins. */
/** Look up `{name, email}` for a CRM user id by joining `userProfiles`
* (display name) + `user` (auth email). Returns nulls on miss. */
async function resolveCrmUser(
userId: string | null,
): Promise<{ name: string; email: string } | null> {
if (!userId) return null;
const [row] = await db
.select({
displayName: userProfiles.displayName,
email: user.email,
})
.from(user)
.leftJoin(userProfiles, eq(userProfiles.userId, user.id))
.where(eq(user.id, userId))
.limit(1);
if (!row || !row.email) return null;
return { name: row.displayName ?? row.email, email: row.email };
}
/**
* Resolve the developer + approver name/email for the EOI signing trio.
*
* Priority chain per slot (highest → lowest):
* 1. Linked CRM user (`documenso_<role>_user_id`) — recommended path
* because "the person on this slot" changes via a CRM admin re-link,
* not a Documenso template edit. The display name comes from
* `userProfiles.displayName`, the email from `user.email`.
* 2. Free-text overrides (`documenso_<role>_name` +
* `documenso_<role>_email`) — for ports where the signer isn't a
* CRM-platform user (e.g. external counsel).
* 3. Legacy `eoi_signers` JSON blob — kept for backward compat with
* ports that haven't migrated to the registry-driven settings yet.
* 4. Empty strings — let the Documenso template's stored values win.
*
* Either slot can resolve via a different tier than the other.
*/
export async function getPortEoiSigners(portId: string): Promise<EoiSignerConfig> {
const row = await db.query.systemSettings.findFirst({
where: and(eq(systemSettings.key, 'eoi_signers'), eq(systemSettings.portId, portId)),
});
const value = row?.value as Record<string, unknown> | undefined;
if (value && isSignerEntry(value.developer) && isSignerEntry(value.approver)) {
return {
developer: value.developer,
approver: value.approver,
};
}
return DEFAULT_EOI_SIGNERS;
const [developerUserId, approverUserId, devName, devEmail, apprName, apprEmail, legacyRow] =
await Promise.all([
readSetting<string>(SETTING_KEYS.documensoDeveloperUserId, portId),
readSetting<string>(SETTING_KEYS.documensoApproverUserId, portId),
readSetting<string>(SETTING_KEYS.documensoDeveloperName, portId),
readSetting<string>(SETTING_KEYS.documensoDeveloperEmail, portId),
readSetting<string>(SETTING_KEYS.documensoApproverName, portId),
readSetting<string>(SETTING_KEYS.documensoApproverEmail, portId),
db.query.systemSettings.findFirst({
where: and(eq(systemSettings.key, 'eoi_signers'), eq(systemSettings.portId, portId)),
}),
]);
const legacyValue = legacyRow?.value as Record<string, unknown> | undefined;
const legacyDev =
legacyValue && isSignerEntry(legacyValue.developer) ? legacyValue.developer : null;
const legacyApr =
legacyValue && isSignerEntry(legacyValue.approver) ? legacyValue.approver : null;
const [developerFromUser, approverFromUser] = await Promise.all([
resolveCrmUser(developerUserId ?? null),
resolveCrmUser(approverUserId ?? null),
]);
const developer =
developerFromUser ??
(devName && devEmail ? { name: devName, email: devEmail } : null) ??
legacyDev ??
EMPTY_SIGNERS.developer;
const approver =
approverFromUser ??
(apprName && apprEmail ? { name: apprName, email: apprEmail } : null) ??
legacyApr ??
EMPTY_SIGNERS.approver;
return { developer, approver };
}
function formatAddress(address: EoiContext['client']['address']): string {
if (!address) return '';
return [address.street, address.city, address.country].filter(Boolean).join(', ');
// Shortest comprehensive format so the line fits the EOI's Address field:
// street, city, REGION (ISO-3166-2 suffix), postal, COUNTRY (alpha-2).
return [address.street, address.city, address.subdivision, address.postalCode, address.countryIso]
.filter(Boolean)
.join(', ');
}
function buildMessage(context: EoiContext): string {
@@ -135,9 +243,74 @@ function buildMessage(context: EoiContext): string {
export function buildDocumensoPayload(
context: EoiContext,
options: DocumensoPayloadOptions,
/**
* Cached field name → ID map from the per-port `documenso_eoi_field_map`
* setting (populated by the admin "Sync from Documenso" button). When
* provided, the payload also emits `prefillFields` keyed by ID — required
* by v2's /template/use. v1 instances ignore this field; v2 instances
* accept either prefillFields OR the legacy formValues shape.
*/
fieldMap?: Record<string, number> | null,
): DocumensoTemplatePayload {
// Honour the rep's unit choice from the EOI drawer's toggle. Defaults to
// 'ft' for legacy call sites that don't pass `dimensionUnit`; new code
// paths (generateAndSign + the drawer) always set it explicitly.
// Append the unit suffix to every dimension value so the rendered EOI
// reads "45 ft" / "13.7 m" rather than the bare number — the original
// form field doesn't tell signers which unit they're looking at.
const dimUnit: 'ft' | 'm' = options.dimensionUnit ?? 'ft';
const yachtLength = dimUnit === 'ft' ? context.yacht?.lengthFt : context.yacht?.lengthM;
const yachtWidth = dimUnit === 'ft' ? context.yacht?.widthFt : context.yacht?.widthM;
const yachtDraft = dimUnit === 'ft' ? context.yacht?.draftFt : context.yacht?.draftM;
const withUnit = (v: string | null | undefined): string =>
v && String(v).trim() ? `${String(v).trim()} ${dimUnit}` : '';
const formValues = {
Name: context.client.fullName,
Email: context.client.primaryEmail ?? '',
Address: formatAddress(context.client.address),
// Yacht + berth are optional EOI fields; when not linked, render as
// empty strings so the corresponding template inputs stay blank.
'Yacht Name': context.yacht?.name ?? '',
Length: withUnit(yachtLength),
Width: withUnit(yachtWidth),
Draft: withUnit(yachtDraft),
// formatBerthRange(['A1']) === 'A1' — so single-berth EOIs render
// identically to the legacy primary-only flow; multi-berth EOIs
// now actually show the full range instead of just the primary
// mooring.
'Berth Number': context.eoiBerthRange || (context.berth?.mooringNumber ?? ''),
Lease_10: false,
Purchase: true,
} as const;
// v2's prefillFields-by-ID emission. Map every formValue entry through the
// cached field map; skip entries that aren't in the map (template doesn't
// have that field, which is fine — Documenso silently drops unknown ones
// in v1 too).
const prefillFields = fieldMap
? Object.entries(formValues)
.map(([label, value]) => {
const fieldId = fieldMap[label];
if (fieldId == null) return null;
const isBoolean = typeof value === 'boolean';
return {
id: fieldId,
type: isBoolean ? ('checkbox' as const) : ('text' as const),
value: String(value),
};
})
.filter((x): x is { id: number; type: 'text' | 'checkbox'; value: string } => x !== null)
: undefined;
// Title format: "<full name>-EOI-NDA[-<berth range>]". When the EOI is
// tied to one or more berths, append the formatted range so the doc
// identifies the deal at a glance in lists and Documenso dashboards.
const berthSuffix = context.eoiBerthRange || context.berth?.mooringNumber || '';
return {
title: `${context.client.fullName}-EOI-NDA`,
title: berthSuffix
? `${context.client.fullName}-EOI-NDA-${berthSuffix}`
: `${context.client.fullName}-EOI-NDA`,
externalId: `loi-${options.interestId}`,
meta: {
message: buildMessage(context),
@@ -146,24 +319,14 @@ export function buildDocumensoPayload(
distributionMethod: 'NONE',
...(options.signingOrder ? { signingOrder: options.signingOrder } : {}),
},
formValues: {
Name: context.client.fullName,
Email: context.client.primaryEmail ?? '',
Address: formatAddress(context.client.address),
// Yacht + berth are optional EOI fields; when not linked, render as
// empty strings so the corresponding template inputs stay blank.
'Yacht Name': context.yacht?.name ?? '',
Length: context.yacht?.lengthFt ?? '',
Width: context.yacht?.widthFt ?? '',
Draft: context.yacht?.draftFt ?? '',
// formatBerthRange(['A1']) === 'A1' — so single-berth EOIs render
// identically to the legacy primary-only flow; multi-berth EOIs
// now actually show the full range instead of just the primary
// mooring.
'Berth Number': context.eoiBerthRange || (context.berth?.mooringNumber ?? ''),
Lease_10: false,
Purchase: true,
},
formValues,
...(prefillFields && prefillFields.length > 0 ? { prefillFields } : {}),
// Per Documenso v2's /template/use schema, `email` and `name` accept "" as
// a sentinel meaning "use the value baked into the template recipient".
// So when an admin leaves the developer/approver name/email blank in our
// admin settings, we pass "" rather than a hardcoded fallback — Documenso
// then takes the email/name set on the template itself. A non-empty
// admin value still wins (overrides the template at send time).
recipients: [
{
id: options.clientRecipientId,
@@ -174,18 +337,29 @@ export function buildDocumensoPayload(
},
{
id: options.developerRecipientId,
name: options.developerName ?? DEFAULT_DEVELOPER_NAME,
email: options.developerEmail ?? DEFAULT_DEVELOPER_EMAIL,
name: options.developerName ?? '',
email: options.developerEmail ?? '',
role: 'SIGNER',
signingOrder: 2,
},
{
id: options.approvalRecipientId,
name: options.approverName ?? DEFAULT_APPROVER_NAME,
email: options.approverEmail ?? DEFAULT_APPROVER_EMAIL,
name: options.approverName ?? '',
email: options.approverEmail ?? '',
role: 'APPROVER',
signingOrder: 3,
},
// Append CC / VIEWER slots after the canonical trio so their signing
// order doesn't collide with 1/2/3. Documenso doesn't require
// signingOrder uniqueness across non-signing roles but we still hand
// out monotonic numbers (4, 5, …) for predictability.
...(options.extraRecipients ?? []).map((extra, idx) => ({
id: extra.id,
name: extra.name,
email: extra.email,
role: extra.role,
signingOrder: extra.signingOrder ?? 4 + idx,
})),
],
};
}