fix(audit): backlog sweep — partial archived indexes, custom-fields per-entity gate, polish
Some checks failed
Build & Push Docker Images / lint (push) Successful in 1m37s
Build & Push Docker Images / build-and-push (push) Failing after 24s

Wave through the 2026-05-07 backlog of small/concrete audit-final-deferred
items (deferring the Documenso Phases 2-7 build and items needing design
decisions or live external instances).

DB schema:
- Migration 0046 converts 5 composite (port_id, archived_at) indexes to
  partial WHERE archived_at IS NULL — clients, interests, yachts, and
  both residential tables. Smaller, faster planner choice for the
  dominant list-query shape.

Multi-tenant isolation:
- document_sends now verifies recipient.interestId belongs to the port
  before landing on the audit row (the surrounding clientId check was
  already port-scoped; interestId pollution was the gap).

Routes / API:
- /api/v1/custom-fields/[entityId] requires entityType query param and
  gates on the matching resource permission (clients/interests/berths/
  yachts/companies). Fixes the cross-resource gap where a user with
  clients.view could read company custom-field values.
- Admin user list trash button wrapped in PermissionGate (edit was
  already gated; remove was not).

Service polish:
- berth-recommender accepts string-shaped JSONB booleans
  ('true'/'false') so admin UIs that wrap values as strings don't
  silently fall through to defaults.
- expense-pdf renderReceiptHeader anchors all text positions to a
  captured baseY rather than reading mutating doc.y after rect+stroke.
  Headers no longer drift on the first receipt page after a soft page
  break.
- berth-pdf apply: collect non-finite numeric coercion drops + warn-log
  them so partial silent drops are observable (was invisible because
  the no-fields-supplied check only fires when ALL drop).
- Storage cache fingerprint comment documenting the encrypted-secret
  invariant + the explicit invalidation hook.

UI polish:
- invoice-detail typed: replaced two `any` casts with a proper
  InvoiceDetailData / LineItem / LinkedExpense interface set.
- YachtForm now accepts initialOwner prop. Wired through:
  - client-yachts-tab passes { type: 'client', id: clientId }
  - interest-form passes { type: 'client', id: selectedClientId }
- Interest-form yacht picker now includes company-owned yachts where
  the selected client is a member (fetches client.companies and feeds
  YachtPicker an array filter). Plus an inline "Add new" button that
  opens YachtForm pre-bound to the client.
- YachtPicker accepts ownerFilter as single OR array for "match any"
  semantics.

BACKLOG.md updated with what landed vs what's still deferred (and why
each deferred item is genuinely larger than this push warrants).

Tests: 1185/1185 vitest, tsc clean.
This commit is contained in:
2026-05-07 21:45:42 +02:00
parent 5c8c12ba1f
commit 60365dc3de
19 changed files with 527 additions and 125 deletions

View File

@@ -0,0 +1,32 @@
-- Convert composite (port_id, archived_at) archived indexes to partial
-- indexes WHERE archived_at IS NULL. Every list query in the codebase that
-- hits archived_at filters on `archived_at IS NULL` (verified in
-- clients.service / interests.service / search.service / residential.service
-- / yachts.service). The composite index always carries the archived rows
-- as dead weight; the partial index is smaller, has a higher cache hit rate,
-- and lets the planner skip the index entirely when the predicate is absent.
-- clients
DROP INDEX IF EXISTS "idx_clients_archived";
CREATE INDEX IF NOT EXISTS "idx_clients_archived" ON "clients" ("port_id")
WHERE "archived_at" IS NULL;
-- interests
DROP INDEX IF EXISTS "idx_interests_archived";
CREATE INDEX IF NOT EXISTS "idx_interests_archived" ON "interests" ("port_id")
WHERE "archived_at" IS NULL;
-- yachts
DROP INDEX IF EXISTS "idx_yachts_archived";
CREATE INDEX IF NOT EXISTS "idx_yachts_archived" ON "yachts" ("port_id")
WHERE "archived_at" IS NULL;
-- residential clients
DROP INDEX IF EXISTS "idx_residential_clients_archived";
CREATE INDEX IF NOT EXISTS "idx_residential_clients_archived" ON "residential_clients" ("port_id")
WHERE "archived_at" IS NULL;
-- residential interests
DROP INDEX IF EXISTS "idx_residential_interests_archived";
CREATE INDEX IF NOT EXISTS "idx_residential_interests_archived" ON "residential_interests" ("port_id")
WHERE "archived_at" IS NULL;

View File

