- Plans in a table (free/pro/scale), quotas enforced on API, SMTP and Supabase hook paths; test sends never count - GET /billing, checkout + portal via Dodo, signed Dodo webhooks, idempotent overage metering - Sandbox tier for new accounts, domain warm-up, auto-pause on bounce >4% / complaint >0.08% - Content checks: executables, brand impersonation, lookalike domains, credential harvest, Spamhaus DBL - Disposable-email and per-IP signup throttles; admin endpoints behind ADMIN_API_KEY Verified against the real server locally with a fake relay and mock Dodo (proof table in plans/scribase-mail-rust-2026-11-12.md). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
128 lines
8.8 KiB
Markdown
128 lines
8.8 KiB
Markdown
# mail-server
|
|
|
|
The axum binary for Scribase Mail: a multi-tenant, Resend-compatible JSON API,
|
|
account management, the mounted `mail-auth` login router, and the send and
|
|
webhook workers. One binary, one Postgres pool, both migration sets.
|
|
|
|
Independent implementation, written without reference to useSend source.
|
|
Licence: MIT.
|
|
|
|
## Credentials
|
|
|
|
* `Authorization: Bearer sk_...` — an API key (live) or `sk_test_...` (test
|
|
mode). The key names its account.
|
|
* `Authorization: Bearer <session JWT>` + `X-Account-Id: <uuid>` — a user
|
|
signed in through the mounted mail-auth router (magic link / OTP). The JWT is
|
|
verified against mail-auth's JWKS (`AUTH_JWKS_URL`, or the in-process key),
|
|
with `aud` = `DASHBOARD_JWT_AUDIENCE`; membership in the account gives the
|
|
role. A pending invitation for the signed-in address is accepted on login.
|
|
|
|
Permissions: full-access key = everything except members; sending key = send
|
|
and read one email; `viewer` read-only; `developer` also sends and manages
|
|
webhooks; `admin`/`owner` manage keys, domains, suppressions and members;
|
|
only an owner grants or removes the owner role.
|
|
|
|
## Endpoints
|
|
|
|
| Method + path | Purpose | Needs |
|
|
|---|---|---|
|
|
| `POST /emails`, `POST /emails/batch` | enqueue (`Idempotency-Key` honoured, 24 h) | send |
|
|
| `GET /emails?limit&after&before`, `GET /emails/{id}` | list / get (`"test": true` on test sends) | read / send |
|
|
| `PATCH /emails/{id}`, `POST /emails/{id}/cancel` | reschedule / cancel | send |
|
|
| `POST /emails/{id}/events` | report `delivered` / `bounced` / `complained` (feedback hook) | manage |
|
|
| `POST /domains`, `GET /domains`, `GET/PATCH/DELETE /domains/{id}`, `POST /domains/{id}/verify` | domains; create returns the DKIM/SPF/DMARC records; verify does real DNS lookups (409 if another account holds the name verified) | manage (read to list/get) |
|
|
| `POST /api-keys`, `GET /api-keys`, `DELETE /api-keys/{id}` | keys: `sk_...`, SHA-256 stored, shown once; `{"mode":"test"}` mints `sk_test_...` | manage |
|
|
| `POST /webhooks`, `GET /webhooks`, `GET/PATCH/DELETE /webhooks/{id}` | signed webhook endpoints (`whsec_...`) | webhooks |
|
|
| `GET /suppressions`, `POST /suppressions`, `DELETE /suppressions/{address}` | the account's suppression list | manage (read to list) |
|
|
| `POST /accounts` | create an account; the signed-in creator becomes owner | session JWT |
|
|
| `GET /accounts` | the caller's accounts with roles | session JWT |
|
|
| `GET /accounts/{id}`, `PATCH /accounts/{id}` | account; rename (plan/status/limits are operator-set) | read / manage |
|
|
| `GET /accounts/{id}/members`, `POST /accounts/{id}/members` | members + pending invites; invite `{email, role}` (sends the link through `CoreSender`) | read / members |
|
|
| `PATCH/DELETE /accounts/{id}/members/{user_id}`, `DELETE /accounts/{id}/invites/{invite_id}` | role change, removal (last owner protected), revoke invite | members |
|
|
| `GET /accounts/invites/{token}`, `POST /accounts/invites/{token}/accept` | invitation link page; explicit accept (idempotent) | none / session JWT |
|
|
| `GET /usage?from=&to=` | daily counters + totals (`emails_sent`, `emails_test`, `recipients`) and the account limits | read |
|
|
| `GET /audit-log?limit&before` | key / domain / member / webhook / suppression / account changes | read |
|
|
| `GET /billing` | plan, effective limits, period usage, overage, next reset, subscription state | read |
|
|
| `GET /billing/plans` | public price list from `mail_plans` | none |
|
|
| `POST /billing/checkout {plan}` | Dodo hosted checkout URL (metadata carries `account_id`) | manage |
|
|
| `POST /billing/portal` | Dodo customer-portal link | manage |
|
|
| `POST /billing/webhooks/dodo` | Standard-Webhooks-signed Dodo events → plan state (idempotent on `webhook-id`) | signature |
|
|
| `GET /admin/accounts?status=paused`, `GET /admin/accounts/{id}` | operator review (reputation, limits, billing) | `X-Admin-Key` |
|
|
| `POST /admin/accounts/{id}/pause|unpause|tier|plan` | kill switch / resume / tier / plan override | `X-Admin-Key` |
|
|
| `GET /admin/alerts`, `POST /admin/alerts/{id}/ack`, `POST /admin/billing/flush`, `GET /admin/policy` | alerts, manual metering flush, thresholds | `X-Admin-Key` |
|
|
| `GET /healthz` | liveness (pings Postgres) | none |
|
|
| `GET`/`POST /unsubscribe/{token}`, `GET /track/...` | hosted unsubscribe (RFC 8058), optional tracking | none |
|
|
| `/auth/*`, `/.well-known/jwks.json` | mail-auth router (see `crates/mail-auth/README.md`) | — |
|
|
|
|
Errors use Resend's shape: `{ "statusCode": 422, "name": "validation_error", "message": "..." }`.
|
|
Extra names: `forbidden` (403), `missing_account_id` (400), `account_paused` /
|
|
`account_suspended` (403), `quota_exceeded` (429, message names the limit and
|
|
the upgrade URL), `sandbox_restricted` (403), `content_blocked` (422),
|
|
`disposable_email` (403), `rate_limit_exceeded` (429, also signup throttles),
|
|
`billing_not_configured` (503), `invalid_invite` (410).
|
|
|
|
`POST /accounts` is the signup step: it runs `mail_core::signup::vet`
|
|
(disposable list, per-IP and per-email-domain throttles) and new accounts
|
|
start in the `sandbox` tier. Billing: `DODO_API_KEY` (test mode unless
|
|
`DODO_ENVIRONMENT=live_mode`), `DODO_WEBHOOK_SECRET`, `DODO_PRODUCT_PRO` /
|
|
`DODO_PRODUCT_SCALE` bind products to plans; the flush worker
|
|
(`BILLING_FLUSH_SECS`) applies scheduled downgrades and ingests overage into
|
|
the `DODO_OVERAGE_EVENT_NAME` meter. Operator alerts (auto-pause) go to
|
|
`ALERT_WEBHOOK_URL` / `ALERT_EMAIL_TO`.
|
|
|
|
## Run
|
|
|
|
```sh
|
|
createdb mail_dev
|
|
export DATABASE_URL=postgres://$USER@localhost/mail_dev # include the user: the inbound store (sqlx 0.9) does not default it
|
|
export PUBLIC_BASE_URL=https://mail.scribase.com # links in mail: unsubscribe, tracking, invites, magic links
|
|
export SMTP_USER=... SMTP_PASS=... # OCI Email Delivery SMTP credentials (relay pool primary, OCI_REGION=eu-frankfurt-1)
|
|
export PUBLIC_BOUNCE_DOMAIN=bounce.scribase.com # VERP return path, routed by Cloudflare Email Routing to the ingest below
|
|
export AUTH_SIGNING_KEY=... # 32-byte Ed25519 seed (mail-auth); AUTH_ADMIN_TOKEN=... for /auth/admin
|
|
export DASHBOARD_JWT_AUDIENCE=scribase-mail # = the mail-auth project's jwt_audience
|
|
export SYSTEM_FROM_ADDRESS="Scribase Mail <no-reply@yourdomain>" # invitation emails, domain of the system account
|
|
export SUBMIT_TLS_CERT=/etc/mail/fullchain.pem SUBMIT_TLS_KEY=/etc/mail/privkey.pem # enables SMTP submission on 587/465
|
|
export INBOUND_HTTP_SECRET=... INBOUND_HTTP_LISTEN=127.0.0.1:8585 INBOUND_DOMAINS=bounce.scribase.com # enables POST /inbound/raw
|
|
export OCI_ONBOARDING=on # create domains on OCI + mirror its suppressions (OCI_* or ~/.oci/config)
|
|
cargo run -p mail-server -- create-key --name bootstrap # system-account key, printed once
|
|
cargo run -p mail-server # listens on BIND_ADDR (127.0.0.1:8790)
|
|
```
|
|
|
|
Bootstrap order: `create-key` → `POST /domains` for your own domain with that
|
|
key → `POST /auth/admin/projects` (bare from-address on that domain) → users
|
|
sign in with magic links and `POST /accounts`.
|
|
|
|
Dev-only flags: `DEV_TRUST_UNVERIFIED_DOMAINS=on`, `WEBHOOK_ALLOW_PRIVATE=on`,
|
|
`RELAY_PRIMARY_HOST=127.0.0.1 RELAY_PRIMARY_TLS=none` (a local SMTP sink as the
|
|
relay), `SMTP_TLS=off` (legacy `MAIL_TRANSPORT=relay`). Full env table in
|
|
`src/main.rs`.
|
|
|
|
## What runs inside the process
|
|
|
|
| Piece | Module | Enabled by |
|
|
|---|---|---|
|
|
| Resend-compatible API + accounts | `routes/*` | always |
|
|
| mail-auth login router (`/auth/*`, JWKS) | `main.rs` | always |
|
|
| mail-hooks Supabase Send Email Hook (`/hooks/*`) | `main.rs` | always |
|
|
| Outbound `RelayPool` (OCI primary, failover, quotas); `/healthz` shows relay health | `transport.rs` | `MAIL_TRANSPORT=relay-pool` (default) |
|
|
| SMTP submission 587/465 (`mail_core::authenticate_api_key` + `enqueue_raw`) | `submit.rs` | `SUBMIT_TLS_CERT` |
|
|
| Inbound HTTPS ingest; DSN/ARF → `mail_core::record_inbound_event` (status, suppression, webhooks) | `inbound.rs` | `INBOUND_HTTP_SECRET` |
|
|
| OCI onboarding on domain create/verify + suppression mirror (`OCI_SUPPRESSION_SYNC_SECS`) | `oci.rs` | `OCI_ONBOARDING=on` |
|
|
|
|
Relay rejections (`[relay-rejected] …`, e.g. an OCI "sender not approved") mark
|
|
the email `failed` with the relay's text and never suppress the recipient.
|
|
|
|
With OCI onboarding on, `POST /domains` (optionally `"senders": [...]`) and
|
|
`POST /domains/{id}/verify` create the OCI email domain, reuse or create its
|
|
DKIM key, approve the From addresses (verify approves every address the
|
|
account has used on the domain) and return `records[]` with the OCI DKIM
|
|
CNAME, our DKIM TXT, SPF (`@`) and DMARC; the response also carries `relay`
|
|
(`dkim_state`, `senders`, `sender_failures`). A domain becomes `verified`
|
|
only when the DNS checks pass and OCI reports the DKIM key `ACTIVE`.
|
|
|
|
## Mounting other routers
|
|
|
|
`mail_server::build_app(state, extra: axum::Router) -> axum::Router` merges
|
|
`extra` into the app; `main.rs` mounts `mail_auth::router(...)` and
|
|
`mail_hooks::router(...)` this way with the shared pool.
|