fix(audit-v2): platform-wide post-merge hardening across 5 domains

Five-domain audit (security, routes, DB, integrations, UI/UX) ran after
the cf37d09 merge. Critical + high-impact items landed here; deferred
medium/low items indexed in docs/audit-final-deferred.md (now organised
into a "Audit-final v2" section).

Security:
- Storage proxy tokens now bind to op (`'get'` vs `'put'`). A long-lived
  download URL minted by `presignDownload` for an emailed brochure can no
  longer be replayed against the proxy PUT to overwrite the original
  storage object. `verifyProxyToken` requires `expectedOp` and rejects
  mismatches; legacy tokens missing `op` fail-closed. Regression tests
  added.
- Markdown email merge values are now markdown-escaped (`[`, `]`, `(`,
  `)`, `*`, `_`, `\`, backticks, braces) before substitution into the
  rep-authored body. A malicious value like `[click here](https://evil)`
  stored in `client.fullName` no longer survives `escapeHtml` to render
  as a real `<a href>` in the outbound email. Phishing-via-merge-field
  closed; regression tests added.
- Middleware now performs an Origin/Referer check on
  POST/PUT/PATCH/DELETE to `/api/v1/**`. Defense-in-depth on top of
  better-auth's SameSite=Lax cookie. Webhooks/public/auth/portal routes
  exempt as they don't carry the session cookie.

Routes:
- Template management routes were calling `withPermission('documents',
  'manage', ...)` — but `documents` doesn't have a `manage` action. The
  registry has `document_templates.manage`. Every non-superadmin was
  getting 403'd on the seven template endpoints. Fixed across the
  /admin/templates surface.
- Custom-fields permission resource is hardcoded to `clients` regardless
  of which entity (yacht/company/etc.) the values belong to. Documented
  as deferred (requires per-entity routes).

DB:
- documentSends: every parent FK (client_id, interest_id, berth_id,
  brochure_id, brochure_version_id) now uses ON DELETE SET NULL so the
  audit trail outlasts hard-deletes. The denormalized columns
  (recipient_email, document_kind, body_markdown, from_address) were
  added precisely for this. Migration 0035.
- Polymorphic discriminators on yachts.current_owner_type and
  invoices.billing_entity_type now have CHECK constraints — typos like
  `'clients'` vs `'client'` were silently inserting unreachable rows
  before. Migration 0036.

Integrations:
- Email attachment resolution (`src/lib/email/index.ts`) was importing
  MinIO directly instead of `getStorageBackend()`. Filesystem-backend
  deployments would have broken every email-with-attachment send. Now
  routes through the pluggable abstraction per CLAUDE.md.
- Documenso DOCUMENT_OPENED webhook filter relaxed: v2 may omit
  `readStatus` or send lowercase, so an event that was the SIGNAL of an
  open was being silently dropped. Now treats any recipient on a
  DOCUMENT_OPENED event as opened.

UI/UX:
- Expense detail used to render `receiptFileIds` as opaque UUID badges —
  reps couldn't view the receipt they uploaded. Now renders an image
  thumbnail (via `/api/v1/files/[id]/preview`) plus a Download link for
  PDFs. Closed the "where's my receipt?" loop in the expense flow.
- Expense detail Edit + Archive buttons now `<PermissionGate>` and the
  archive mutation surfaces success/error toasts instead of silent 403s.
- Brochures admin: setDefault/archive/create mutations now have onError
  toasts (only onSuccess existed before).
- Removed broken bulk-upload link in scan/page (route doesn't exist;
  used a raw `<a>` triggering a full reload to a 404).

Test status: 1168/1168 vitest passing. tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-05 05:51:39 +02:00
parent d4b3a1338f
commit ade4c9e77d
22 changed files with 577 additions and 97 deletions

View File

@@ -32,9 +32,58 @@ function isApiRoute(pathname: string): boolean {
return pathname.startsWith('/api/');
}
const STATE_CHANGING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
/**
* SameSite=Lax cookies block top-level cross-site POSTs in modern browsers,
* but defense-in-depth: every state-changing request to a session-authed
* `/api/v1/**` endpoint must originate from the same origin as the app.
* Webhooks (`/api/webhooks/**`) and public posts (`/api/public/**`) are
* exempt because they're called by external systems with no session
* cookie. Auth flows (`/api/auth/**`) and portal (`/api/portal/**`) handle
* their own origin/CSRF checks via better-auth.
*/
function isOriginCheckedPath(pathname: string): boolean {
if (!pathname.startsWith('/api/v1/')) return false;
return true;
}
function originAllowed(request: NextRequest): boolean {
const origin = request.headers.get('origin');
const referer = request.headers.get('referer');
// Same-origin fetch from the app sends both Origin AND a matching host.
// Use request.nextUrl.origin (the deployed origin) as the source of truth.
const expectedOrigin = request.nextUrl.origin;
if (origin) return origin === expectedOrigin;
if (referer) {
try {
return new URL(referer).origin === expectedOrigin;
} catch {
return false;
}
}
// Neither header present: most browser fetches always send Origin on
// POST/PUT/PATCH/DELETE, so this likely means a same-origin server-side
// call (e.g. Next.js internal fetch). Allow.
return true;
}
export function middleware(request: NextRequest): NextResponse {
const { pathname } = request.nextUrl;
// CSRF defense-in-depth: state-changing requests to authed /api/v1
// endpoints must come from the app's own origin.
if (
STATE_CHANGING_METHODS.has(request.method) &&
isOriginCheckedPath(pathname) &&
!originAllowed(request)
) {
return NextResponse.json(
{ error: 'Cross-origin state-changing request rejected' },
{ status: 403 },
);
}
// Always allow public paths through
if (isPublicPath(pathname)) {
return NextResponse.next();