@@ -57,7 +57,9 @@ export const clients = pgTable(
(table) => [
index('idx_clients_port').on(table.portId),
index('idx_clients_name').on(table.portId, table.fullName),
index('idx_clients_archived').on(table.portId, table.archivedAt),
index('idx_clients_archived')
.on(table.portId)
.where(sql`${table.archivedAt} IS NULL`),
index('idx_clients_nationality_iso').on(table.nationalityIso),
index('idx_clients_merged_into').on(table.mergedIntoClientId),
],

View File

@@ -72,7 +72,9 @@ export const interests = pgTable(
index('idx_interests_client').on(table.clientId),
index('idx_interests_yacht').on(table.yachtId),
index('idx_interests_stage').on(table.portId, table.pipelineStage),
index('idx_interests_archived').on(table.portId, table.archivedAt),
index('idx_interests_archived')
.on(table.portId)
.where(sql`${table.archivedAt} IS NULL`),
index('idx_interests_outcome').on(table.portId, table.outcome),
],
);

View File

@@ -1,4 +1,5 @@
import { boolean, pgTable, text, timestamp, index } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';
import { ports } from './ports';
@@ -50,7 +51,9 @@ export const residentialClients = pgTable(
(table) => [
index('idx_residential_clients_port').on(table.portId),
index('idx_residential_clients_email').on(table.email),
index('idx_residential_clients_archived').on(table.portId, table.archivedAt),
index('idx_residential_clients_archived')
.on(table.portId)
.where(sql`${table.archivedAt} IS NULL`),
],
);
@@ -98,7 +101,9 @@ export const residentialInterests = pgTable(
index('idx_residential_interests_client').on(table.residentialClientId),
index('idx_residential_interests_stage').on(table.portId, table.pipelineStage),
index('idx_residential_interests_assigned').on(table.assignedTo),
index('idx_residential_interests_archived').on(table.portId, table.archivedAt),
index('idx_residential_interests_archived')
.on(table.portId)
.where(sql`${table.archivedAt} IS NULL`),
],
);

View File

@@ -51,7 +51,9 @@ export const yachts = pgTable(
table.currentOwnerId,
),
index('idx_yachts_name').on(table.portId, table.name),
index('idx_yachts_archived').on(table.portId, table.archivedAt),
index('idx_yachts_archived')
.on(table.portId)
.where(sql`${table.archivedAt} IS NULL`),
],
);

View File

