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

@@ -111,6 +111,7 @@ describe('GET /api/storage/[token]', () => {
k: 'berths/abc/file.txt',
e: Math.floor(Date.now() / 1000) + 60,
n: 'nonce',
op: 'get' as const,
},
'wrong-secret',
);
@@ -130,6 +131,7 @@ describe('GET /api/storage/[token]', () => {
k: 'berths/abc/file.txt',
e: Math.floor(Date.now() / 1000) - 1,
n: 'nonce',
op: 'get' as const,
},
backend.getHmacSecret(),
);

View File

@@ -143,4 +143,30 @@ describe('merge token helpers', () => {
});
expect(unresolved).toEqual(['{{b}}', '{{c}}']);
});
// Audit-final v2: a malicious merge value (e.g. a client.fullName imported
// from a low-trust source) must NOT inject a link or emphasis into the
// rendered email body. escapeMergeValue neutralizes the markdown chars
// inside the value before substitution.
it('escapes markdown control chars inside merge values', () => {
const expanded = expandMergeTokens('Hi {{client.fullName}}, welcome.', {
'{{client.fullName}}': '[click here](https://attacker.tld)',
});
// The brackets/parens are now entity-encoded, so the markdown link
// rule will not fire.
expect(expanded).not.toContain('[click here](https://attacker.tld)');
expect(expanded).toContain('&#91;click here&#93;');
const html = renderEmailBody(expanded);
expect(html).not.toContain('<a href="https://attacker.tld');
// Plain-text version (visible to recipient) still reads normally.
expect(html).toContain('click here');
});
it('escapes nested {{token}} forms in merge values to prevent re-expansion shenanigans', () => {
const expanded = expandMergeTokens('Hi {{a}}', { '{{a}}': '{{secret_token}}' });
// Both braces and the underscore are entity-encoded.
expect(expanded).toContain('&#123;&#123;secret&#95;token&#125;&#125;');
expect(expanded).not.toContain('{{secret_token}}');
});
});

View File

@@ -158,58 +158,82 @@ describe('proxy HMAC token', () => {
it('signed token verifies', () => {
const t = signProxyToken(
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, n: 'nonce' },
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, op: 'get', n: 'nonce' },
secret,
);
const r = verifyProxyToken(t, secret);
const r = verifyProxyToken(t, secret, 'get');
expect(r.ok).toBe(true);
});
it('tampered signature fails', () => {
const t = signProxyToken(
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, n: 'nonce' },
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, op: 'get', n: 'nonce' },
secret,
);
const parts = t.split('.');
const body = parts[0] ?? '';
const sig = parts[1] ?? '';
const tampered = `${body}.${sig.slice(0, -2)}aa`;
const r = verifyProxyToken(tampered, secret);
const r = verifyProxyToken(tampered, secret, 'get');
expect(r.ok).toBe(false);
});
it('wrong secret fails', () => {
const t = signProxyToken(
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, n: 'n' },
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, op: 'get', n: 'n' },
secret,
);
const r = verifyProxyToken(t, 'other-secret');
const r = verifyProxyToken(t, 'other-secret', 'get');
expect(r.ok).toBe(false);
});
it('expired token fails', () => {
const t = signProxyToken(
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) - 10, n: 'n' },
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) - 10, op: 'get', n: 'n' },
secret,
);
const r = verifyProxyToken(t, secret);
const r = verifyProxyToken(t, secret, 'get');
expect(r.ok).toBe(false);
if (!r.ok) expect(r.reason).toBe('expired');
});
it('rejects payload with invalid storage key', () => {
const t = signProxyToken(
{ k: '../etc/passwd', e: Math.floor(Date.now() / 1000) + 60, n: 'n' },
{ k: '../etc/passwd', e: Math.floor(Date.now() / 1000) + 60, op: 'get', n: 'n' },
secret,
);
const r = verifyProxyToken(t, secret);
const r = verifyProxyToken(t, secret, 'get');
expect(r.ok).toBe(false);
if (!r.ok) expect(r.reason).toBe('invalid-key');
});
it('malformed token shape fails', () => {
expect(verifyProxyToken('garbage', secret).ok).toBe(false);
expect(verifyProxyToken('only-one-part', secret).ok).toBe(false);
expect(verifyProxyToken('too.many.parts.here', secret).ok).toBe(false);
expect(verifyProxyToken('garbage', secret, 'get').ok).toBe(false);
expect(verifyProxyToken('only-one-part', secret, 'get').ok).toBe(false);
expect(verifyProxyToken('too.many.parts.here', secret, 'get').ok).toBe(false);
});
// Audit-final v2: tokens minted for download (op='get') must not be
// accepted by the upload (PUT) handler, and vice versa. Without this
// a 24h email link could be replayed against the proxy PUT to overwrite
// the original storage object.
it('rejects a get-issued token verified as put', () => {
const getToken = signProxyToken(
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, op: 'get', n: 'n' },
secret,
);
const r = verifyProxyToken(getToken, secret, 'put');
expect(r.ok).toBe(false);
if (!r.ok) expect(r.reason).toBe('op-mismatch');
});
it('rejects a put-issued token verified as get', () => {
const putToken = signProxyToken(
{ k: 'berths/abc/file.pdf', e: Math.floor(Date.now() / 1000) + 60, op: 'put', n: 'n' },
secret,
);
const r = verifyProxyToken(putToken, secret, 'get');
expect(r.ok).toBe(false);
if (!r.ok) expect(r.reason).toBe('op-mismatch');
});
});