# CyanText Email SaaS

Multi-tenant email on the **same** paid Supabase project as SMS (`ttkdvfqcebfzdcbhdhdp`), with **isolated** `email_*` tables. SMS `public.messages` / device claim are untouched.

## Locked product choices

| Topic | Choice |
|---|---|
| UI | CyanText webmail at `/mail` first; white-label (`email.echobee.com.au` CNAME) later |
| Hub | `/portal` switches between SMS and Email for dual-product accounts |
| Mailboxes | Shared (`info@`) + per-user |
| Transport | **Dedicated CyanText Resend account** (do not reuse Cyandex production Resend) |
| Recovery | Email magic link + admin reset (SMS OTP later via Twilio) |
| Billing | Manual onboard + usage/storage metering (`docs/saas-billing-storage.md`); plans unlimited until super-admin UI |
| Identity | Same Supabase Auth + `account_entitlements` products `sms` / `email` |
| Domains | BYO (customer keeps registrar) + optional `@cyantext.com` later |

## Resend account guidance

Create a **new Resend account (or team) for CyanText**. Keep Cyandex on its existing Resend project.

Why separate:
- Sending reputation stays isolated (Cyandex volume/bounces must not hurt Echobee/CyanText SaaS)
- Webhooks, domain verification, and billing stay clear per product
- API keys can be rotated without taking Cyandex offline

Same Resend *company* login is fine if you create a separate team/project for CyanText — just do not share the Cyandex production `RESEND_API_KEY` with Vercel `cyantext`.

## Env

| Variable | Purpose |
|---|---|
| `RESEND_API_KEY` | Send + domain verify + inbound fetch |
| `RESEND_FROM` | Fallback from for auth/system mail (`CyanText <noreply@cyantext.com>`) |
| `RESEND_INBOUND_WEBHOOK_SECRET` | Optional header check for inbound webhook |
| `RESEND_WEBHOOK_SECRET` | Optional header check for delivery webhook |
| Existing Supabase + portal vars | Unchanged |

## APIs (mail only — not SMS)

| Method | Path | Auth |
|---|---|---|
| GET/POST | `/api/v1/email/domains` | Portal session (email entitlement) or `ctmail_` key |
| POST | `/api/v1/email/domains/:id/verify` | Owner/admin or mail key |
| POST | `/api/v1/email/domains/:id/enable-receiving` | Owner/admin — Resend Receiving MX for inbound |
| GET/POST | `/api/v1/email/mailboxes` | Same |
| GET/POST/PATCH | `/api/v1/email/messages` | Same — list filters `folder`/`q`/`starred`/`attention`; PATCH read/star/folder/`reportSpam`/`notSpam`; POST supports reply headers, attachments, `retryFailedId` |
| GET/POST/DELETE | `/api/v1/email/failures` | Failed-send queue + bounce dismiss (Cyandex Failed panel) |
| POST | `/api/v1/email/attachments` | Upload outbound attachment files → storage URLs |
| GET/POST/DELETE | `/api/v1/email/filters` | Auto-filter rules (Cyandex label-rule parity → spam/archive) |
| GET/POST/DELETE | `/api/v1/email/attentions` | Bring a message to a teammate’s Attention folder |
| POST | `/api/v1/email/keys` | Portal owner/admin — returns `ctmail_…` once |
| POST | `/api/v1/email/auth/forgot-password` | Public same-origin |
| POST | `/api/v1/email/auth/admin-reset` | Portal owner/admin |
| POST | `/api/v1/email/webhooks/resend-inbound` | Resend webhook (applies spam heuristics + filter rules) |
| POST | `/api/v1/email/webhooks/resend-delivery` | Resend webhook |

Mail API keys **cannot** call `/api/v1/messages` or claim devices.

## Spam auto-filtering (Cyandex parity)

Inbound mail is classified before it lands in Inbox:

1. **Heuristics** — `X-Spam-Flag: YES`, high `X-Spam-Score`, complaint suppressions, obvious spammy subjects → `folder=spam`
2. **Account filter rules** (`email_filter_rules`) — same criteria as Cyandex `email_label_rules` (`from`/`to`/`subject`/`body` contains, has attachment) with `action_folder` `spam` or `archive` and optional `mark_as_read`
3. **Report spam** in the UI moves the message to Spam and learns a `from_contains` rule for that sender
4. Unread badges and search **exclude** spam (Cyandex skips the SPAM label)

## Attention (other users)

Cyandex `email_attentions`: any teammate can flag a message for others. Recipients see it under **Attention** without moving folders. Done dismisses it for you.

## Mobile

- **SMS gateway:** native Android app under `android/` (device claim, dual-SIM, MMS).
- **Email:** installable PWA — open `/mail` on phone → browser **Add to Home Screen** (`manifest.webmanifest`). Layout is phone-first (list → reader).
- Native Flutter email shell (Cyandex-style) can wrap the same APIs later; webmail + PWA ships first so every mailbox works on mobile without a store build.

## DNS onboarding (generic + examples)

CyanText shows exact records after `POST /domains` (from Resend). Customer keeps the domain.

**Cloudflare:** DNS → Add record → paste Type/Name/Value; for Resend CNAMEs set **Proxy status DNS only** (grey cloud).

**cPanel / VentraIP:** Zone Editor → Add MX/TXT/CNAME exactly as listed.

Typical purposes:

- SPF / DKIM TXT — prove send authorization  
- MX on the receiving domain/subdomain — inbound to Resend → CyanText webhook  
- **DMARC TXT** (recommended) — `_dmarc` → `v=DMARC1; p=none; rua=mailto:dmarc@YOURDOMAIN; fo=1`  
  Start with `p=none`, then tighten. Missing DMARC is a common reason Gmail treats mail as less trusted / Spam.

### Gmail “Updates” vs Spam

- **Updates** is a Gmail *category tab* (receipts, confirmations, statements) — not the Spam folder. CyanText cannot force Primary.
- **Spam** is usually authentication, reputation, or content. Keep domains **verified** in CyanText, add DMARC, use a real From display name, and avoid marketing/`List-Unsubscribe` headers on 1:1 mail (CyanText strips those on portal compose).
- Ask recipients to move one message to **Primary** or add the mailbox to Google Contacts — that trains Gmail.

If the root domain already uses Google Workspace MX, prefer a **subdomain** for CyanText receive, or move MX fully to CyanText/Resend when cutting over.

## Echobee follow-up checklist

1. Enable email entitlement on Echobee `accounts.id` (`products` includes `email`, usually `['sms','email']` or `['email']`).
2. Owner signs in at `https://www.cyantext.com/mail` (or AU host).
3. Add domain `echobee.com.au` → publish DNS at Echobee’s Cloudflare/cPanel → Verify.
4. Create `info@echobee.com.au` (shared) and any user mailboxes.
5. In Resend dashboard, point webhooks to:
   - `…/api/v1/email/webhooks/resend-inbound` (`email.received`)
   - `…/api/v1/email/webhooks/resend-delivery` (delivered/bounced/failed/complained)
6. White-label later: CNAME `email.echobee.com.au` → CyanText; retire free Echobee Supabase `ocmcutwreyshzposahwc`.

## SQL: enable email for a tenant

```sql
insert into public.account_entitlements (account_id, products, plan_code, monthly_send_limit)
values ('ACxxxxxxxx', array['email']::text[], 'manual', 5000)
on conflict (account_id) do update
set products = excluded.products,
    updated_at = now();
```

To keep SMS + email on one account:

```sql
update public.account_entitlements
set products = array['sms','email']::text[],
    updated_at = now()
where account_id = 'ACxxxxxxxx';
```

## Isolation proof

- Email rows live only in `email_messages`.
- SMS claim RPCs still target `public.messages` only.
- Do not add `channel = 'email'` to the SMS model.