@@ -479,6 +479,11 @@ export async function applyParseResults(
const update: Record<string, unknown> = {};
const applied: Array<keyof ExtractedBerthFields> = [];
// Capture keys whose values were supplied but couldn't be coerced
// (e.g. a numeric column receiving a non-finite or non-numeric value).
// Without this, partial silent drops are invisible because the
// "no appliable fields supplied" check only fires when EVERY key drops.
const dropped: Array<{ key: keyof ExtractedBerthFields; reason: string }> = [];
for (const key of APPLIABLE_FIELDS) {
const value = fieldsToApply[key];
if (value === undefined) continue;
@@ -489,7 +494,10 @@ export async function applyParseResults(
}
if (NUMERIC_FIELDS.has(key)) {
const n = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(n)) continue;
if (!Number.isFinite(n)) {
dropped.push({ key, reason: `non-finite numeric (${typeof value}: ${String(value)})` });
continue;
}
// numeric columns expect strings to preserve precision.
update[key] = String(n);
} else {
@@ -500,6 +508,12 @@ export async function applyParseResults(
if (applied.length === 0) {
throw new ValidationError('No appliable fields supplied.');
}
if (dropped.length > 0) {
logger.warn(
{ berthId, versionId, dropped },
'Berth PDF apply: silently dropped fields that failed type coercion',
);
}
update.updatedAt = new Date();
await db.transaction(async (tx) => {

View File

@@ -114,7 +114,18 @@ export async function loadRecommenderSettings(portId: string): Promise<Recommend
}
return null;
};
const asBool = (v: unknown): boolean | null => (typeof v === 'boolean' ? v : null);
const asBool = (v: unknown): boolean | null => {
if (typeof v === 'boolean') return v;
// Some admin UIs (or older settings rows) persist booleans as the
// strings "true" / "false" inside the JSONB blob. Without this
// tolerant parse, a per-port override quietly falls through to the
// default and the admin's tuning has no effect.
if (typeof v === 'string') {
if (v === 'true') return true;
if (v === 'false') return false;
}
return null;
};
const asPolicy = (v: unknown): RecommenderSettings['fallthroughPolicy'] | null => {
if (v === 'immediate_with_heat' || v === 'cooldown' || v === 'never_auto_recommend') {
return v;

View File

@@ -38,6 +38,7 @@ import {
berthPdfVersions,
clients,
clientContacts,
interests,
ports,
} from '@/lib/db/schema';
import type { DocumentSend } from '@/lib/db/schema';
@@ -225,6 +226,21 @@ async function resolveRecipientEmail(
return primary.value;
}
/**
* Verify a caller-supplied `interestId` belongs to the authenticated port
* before it lands on the `document_sends` audit row. Without this, an
* attacker who knows a foreign-port interest UUID can pollute another
* tenant's audit history (the surrounding `clientId` lookup is already
* port-scoped, so data isn't exposed — but the audit trail would be).
*/
async function assertInterestInPort(portId: string, interestId: string): Promise<void> {
const row = await db.query.interests.findFirst({
where: and(eq(interests.id, interestId), eq(interests.portId, portId)),
columns: { id: true },
});
if (!row) throw new NotFoundError('Interest');
}
async function checkSendRateLimit(portId: string, userId: string): Promise<void> {
// Per-(port, user) so a multi-port rep can't be DoS'd by another tenant
// burning their global cap. Audit caught this — the original
@@ -375,6 +391,9 @@ export async function sendBerthPdf(input: SendBerthPdfInput): Promise<SendResult
// Rate-limit AFTER validation so a typo'd recipient or missing-PDF rep
// doesn't burn a slot on a send that would have failed anyway.
const recipientEmail = await resolveRecipientEmail(input.portId, input.recipient);
if (input.recipient.interestId) {
await assertInterestInPort(input.portId, input.recipient.interestId);
}
// Resolve berth + active version.
const berth = await db.query.berths.findFirst({
@@ -444,6 +463,9 @@ export async function sendBerthPdf(input: SendBerthPdfInput): Promise<SendResult
export async function sendBrochure(input: SendBrochureInput): Promise<SendResult> {
// Rate-limit AFTER validation (audit finding); typos shouldn't burn slots.
const recipientEmail = await resolveRecipientEmail(input.portId, input.recipient);
if (input.recipient.interestId) {
await assertInterestInPort(input.portId, input.recipient.interestId);
}
// Resolve brochure + most-recent version.
let brochureRow;

View File

@@ -913,8 +913,15 @@ function renderReceiptHeader(
) {
const margin = 60;
const headerH = 90;
// Capture the header's top edge BEFORE drawing — every subsequent text
// call below uses pdfkit's auto-flow which advances `doc.y`. Using
// `doc.y - headerH + 10` after the rect+stroke block computes against
// the post-rect position and only happens to work because pdfkit's
// text-after-rect hasn't moved y yet. On the first receipt page after
// a soft page break that assumption breaks and the header misaligns.
const baseY = doc.y;
doc
.rect(margin, doc.y, doc.page.width - margin * 2, headerH)
.rect(margin, baseY, doc.page.width - margin * 2, headerH)
.fillColor('#f8f9fa')
.fill()
.strokeColor('#dee2e6')
@@ -924,14 +931,14 @@ function renderReceiptHeader(
doc
.fontSize(14)
.font('Helvetica-Bold')
.text(`Receipt ${index} of ${total}`, margin + 10, doc.y - headerH + 10);
.text(`Receipt ${index} of ${total}`, margin + 10, baseY + 10);
doc
.fontSize(11)
.font('Helvetica-Bold')
.text(
`${expense.establishmentName ?? '—'} ${sym}${expense.amountTarget.toFixed(2)}`,
margin + 10,
doc.y + 4,
baseY + 36,
);
doc
.fontSize(9)
@@ -940,14 +947,14 @@ function renderReceiptHeader(
.text(
`Date: ${expense.expenseDate.toISOString().slice(0, 10)} · Payer: ${expense.payer ?? '—'} · Category: ${expense.category ?? '—'} · File: ${file.filename}`,
margin + 10,
doc.y + 4,
baseY + 56,
{ width: doc.page.width - margin * 2 - 20 },
);
doc.fillColor('#000000');
// Reset cursor to below the header block.
const margin2 = 60;
doc.y = doc.y + Math.max(headerH - 50, 20);
void margin2;
// Reset cursor to below the header block, anchored to the captured
// baseline so it's independent of however many auto-flowed text runs
// occurred above.
doc.y = baseY + headerH + 8;
}
function addReceiptErrorPage(

View File

@@ -155,6 +155,16 @@ async function loadStorageConfig(): Promise<StorageConfigSnapshot> {
};
}
/**
* The fingerprint includes encrypted-secret material because rotating the
* secret should invalidate the cached client. After a key rotation the
* settings-write hook calls `resetStorageBackendCache()` explicitly, so
* this comparison is a defense-in-depth backstop rather than the primary
* invalidation path. If you ever change `loadStorageConfig` to read
* additional sensitive material, make sure the rotation flow keeps
* resetting the cache — relying on fingerprint diff alone means the old
* client is held in memory until the next mismatch.
*/
function fingerprint(cfg: StorageConfigSnapshot): string {
return JSON.stringify(cfg);
}