caelum0x ccb966b4d8 feat(mail): box1 deploy — Dockerfile, fixed relay envelope sender, key parsing + Dodo webhook hardening
- apps/mail/Dockerfile + .dockerignore: rust:1-bookworm build -> debian slim runtime
  (pure rustls, only ca-certificates), dashboard baked in at /app/dashboard
- RELAY_RETURN_PATH: fixed MAIL FROM for relays that only accept approved senders
  (OCI Email Delivery approves exact addresses, so per-email VERP is rejected);
  test mode keeps VERP so the simulated transport still recovers the email id
- mail-auth keys: try hex first — 64 hex chars are also valid standard base64
  (48 bytes), which made AUTH_SIGNING_KEY=<hex> fail at boot
- Dodo webhook: an account_id from checkout metadata that does not exist is now
  ignored (200) instead of failing on the customer FK (500 + endless retries)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 14:03:39 +03:00
..

mail-core

Scribase Mail domain logic: multi-tenant accounts, the Postgres-backed send queue, DKIM signing, DNS record generation and verification, the SMTP relay transport, test-mode simulation, suppression lists, usage metering, audit log, event log and signed webhooks.

Independent implementation, written without reference to useSend source.

Wire shapes follow Resend's public API docs; mail formats follow RFC 5321/5322, RFC 6376 (DKIM, rsa-sha256, relaxed/relaxed) and RFC 8058 (one-click unsubscribe). Licence: MIT.

Tenancy

Every row belongs to an account (mail_accounts). mail_account_members maps a mail-auth user (sub of the session JWT) to an account with a role: owner > admin > developer > viewer. Invitations live in mail_account_invites. The built-in account 00000000-0000-0000-0000-000000000001 (SYSTEM_ACCOUNT_ID) owns pre-multi-tenant rows after the backfill migration, internal senders (CoreSender::new) and keys minted by the create-key CLI.

A domain name may be registered by several accounts while pending, but only one account can hold it verified (partial unique index). Suppressions are per account; hard bounces and complaints are also written to mail_global_suppressions, which applies to everyone.

Test mode

sk_test_ keys never deliver. Their emails are stored with test = true, need no registered domain (use test.scribase.dev as the from-domain), go through SimulatedTransport, are not metered against limits (they bump emails_test only) and never touch the suppression lists. Magic recipients on test.scribase.dev (or sandbox.scribase.com): delivered@, bounced@ (550 5.1.1), soft-bounce@ / delayed@ (451, then delivered 5 s later), complained@ (delivered, then a complaint), suppressed@. Webhook payloads carry "test": true at the top level and in data.

Modules

Module What it does
account Account, Role, AccountMember, AccountInvite, Actor, AuditEntry, UsageDay, SYSTEM_ACCOUNT_ID.
auth authenticate_api_key(&PgStore, raw) -> Result<Option<KeyContext>>: shared key resolution for the HTTP API, SMTP submission and hook adapters.
request The Resend-compatible SendRequest body and validate() (everything checkable without the database).
enqueue Caller { account_id, api_key_id, restricted_domain, test }, enqueue() (account active + under caps, domain, suppression, insert, usage bump) and CoreSender (mail_types::EmailSender).
raw enqueue_raw(store, cfg, caller, raw_rfc5322, envelope_rcpts): queue a finished message verbatim, keeping the client's Message-ID and header-only To/Cc.
worker Worker::new(store, cfg, secret, transport); run() claims due rows (FOR UPDATE SKIP LOCKED), renders (or takes raw_message), DKIM-signs, delivers through Arc<dyn Transport> or the simulator, maps results to status / retry / suppression.
simulate SimulatedTransport and the magic-recipient scripts.
transport RelayTransport: lettre STARTTLS smarthost (SMTP_*). SMTP_TLS=off is for a local dev sink only.
dkim, dns, mime, verp, tokens, tracking Signing, DNS records + real verification, MIME assembly, VERP return paths, signed unsubscribe/tracking tokens.
events Event log + per-account webhook fan-out. record_inbound_event(pool, email_id, kind, detail) lets the inbound server report async bounces/complaints/deliveries.
webhooks Svix-style signing and the retrying delivery worker. Event types include email.suppressed.
store PgStore: all SQL, account-scoped. migrate() ignores sibling crates' migrations in _sqlx_migrations. Tables use the mail_ prefix; migrations in migrations/.

Statuses

queued → scheduled → sent → delivered | delivery_delayed | bounced | complained | failed | canceled | suppressed | opened | clicked (the Resend last_event vocabulary plus suppressed). A relay 250 means sent; the direct MTA and the simulator report delivered.

Metering, plans and billing

mail_usage holds per-account daily counters (emails_sent, emails_test, recipients), bumped when an email is accepted onto the queue. Limits live in mail_plans (free 3,000/mo + 100/day + 1 domain, pro 50,000/mo metered overage, scale 150,000/mo, system uncapped); account limits JSON may override single caps. A metered plan keeps sending past its monthly allowance and the overage goes to the mail_usage_reports outbox (one increment per flush, event id overage:<account>:<YYYY-MM>:<seq>), which the server ingests into a Dodo usage meter. mail_billing_customers / mail_billing_events hold the Dodo customer, subscription state and processed webhook ids (store/billing.rs, plan.rs).

Send policy and abuse controls

Every entry point (enqueue, enqueue_raw, so API, SMTP submission, Supabase hook and internal senders) runs policy::enforce before queueing:

Gate Error (HTTP name)
account paused/suspended (reason included) account_paused 403
monthly / daily / hourly plan caps (overage plans skip the monthly one); message names the limit, reset time and upgrade_url quota_exceeded 429
sandbox tier: new accounts send only to their own members until a domain is verified and sandbox_graduation_sends clean sends exist (auto-promotes to standard) sandbox_restricted 403
per-domain warm-up: daily cap ramp (warmup_daily_caps) from verified_at; trusted tier skips quota_exceeded 429
content filter (content/): executable attachments by extension / MIME / magic bytes (also raw MIME part headers), brand impersonation in the display name, lookalike domains (brands and the sender's own domain), credential-harvest wording + off-domain or bare-IP links, link hosts on a DBL zone (url_blocklist_zone, cached; refused/unknown answers never block) content_blocked 422

Test-mode sends run the content filter only. reputation::review_account runs after every bounce/complaint (worker and inbound feedback): over min_volume sends in window_hours, bounce rate > bounce_rate_max or complaint rate > complaint_rate_max pauses the account, audits it, fires an account.paused webhook and leaves a row in mail_abuse_alerts. signup::vet refuses disposable providers and throttles signups per IP and per email domain (mail_throttles). Thresholds: AbusePolicy (persisted in mail_settings).