fix(audit): post-review hardening across phases 0-7
15 of 17 findings from the consolidated audit (3 reviewer agents on the previously-shipped phase commits). Remaining two are nice-to-have follow-ups deferred. Critical (data integrity / security): - Public berths API: closed-deal junction rows no longer flip a berth to "Under Offer" - filter on `interests.outcome IS NULL` so won/ lost/cancelled don't pollute public-map status. Both list + single-mooring routes. - Recommender heat: cancelled outcomes now count as fall-throughs (SQL was `LIKE 'lost%'` which silently dropped them, leaving cancelled-only berths stuck in tier A). - Filesystem presignDownload returns an absolute URL (origin from APP_URL) so emailed download links resolve from external mail clients. - Magic-byte verification on the presigned-PUT path: both per-berth PDFs and brochures stream the first 5 bytes via the storage backend and reject + delete on `%PDF-` mismatch (was only enforced when the server saw the buffer; presign-PUT was wide open). - Replay-protection TTL aligned to the token's own expiry (was a fixed 30 min, but send-out tokens live 24 h). Floor 60 s, ceiling 25 days. - Brochures unique partial index on (port_id) WHERE is_default=true + 0032 migration. Closes the read-then-write race in the create/ update transactions. Important: - Recommender SQL: defense-in-depth `i.port_id = $portId` filter on the aggregates CTE. - berth-pdf service: per-berth pg_advisory_xact_lock around the version-number SELECT + insert. Storage key is now UUID-based so concurrent uploads can't collide on blob paths. Replaces `nextVersionNumber` with the tx-bound variant. - berth-pdf apply: rejects with ConflictError when parse_results contain a mooring-mismatch warning unless the caller passes `confirmMooringMismatch: true` (force-reconfirm gate was UI-only). - Send-out body: HTML-escape brochure filename in the download-link fallback (XSS guard). - parseDecimalWithUnit rejects negative numbers. - listClients DISTINCT ON for primary contact resolution: bounds contact-row count to ~2 per client. Defensive: - verifyProxyToken rejects NaN/Infinity expiries via Number.isFinite. - Replaced sql ANY() with inArray() in interest-berths. Tests: 1145 -> 1163 passing. Deferred: bulk-send rate limit (no bulk endpoint today), markdown italic regex breaking links with asterisks (cosmetic). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { and, count, desc, eq, ilike, inArray, isNull } from 'drizzle-orm';
|
||||
import { and, count, desc, eq, ilike, inArray, isNull, sql } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import {
|
||||
@@ -139,22 +139,29 @@ export async function listClients(portId: string, query: ListClientsInput) {
|
||||
),
|
||||
)
|
||||
.groupBy(interests.clientId),
|
||||
// Pull every contact row for the page; the per-client primary
|
||||
// resolution happens in the post-fetch loop below. Cheaper than
|
||||
// running a DISTINCT-ON query per channel and keeps the picker
|
||||
// logic (is_primary desc, then most recent created_at) in one
|
||||
// place.
|
||||
db
|
||||
.select({
|
||||
clientId: clientContacts.clientId,
|
||||
channel: clientContacts.channel,
|
||||
value: clientContacts.value,
|
||||
isPrimary: clientContacts.isPrimary,
|
||||
createdAt: clientContacts.createdAt,
|
||||
})
|
||||
.from(clientContacts)
|
||||
.where(inArray(clientContacts.clientId, ids))
|
||||
.orderBy(desc(clientContacts.isPrimary), desc(clientContacts.createdAt)),
|
||||
// Pull at most ONE contact per (client_id, channel) for the page.
|
||||
// DISTINCT ON sorted by `is_primary DESC, created_at DESC` keeps
|
||||
// the picker logic identical to the in-memory version it replaced
|
||||
// while bounding the row count to ~2 per client (one email, one
|
||||
// phone) regardless of how many contacts the client has.
|
||||
db.execute<{
|
||||
clientId: string;
|
||||
channel: string;
|
||||
value: string;
|
||||
isPrimary: boolean;
|
||||
createdAt: Date;
|
||||
}>(sql`
|
||||
SELECT DISTINCT ON (client_id, channel)
|
||||
client_id AS "clientId",
|
||||
channel,
|
||||
value,
|
||||
is_primary AS "isPrimary",
|
||||
created_at AS "createdAt"
|
||||
FROM client_contacts
|
||||
WHERE client_id = ANY(${ids})
|
||||
AND channel IN ('email', 'phone')
|
||||
ORDER BY client_id, channel, is_primary DESC, created_at DESC
|
||||
`),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -172,16 +179,23 @@ export async function listClients(portId: string, query: ListClientsInput) {
|
||||
}
|
||||
}
|
||||
|
||||
// Pick the per-client primary (or, failing that, most-recent) email
|
||||
// and phone. contactRows is pre-sorted is_primary desc, created_at desc.
|
||||
// Pick the per-client primary email + phone. The SQL DISTINCT ON
|
||||
// returns at most one row per (clientId, channel); the result is
|
||||
// already the picker's "is_primary desc, created_at desc" choice.
|
||||
const primaryEmailMap = new Map<string, string>();
|
||||
const primaryPhoneMap = new Map<string, string>();
|
||||
for (const c of contactRows) {
|
||||
if (c.channel === 'email' && !primaryEmailMap.has(c.clientId)) {
|
||||
primaryEmailMap.set(c.clientId, c.value);
|
||||
} else if (c.channel === 'phone' && !primaryPhoneMap.has(c.clientId)) {
|
||||
primaryPhoneMap.set(c.clientId, c.value);
|
||||
}
|
||||
type ContactRow = {
|
||||
clientId: string;
|
||||
channel: string;
|
||||
value: string;
|
||||
isPrimary: boolean;
|
||||
createdAt: Date;
|
||||
};
|
||||
const contactRowList: ContactRow[] =
|
||||
(contactRows as { rows?: ContactRow[] }).rows ?? (contactRows as unknown as ContactRow[]);
|
||||
for (const c of contactRowList) {
|
||||
if (c.channel === 'email') primaryEmailMap.set(c.clientId, c.value);
|
||||
else if (c.channel === 'phone') primaryPhoneMap.set(c.clientId, c.value);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user