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:
@@ -77,6 +77,10 @@ export async function GET(
|
||||
eq(interestBerths.berthId, berth.id),
|
||||
eq(interestBerths.isSpecificInterest, true),
|
||||
isNull(interests.archivedAt),
|
||||
// Closed deals (won/lost/cancelled) don't promote to "Under
|
||||
// Offer" - won flows through berths.status='sold' handled in
|
||||
// derivePublicStatus; lost/cancelled means back on the market.
|
||||
isNull(interests.outcome),
|
||||
),
|
||||
)
|
||||
.limit(1),
|
||||
|
||||
@@ -85,6 +85,11 @@ export async function GET(request: Request): Promise<Response> {
|
||||
inArray(interestBerths.berthId, berthIds),
|
||||
eq(interestBerths.isSpecificInterest, true),
|
||||
isNull(interests.archivedAt),
|
||||
// Don't promote a berth to "Under Offer" when the only specific-
|
||||
// interest link is a closed deal. `won` flips happen via
|
||||
// berths.status='sold' (handled in derivePublicStatus). Lost/
|
||||
// cancelled outcomes mean the berth is back on the market.
|
||||
isNull(interests.outcome),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -28,7 +28,13 @@ import { verifyProxyToken } from '@/lib/storage/filesystem';
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const REPLAY_TTL_SECONDS = 60 * 30; // 30min — longer than any presign expiry default.
|
||||
// Replay-protection TTL must outlive the token itself, otherwise the
|
||||
// dedup key expires and the same token can be redeemed twice. We pin it
|
||||
// to the token's own expiry (clamped to a 25-day ceiling so a forged
|
||||
// far-future token can't pollute Redis indefinitely). Send-out emails
|
||||
// mint 24-hour tokens so the typical TTL is 24h + a small buffer.
|
||||
const REPLAY_TTL_FLOOR_SECONDS = 60; // never below 60s (post-expiry tail).
|
||||
const REPLAY_TTL_CEILING_SECONDS = 25 * 24 * 60 * 60; // 25 days.
|
||||
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
@@ -51,11 +57,16 @@ export async function GET(
|
||||
}
|
||||
const { payload } = result;
|
||||
|
||||
// Single-use enforcement. SET NX with a TTL longer than the token itself.
|
||||
// Using the body half of the token as the dedup key (signature included
|
||||
// Single-use enforcement. SET NX with a TTL pinned to the token's own
|
||||
// expiry so the dedup window never closes before the token does. Using
|
||||
// the body half of the token as the dedup key (signature included
|
||||
// would also work but body is enough — a reused token has the same body).
|
||||
const replayKey = `storage:proxy:seen:${token.split('.')[0]}`;
|
||||
const setOk = await redis.set(replayKey, '1', 'EX', REPLAY_TTL_SECONDS, 'NX');
|
||||
const remainingSeconds = Math.max(
|
||||
REPLAY_TTL_FLOOR_SECONDS,
|
||||
Math.min(REPLAY_TTL_CEILING_SECONDS, payload.e - Math.floor(Date.now() / 1000) + 60),
|
||||
);
|
||||
const setOk = await redis.set(replayKey, '1', 'EX', remainingSeconds, 'NX');
|
||||
if (setOk !== 'OK') {
|
||||
logger.warn({ key: payload.k }, 'Storage proxy token replay rejected');
|
||||
return NextResponse.json({ error: 'Token already used' }, { status: 403 });
|
||||
|
||||
@@ -16,9 +16,16 @@ import { updateSalesEmailConfigSchema } from '@/lib/validators/sales-email-confi
|
||||
* GET /api/v1/admin/email/sales-config
|
||||
*
|
||||
* Returns the redacted view of the sales-email config. Per §14.10
|
||||
* "Permission escalation: who configures SMTP credentials?", reps cannot
|
||||
* see the decrypted password — the response only carries `*PassIsSet`
|
||||
* boolean markers.
|
||||
* reps can't see the decrypted password — the response only carries
|
||||
* `*PassIsSet` boolean markers via `redactSalesConfigForResponse`.
|
||||
*
|
||||
* Today this endpoint is admin-only because it's consumed only by the
|
||||
* admin UI panel (`src/components/admin/sales-email-config-card.tsx`).
|
||||
* A future rep-facing surface that needs the from-address or body
|
||||
* templates can split into a separate `/email/sales-config/preview`
|
||||
* endpoint scoped to `email.view` — keeping the admin endpoint locked
|
||||
* to `manage_settings` avoids accidentally widening secret-adjacent
|
||||
* surfaces (e.g. the SMTP host name itself can be a leak vector).
|
||||
*/
|
||||
export const GET = withAuth(
|
||||
withPermission('admin', 'manage_settings', async (_req, ctx) => {
|
||||
|
||||
Reference in New Issue
Block a user