# Architecture

## Request flow

```
Internet ─► Caddy :443 ─┬─ /api/*  ─► api (NestJS)  ─► Postgres (app_user, RLS)
  (auto HTTPS,          │                           └► Redis (BullMQ) ◄─ worker
   on-demand certs      └─ else    ─► web (Next.js) ─► api (internal)
   only for known hosts)
```

Caddy asks `api /internal/caddy-ask` before issuing a certificate. The API answers yes only
for the platform's own hosts, existing preview subdomains, and verified custom domains of
live sites. Every other hostname gets no certificate and no content.

## Tenancy: three walls

1. **Authorization.** Tenant routes are `/businesses/:businessId/...`. `TenantGuard` looks up
   the signed-in user's role for that business through `app_membership_role()`. No membership → 404.
2. **Row-level security.** The API connects as `app_user`, which doesn't own the tables.
   Each tenant table has a policy `business_id = app_current_business()`. `withTenant()` sets
   that value per transaction. Forget a `WHERE` and you get nothing, not someone else's data.
3. **Integrity.** Child rows reference `(site_id, business_id)` together, so a product can't
   point at another business's site even with the right IDs.

Cross-tenant lookups that must happen before a tenant is known (hostname → site, user →
businesses) go through narrow `SECURITY DEFINER` functions that return only IDs.

Platform admin routes use a separate `app_admin` role (BYPASSRLS), behind a guard that
requires platform-admin status and a completed MFA check.

Jobs: payloads carry `businessId` set by server code; the worker re-enters `withTenant()`.

Redis keys, object storage paths and exports will follow the same rule as they arrive:
always prefixed by business ID, never built from request input.

## Data rules

* Money: integer cents (`bigint`). Parsed from strings, never through floats.
* Weight: integer grams.
* Timestamps: `timestamptz`.

## Plugin model (Milestone 3, planned)

Plugins are TypeScript packages built against `@meat/plugin-sdk`, uploaded as release
artifacts, built in an isolated CI job (no network, no secrets), checked for SDK
compatibility, tested, and only then published to the private registry. Approved releases
are baked into the platform image at deploy time and enabled per site by subscription.
Uploaded code is never executed in production straight from a ZIP. Access is enforced in the
API and in job handlers by checking the site's active plugin entitlements.
