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

@@ -70,6 +70,17 @@ export function validateStorageKey(key: string): void {
// ─── HMAC token helpers ─────────────────────────────────────────────────────
/**
* Token op binding. `'get'` tokens are issued by `presignDownload` and only
* accepted by the proxy GET handler. `'put'` tokens are issued by
* `presignUpload` and only accepted by the proxy PUT handler. Without this
* binding a long-lived 24h download URL emailed to a customer could be
* replayed against the PUT handler to overwrite the original storage object
* (since both routes share an HMAC and key — the magic-byte check is also
* skipped when `c` is unset).
*/
export type ProxyTokenOp = 'get' | 'put';
interface ProxyTokenPayload {
/** Storage key (validated). */
k: string;
@@ -77,6 +88,11 @@ interface ProxyTokenPayload {
e: number;
/** Random nonce so two URLs for the same (key, expiry) differ. */
n: string;
/**
* Bound operation. Tokens minted before this field was added (legacy)
* fail-closed: the proxy handlers require the field's exact value.
*/
op: ProxyTokenOp;
/** Optional download filename. */
f?: string;
/** Optional content-type override. */
@@ -102,6 +118,12 @@ export function signProxyToken(payload: ProxyTokenPayload, secret: string): stri
export function verifyProxyToken(
token: string,
secret: string,
/**
* Required: the operation the verifier is allowed to perform. The token
* must have been minted with the same `op`. Without this argument an
* upload token could be replayed as a download (and vice versa).
*/
expectedOp: ProxyTokenOp,
): { ok: true; payload: ProxyTokenPayload } | { ok: false; reason: string } {
if (typeof token !== 'string' || !token.includes('.')) {
return { ok: false, reason: 'malformed' };
@@ -138,6 +160,11 @@ export function verifyProxyToken(
} catch {
return { ok: false, reason: 'invalid-key' };
}
// Op-binding: tokens minted before this field was added have no `op`
// and are now rejected. Fresh tokens must match `expectedOp` exactly.
if (payload.op !== expectedOp) {
return { ok: false, reason: 'op-mismatch' };
}
return { ok: true, payload };
}
@@ -269,7 +296,7 @@ export class FilesystemBackend implements StorageBackend {
validateStorageKey(key);
const expiresAt = Math.floor(Date.now() / 1000) + (opts.expirySeconds ?? 900);
const token = signProxyToken(
{ k: key, e: expiresAt, n: randomUUID(), c: opts.contentType },
{ k: key, e: expiresAt, n: randomUUID(), op: 'put', c: opts.contentType },
this.hmacSecret,
);
return { url: `/api/storage/${token}`, method: 'PUT' };
@@ -280,7 +307,14 @@ export class FilesystemBackend implements StorageBackend {
const expirySec = opts.expirySeconds ?? 900;
const expiresAtSec = Math.floor(Date.now() / 1000) + expirySec;
const token = signProxyToken(
{ k: key, e: expiresAtSec, n: randomUUID(), f: opts.filename, c: opts.contentType },
{
k: key,
e: expiresAtSec,
n: randomUUID(),
op: 'get',
f: opts.filename,
c: opts.contentType,
},
this.hmacSecret,
);
// ABSOLUTE URL: send-out emails interpolate this verbatim into the