Security hardening: deps, tenancy quotas, auth, deploy, webhooks

Addresses the findings from the platform security audit. Verified green:
all-workspace typecheck, web build, 16 API unit tests, 23 e2e auth tests,
and 0 high/critical production dependency vulnerabilities.

Dependencies (High):
- Bump drizzle-orm 0.36→0.45.2 (GHSA-gpj5-g38j-94v9 SQLi-via-identifier)
  and drizzle-kit→0.31.10; npm audit fix cleared fast-uri path-traversal
  and the react-router open-redirect. Remaining audit items are dev-only
  build tooling (esbuild/vite), not shipped at runtime.

AI cost control + storage quota (new ai_usage table, migration 0002):
- Per-firm monthly AI token budget enforced before each completion (429),
  with every completion recorded to an ai_usage ledger (lib/ai-usage.ts).
- Enforce per-plan storage quota on upload (402) and maintain
  storage_bytes_used on upload/delete (lib/storage-quota.ts); widen the
  column int→bigint so 8GB/50GB plans don't overflow.

Auth (defense-in-depth):
- Constant-time login: verify against a dummy argon2 hash when the account
  doesn't exist, closing the timing/enumeration oracle (verifyPasswordSafe).
- Enforce suspension on requireSuperadmin, /auth/me, /auth/resend-verification.

Web:
- Validate the post-login ?next= redirect to same-origin paths only
  (open-redirect / phishing).

Deploy hardening:
- docker-compose: memory/CPU limits so a spike can't OOM the Dokploy host.
- .dockerignore: keep destructive one-off scripts (seed-demo, create-admin,
  migrate-storage) out of the runtime image; retain the cron scripts.
- seed-demo.ts: hard-refuse NODE_ENV=production and the prod DB host.

Webhooks / config:
- Stripe idempotency via a stripe_events ledger (skip already-processed
  events; record only after successful processing so a transient failure
  still retries); make the plan-upgraded email non-blocking.
- Rate-limit account export and invoice PDF; cap invoice item arrays at 200.
- Require TURNSTILE_SECRET_KEY in production (bot protection no longer fails
  open on a forgotten key); don't load .env under NODE_ENV=test so the suite
  is hermetic.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Leon Serfaty
2026-07-17 13:34:33 -04:00
co-authored by Claude Fable 5
parent d1d96e4dd2
commit 304f7f30c3
25 changed files with 2854 additions and 402 deletions
+26 -2
View File
@@ -1,7 +1,7 @@
import type { FastifyInstance } from 'fastify';
import type Stripe from 'stripe';
import { and, eq } from 'drizzle-orm';
import { getDb, firms, users } from '@lawdesk/db';
import { getDb, firms, users, stripeEvents } from '@lawdesk/db';
import { env } from '../env';
import { getStripe } from '../lib/stripe';
import {
@@ -38,7 +38,27 @@ export async function stripeWebhookRoute(app: FastifyInstance) {
}
try {
// Idempotency for Stripe's at-least-once delivery. Skip events we've already fully
// processed so retries don't re-send emails or re-write audit rows.
const [seen] = await getDb()
.select({ id: stripeEvents.id })
.from(stripeEvents)
.where(eq(stripeEvents.id, event.id))
.limit(1);
if (seen) {
app.log.info({ id: event.id, type: event.type }, 'stripe webhook duplicate event ignored');
return { received: true, duplicate: true };
}
await handleEvent(event, app);
// Record only AFTER successful processing: a transient handler failure (→ 500 → Stripe
// retry) then re-processes instead of being skipped forever. applyPlan is idempotent, so
// the narrow check-then-insert race on truly concurrent redeliveries is harmless.
await getDb()
.insert(stripeEvents)
.values({ id: event.id, type: event.type })
.onConflictDoNothing();
} catch (err) {
app.log.error({ err, type: event.type }, 'stripe webhook handler failed');
// Return 200 anyway for some failures? No — let Stripe retry on transient failures.
@@ -65,7 +85,11 @@ async function handleEvent(event: Stripe.Event, app: FastifyInstance) {
typeof session.subscription === 'string' ? session.subscription : session.subscription?.id ?? null;
await applyPlan(firmId, plan, { customerId, subscriptionId });
await sendPlanUpgradedNotice(firmId, plan);
// Fire-and-forget: an email failure must not throw out of the handler (→ 500 → Stripe
// redelivery → duplicate processing). The plan (DB writes above) is already applied.
sendPlanUpgradedNotice(firmId, plan).catch((err) =>
app.log.warn({ err, firmId }, 'plan upgraded email failed'),
);
break;
}