API ReferenceREST /api/v1Sign in

Paid email sending service — business plan and TODO

Prepared: 6 November 2026. Status: proposal; implementation tasks below are not completed. Target portal: http://localhost:3002/email.

2. Provider choice and costs

Official public prices checked 6 November 2026; USD provider costs and proposed NZD retail prices below are different currencies. Recheck account/region pricing and provider terms before launch. No FX rate is assumed here.

| Component | Published requirement/cost | Plan | | --- | --- | --- | | Cloudflare Email Sending | Workers Paid; 3,000 emails/account/month included, then US$0.35/1,000 | Primary provider | | Cloudflare DNS | Required for Email Service sending domains | Onboard customer zones and verify sending setup | | Event subscriptions and Queues | Additional usage/service costs to validate | Delivery, bounce and complaint ingestion | | Email Routing | Inbound forwarding service | Optional later; preserve current mailbox MX |

The included allowance is shared by the Cloudflare account, not granted to each customer. Sends to verified destination addresses are free at provider level; accepted hard-bounced mail counts toward provider usage. Validate the exact multi-recipient charging unit and reconcile it against our per-recipient retail ledger before launch. Daily sending quotas are account based and may constrain pilots.

Sources: Cloudflare pricing, sending setup and DNS prerequisite, domain configuration, limits, event subscriptions.

### Proposed launch pricing — draft, not configured

Start with one plan to reduce sales and billing complexity: **NZ$9/month platform fee + NZ$2 per 1,000 accepted recipient sends**, with no included sends and no rounding usage up to whole 1,000-email blocks. Include three verified sending domains; additional domains require a reviewed plan. Show any applicable tax separately through the existing billing system.

| Monthly accepted recipients | Platform | Usage | Total before tax | | --- | --- | --- | --- | | 0 | NZ$9 | NZ$0 | NZ$9 | | 1,000 | NZ$9 | NZ$2 | NZ$11 | | 10,000 | NZ$9 | NZ$20 | NZ$29 | | 100,000 | NZ$9 | NZ$200 | NZ$209 |

Usage amount in NZ cents = round-half-up(accepted recipients × 200 / 1,000), rounded once per billing period. For example, 1,001 recipients cost NZ$2.00 in usage; 1,005 cost NZ$2.01. Store the integer count and snapshotted rate so invoices are reproducible. Use integer/rational arithmetic, never floating-point money.

This is a pricing hypothesis, not a profit forecast. At 100,000 provider-billable emails, assuming the full 3,000 allowance remains available, outbound usage costs US$33.95 before Workers Paid, Queues, compute, storage and other charges. If another application consumes the allowance, allocate the shared benefit explicitly. Convert actual costs to NZD and include payment fees, support, refunds and abuse losses before assessing contribution margin. Keep the retail pricing provisional until the first pilot invoice reconciles.

Default pilot usage cap: NZ$20/month excluding the platform fee; show the resulting maximum invoice clearly. Reserve usage atomically before enqueueing so concurrent requests cannot exceed the cap. Stop new sends at the cap; increasing it requires an authenticated customer action within staff-approved account limits.

3. What already exists

Repository inspection, not a production readiness assessment:

- apps/portal/src/app/email/page.tsx creates/lists mailboxes through createMailbox; it has no sending-domain, usage or email-provider controls. The local /email route returned HTTP 200 during planning. - apps/api/src/identity/me.controller.ts exposes customer mailbox operations; preserve these routes while adding a separate email sending module. - packages/db/prisma/schema.prisma contains domains, mailboxes, invoices and usage records. Existing UsageRecord is keyed to a hosting account, so a standalone email subscription needs its own ledger/aggregation relationship. - packages/billing already handles invoices, payment flows and service lifecycle. Reuse these mechanisms, with explicit email references and invoice types. - apps/worker, apps/scheduler and packages/jobs are integration points for dispatch, reconciliation and billing tasks; do not send inline in portal requests. - Reference service: /Users/udeshikasenarathna/Devlopment/tui24/Membership24/email-service. Its config supports SES and **Mailchimp Transactional**, not Mailgun. It provides preview/send modes, client tokens/IP restrictions, limits, a sending switch and rich-message sending. Its sender is fixed by runtime configuration. Its README explicitly says there is no API-wide idempotency. - Reuse reviewed delivery/validation patterns, not the deployed Membership service, its credentials, sender or customer traffic. Multi-tenant domains, durable usage billing and API-wide idempotency need new implementation here. - No usable graphify-out/graph.json was present; findings above came from source reads.

4. Portal experience and controls

Keep /email with two clearly labelled areas: **Mailboxes** and **Email sending**. Sending setup should work for a customer who has no hosting subscription and for an externally registered domain after Cloudflare DNS onboarding and verification.

1. Activate the email subscription: show pricing, billing cycle, usage definition, cap, acceptable-use terms and cancellation rules before acceptance. 2. Add a domain, preferably a dedicated sending subdomain such as notify.example.nz. 3. Require the sending domain to use Cloudflare DNS. Confirm whether its zone belongs to the managed Kiwi account or a customer account with an approved connection. Do not assume arbitrary external DNS is supported. Show exact provider-issued DNS names, types, values, purpose, copy buttons, last check and individual verification status. Explain required nameserver migration where applicable; preserve all existing zone records. 4. Explain DKIM, SPF/custom MAIL FROM and DMARC with provider-specific instructions. Never create a second SPF record at the same name or overwrite existing MX. An outbound bounce subdomain may need its own MX; this must not replace mailbox MX. 5. Preview Cloudflare onboarding changes, including cf-bounce records and any DMARC changes, before applying them; preserve existing mailbox MX and policies. Offer **Check verification** with background polling, pending/error explanations and retry controls. Provider status is authoritative; a local DNS match alone must not enable sending. Recheck periodically and block new sends if invalid. 6. Add permitted sender addresses on the verified domain and an optional Reply-To. Enforce the exact tenant-approved domain policy regardless of provider identity inheritance. 7. Create an API key (secret shown once), copy an API example and send a test. Live tests follow the disclosed retail acceptance rule even if a verified destination is free to us; preview tests do not contact providers or count. 8. Show sending on/off, domain health, accepted/delivered/bounced/complained counts, month-to-date charge, remaining cap and a forecast clearly labelled as an estimate. 9. Show message history with status, timestamps and safe errors; API-key rotation, revocation, billing CSV and cancellation remain accessible while sending is off.

Customer off stops dispatch of queued and future messages; accepted provider sends cannot be recalled. Hold pending messages until resumed or their expiry, without billing unsubmitted recipients. Recheck flags at worker dispatch, not just enqueue. Turning sending off does not cancel the monthly subscription: show this beside the switch. Cancellation stops sends immediately and stops renewal; proposed policy is no platform-fee refund for the started period, with final accepted usage invoiced.

Staff controls: global kill switch, provider enabled/disabled, active provider per subscription, customer suspension, limits and auditable cap adjustments. Preview is a separate mode. Effective permission requires all applicable switches, account payment/approval, verified sender, quota and reputation checks to pass. Disabling a provider must pause affected queues, never silently reroute them.

### How clients use Cloudflare through Kiwi Hosting

For the MVP, customers use the Kiwi Hosting portal while our backend manages Cloudflare resources in a dedicated Kiwi-managed Cloudflare account. Customers need no Cloudflare login or Cloudflare API token for this model. Their applications receive Kiwi email API keys only. Domain registration remains owned by the client; DNS hosting does not transfer their registrar ownership.

1. **Add domain:** accept an existing domain, confirm customer authorization and bind it to the customer before provisioning any provider resource. 2. **Connect DNS:** detect existing delegation. For domains moving to our managed account, inventory and copy existing DNS records, review conflicts and provide the assigned nameservers with registrar-specific guidance where practical. Tell the customer when they must update nameservers at their registrar. 3. **Wait for activation:** display pending/active/error states and recheck delegation. A submitted nameserver change is not proof of activation. Handle existing DNSSEC/DS configuration in the migration runbook to avoid broken resolution. 4. **Manage DNS:** allow authorized users to manage supported records in the portal, with clear descriptions, validated changes and protected service records. 5. **Enable email:** show pricing and cap, configure the required sending records, check provider verification and allow approved sender addresses. 6. **Connect application:** issue a scoped Kiwi API key, show a copyable send example and offer a clearly labelled test. Cloudflare credentials stay on our backend. 7. **Operate service:** show delivery history, usage, estimated charges and remaining budget; allow sending on/off, API-key rotation and subscription cancellation. 8. **Leave or transfer:** provide a DNS export and a documented account/domain handover process. Explain how delegation, DNSSEC, email verification and pending messages must be handled; subscription cancellation must not silently delete a customer's DNS zone or break their separately paid website/mailbox services.

Connecting a client's existing Cloudflare account is a later capability. Detect this case during onboarding and explain the supported migration or assisted path; do not silently move a zone between accounts or request their global API key. Design a separately reviewed, scoped connection before offering self-service customer-account access. Validate provider terms and managed-account suitability before onboarding paying clients.

``mermaid flowchart LR Client[Client] --> Portal[Kiwi Hosting portal] Portal --> Backend[Tenant authorized backend] Backend --> DNS[Cloudflare DNS API] Backend --> Email[Cloudflare Email Service] Client --> Registrar[Client owned registrar] Registrar --> Delegation[Nameserver delegation] Delegation --> DNS App[Client application] -->|Kiwi API key| Backend ``

### Cloudflare DNS API management

Use Cloudflare's DNS API for the portal's general DNS management and email DNS setup. Reuse packages/adapters-dns and its existing CloudflareDns adapter, which already supports finding/creating zones and listing, upserting and deleting records. This is existing integration code, not a completed email onboarding flow.

- Provide tenant-owned domain DNS screens to list, add, edit and delete A, AAAA, CNAME, MX and TXT records with TTL, MX priority and validation appropriate to type. - Resolve zone IDs from server-side customer/domain mappings, never directly trust a customer-supplied Cloudflare zone or record ID. Scope API tokens to permitted zones and the necessary DNS permissions; zone creation needs separately reviewed permissions. Store secrets server-side and audit each mutation without tokens. - Offer **Configure email DNS** after showing the exact proposed changes. Fetch authoritative provider instructions, compare existing records and add only the required missing records. Do not invent DKIM values or treat DNS writes as successful sending-domain verification. - Preserve multiple TXT/MX records at the same name. Before reuse, fix the adapter's current first-match-by-type/name upsert behavior, which can overwrite an unrelated TXT value or MX destination. Use exact record IDs for edits and ownership metadata for platform-managed records; do not rely on a comment alone for authorization. - Add pagination: the current list method reads only 100 records and upsert checks only five matches. Return the full relevant record set before planning changes. - Preserve existing SPF, DKIM selectors, DMARC policies and mailbox MX. Surface conflicts rather than replacing them silently. Protect platform-managed records from accidental edits and require an explicit reviewed change for removals. - Record before/after snapshots, re-read before writing to detect intervening edits, handle API throttling with bounded retries and make repeated setup idempotent. Batch operations do not propagate atomically across DNS; show pending status and recheck authoritative DNS/provider status before displaying success. - Show nameserver activation status for newly onboarded zones. An API-created zone still requires registrar delegation; preserve the existing zone before migration. - Include basic DNS self-service with the hosting offer initially; quote assisted migrations separately. Email usage charges apply to sends, not each DNS API call.

References: DNS record API, record creation and conflicts, batch behavior and DNS Write permission.

5. Sending, billing and reliability design

``mermaid flowchart LR Customer[Customer portal] --> API[Tenant authenticated API] App[Customer application] --> API API --> DB[(Subscription, domains, keys and ledger)] API --> Queue[Durable outbox and queue] Queue --> Worker[Dispatch gates and reservations] Worker --> CF[Cloudflare Email Sending REST API] CF --> Subscription[Domain event subscriptions] Subscription --> CFQueue[Cloudflare Queue] CFQueue --> Events[Authenticated consumer and event ingestion] Events --> DB DB --> Billing[Reconcile and generate existing invoices] ``

### Charge definition

- One email unit means **one recipient accepted by the provider**, counting To, CC and BCC. Deduplicate identical recipient addresses within one request. - A message to three distinct recipients is three units. A later bounce or complaint does not refund acceptance; disclose this because provider sending costs remain. - Preview, local validation failure, local suppression, definite rejection at the provider API boundary and never-submitted queued messages are zero units. Release their reservations. - A later asynchronous rejection after confirmed acceptance must follow the published acceptance billing rule; do not confuse it with an API-boundary rejection. - Partial provider acceptance bills only accepted recipients, not the entire request. - API HTTP 202 means queued locally, not provider accepted or delivered. Display and document these separate states; acceptance never guarantees inbox placement. - An idempotency key scoped to customer plus payload digest returns the original result on retry; a different payload with the same key returns a conflict. - Provider timeout or crash after submission becomes unknown, with its budget reservation held. Do not blindly retry, fail over or invoice uncertain acceptance. Reconcile through trusted events/provider records; if still unresolved, expire via a staff-reviewed adjustment policy. Track unrecoverable provider cost separately. - Pin each message to its provider/account/region. Switching affects new messages only after that provider has independently verified the domain. Drain or explicitly cancel old work before retiring the old provider configuration. - Capture provider message IDs and immutable per-recipient acceptance entries with unique constraints. Duplicate callbacks/retries must never create another charge. - Use UTC timestamps and explicit stored UTC period boundaries for subscription billing; display dates in the customer's timezone. Persist the rate version. - Close periods idempotently with a unique subscription/period invoice reference; reconcile before finalization and carry late confirmations as labelled adjustments into the next open period. Corrections are credits/debits, not edited ledger history.

### Proposed persistent entities

| Entity | Minimum responsibility | | --- | --- | | EmailSubscription | Customer, lifecycle, provider reference, rate version, cycle, limits and switches | | EmailSendingDomain | Tenant ownership, canonical name, provider account/zone/domain identity, DNS and verification state | | EmailApiKey | Tenant, hashed secret, scopes, expiry/revocation and last-used timestamp | | EmailMessage / recipient | Idempotency, digest, provider pin, safe metadata and recipient outcomes | | EmailOutbox / reservation | Atomic admission, durable queue handoff, cap reservation and expiry | | EmailProviderEvent | Authenticated deduplicated delivery/bounce/complaint events | | EmailUsageLedger | Immutable accepted-recipient charges and explicit adjustments | | EmailSuppression | Tenant recipient suppression and provider/account suppression references | | EmailBillingPeriod | Usage/rate snapshot, reconciliation and one invoice linkage |

Choose exact Prisma names during implementation. All resource queries must enforce customer ownership; provider identifiers supplied by clients cannot bypass it. Prevent a domain being claimed by another customer while already active; define an audited transfer/reverification process. Protect parent/subdomain ownership relationships explicitly rather than relying on provider-wide identity inheritance.

### Suggested API surface

- Portal session: /api/v1/me/email/subscription, /domains, /domains/:id/verify, /senders, /keys, /usage, /messages, /test-send, /settings under that email prefix. - Customer backend: POST /api/v1/email/send with scoped bearer key and idempotency key; GET /api/v1/email/messages/:id for status, limited to the key's tenant. - Provider events: consume Cloudflare domain event subscriptions through Queues, using a scoped authenticated HTTP pull consumer or reviewed Worker bridge. Validate schema, deduplicate event IDs and acknowledge only after durable storage. - Staff: provider readiness, customer approval/suspension, limits and audit views.

Cloudflare event subscriptions are domain scoped. Validate expected account, zone, domain and stored message IDs before mapping events to a customer. Handle delivered, deferred, bounced, failed, rejected and complained events. Use scoped queue credentials and authenticated ingestion; never trust a payload's customer ID. Confirm retention, retries, dead-letter handling and reconciliation coverage during the adapter spike rather than assuming an SES-style webhook.

6. Ordered implementation TODO

### Phase 0 — agree the offer and isolate infrastructure

- [ ] Confirm transactional-only MVP, proposed price, cap, tax display and cancellation terms. - [ ] Confirm provider commercial/resale terms and abuse responsibilities before selling. - [ ] Choose a dedicated Kiwi Cloudflare account, Workers Paid setup, zone ownership, beta access, daily quotas and tenant reputation isolation; avoid sharing Membership24's live account/service. - [ ] Record baseline provider/infrastructure/support cost and pilot success targets. - [ ] Define retention/deletion rules and review customer terms/privacy for intended markets.

### Phase 1 — subscription, domain verification and switches

- [ ] Add tenant-owned schema/migrations and email contracts without changing mailbox behavior. - [ ] Spike Cloudflare domain-management API coverage; implement supported onboarding/ verification operations and document any dashboard-only steps honestly. - [ ] Separate scoped DNS/domain-management tokens from restricted sending/queue tokens; encrypt credentials and never expose Cloudflare secrets to portal customers. - [ ] Add customer, provider and global sending gates, preview mode and staff audit events. - [ ] Add portal setup, verification statuses and Cloudflare DNS onboarding instructions. - [ ] Enforce sender ownership, safe domain transfer and periodic verification checks.

### Phase 1a — client onboarding and account ownership

- [ ] Implement the Kiwi-managed Cloudflare account model with tenant/domain/zone mappings. - [ ] Build add-domain → DNS migration review → nameserver instructions → activation status. - [ ] Add migration checks for existing records, DNSSEC/DS and domains already in Cloudflare. - [ ] Keep registrar ownership with the client and explain required registrar actions. - [ ] Add guided email activation, Kiwi API-key creation, send example and test-send steps. - [ ] Add customer help explaining managed DNS, email sending, billing and on/off behavior. - [ ] Document DNS export, transfer/offboarding and cancellation without unrelated DNS deletion. - [ ] Test pending/failed delegation, duplicate domain claims and safe resume after partial setup. - [ ] Track customer-owned Cloudflare account connections as a later phase, not an MVP promise.

### Phase 1b — DNS API management

- [ ] Reuse the existing DNS adapter; fix pagination and record identity handling. - [ ] Add tenant-scoped record CRUD routes and DNS screens with type validation. - [ ] Add zone ownership mappings, scoped tokens and auditable before/after changes. - [ ] Add email DNS preview/apply/recheck with conflict detection and idempotency. - [ ] Test multiple TXT/MX records, more than 100 records, cross-tenant IDs, concurrent edits, API failures, protected records and preserved SPF/MX/DMARC settings. - [ ] Document zone onboarding, nameserver migration and recovery from partial setup.

### Phase 2 — authenticated sending and feedback

- [ ] Add scoped hashed API keys with one-time reveal, rotation and revocation. - [ ] Add validated API/test send, message-size/recipient limits and per-tenant rate limits. - [ ] Implement durable outbox, atomic cap reservations and request idempotency. - [ ] Implement Cloudflare REST dispatch with explicit accepted/rejected/unknown states and safe retries. - [ ] Configure domain event subscriptions, Queues consumption and event deduplication. - [ ] Suppress hard bounces/complaints before future dispatch, enforce provider suppression, and add conservative reputation alerts/automatic suspension thresholds for review. - [ ] Add history, usage counts and test-send UI with explicit preview/live distinction.

### Phase 3 — usage billing and lifecycle

- [ ] Implement immutable per-recipient ledger, rate snapshots and budget alerts. - [ ] Reconcile counts against provider evidence; alert on missing or unmatched events. - [ ] Add existing invoice/payment integration with unique email billing-period linkage. - [ ] Handle late events, credits, final usage, failed payment suspension and cancellation. - [ ] Add itemized usage export, charge estimate and understandable invoice descriptions.

### Phase 4 — validate and pilot

- [ ] Verify tenant/key isolation, unverified/forged sender denial and key revocation. - [ ] Verify customer/global/provider off also stops already queued work at dispatch. - [ ] Test 1/3 recipients, partial acceptance, suppression, rejection and bounce billing rules. - [ ] Test duplicate keys/events, worker crashes, provider timeout and no automatic failover. - [ ] Test concurrent cap admission, rate rounding, period boundaries and repeated invoice jobs. - [ ] Test webhook signature/replay/confirmation URL attacks and provider-account mismatch. - [ ] Test Cloudflare zone onboarding, cross-account access boundaries, existing SPF/MX preservation, verification loss and DNS changes requiring customer action. - [ ] Complete local mock-provider end-to-end setup → verify → send → event → invoice. - [ ] Prepare an operational runbook for abuse, provider outage, unknown sends and rollback. - [ ] Obtain specific live activation authorization before production configuration or real tests. - [ ] Run the approved pilot, reconcile the first invoice cycle and decide whether to launch.

### Phase 5 — expand only after the Cloudflare pilot

- [ ] Review beta stability, account-level reputation exposure and quota increases. - [ ] Validate customer-owned Cloudflare account connections if managed-account zones do not cover demand; document credential ownership and disconnection behavior. - [ ] Consider SES/Mailgun only if customer demand or Cloudflare limitations justify it. - [ ] Independently verify domains and test deliberate migration before any new provider.

7. Launch boundaries

No campaign builder, newsletter audience manager, dedicated IP offering, inbound mail processing or customer SMTP gateway in the initial release. Consider these only after validated demand. Keep message bodies out of routine logs; retain only what dispatch needs, encrypted with a defined expiry. Redact BCC and recipient data from unauthorized views. Do not promise inbox delivery or an SLA before measuring it.

This document authorizes no deployment, provider configuration changes or real email sends. The referenced Membership24 repository also explicitly requires a specific request before live actions. This task creates a plan only.

Markdown source
# Paid email sending service — business plan and TODO

Prepared: 6 November 2026. Status: proposal; implementation tasks below are not completed.
Target portal: http://localhost:3002/email.

## 1. Recommended business

Sell managed transactional email to existing Kiwi Hosting customers: invoices,
password resets, booking confirmations, receipts and application notifications.
Customers pay for an easy setup, domain authentication, reliable API, delivery
visibility and local support. Start with existing hosting customers and agencies;
validate demand with 3–5 pilot customers before investing in a campaign builder.

Use **Cloudflare Email Service** as the primary transactional sending provider,
with Cloudflare DNS for sending domains. Use its REST API from the existing
Node backend/worker; moving the whole portal to Workers is not required.
Customers control their sending on/off switch; staff retain global suspension
and provider controls. SES and Mailgun are deferred alternatives, not MVP work.
Cloudflare Email Sending is currently labelled beta: validate account access,
commercial terms and production suitability before accepting paying customers.

Offer mailbox hosting and email sending as separate services in `/email`.
Mailboxes receive/store mail; this product sends application messages. Existing
mailbox customers must retain their addresses and mailbox management.

### Initial offer and commercial validation

- Managed domain setup, HTTPS sending API, test send, usage dashboard and delivery logs.
- Transactional messages only at launch; no purchased lists, cold outreach or bulk campaigns.
- Monthly platform charge plus metered recipient sends, with an explicit spending cap.
- Free local preview; a small, manually approved live trial with a hard recipient limit.
- Optional assisted setup fee, quoted before work, for Cloudflare DNS onboarding.
- Interview pilots about monthly volume, current provider, integration and support needs.
- Measure activation rate, time to first verified domain, paying customers, revenue,
  contribution margin, support minutes/customer, bounce/complaint rates and churn.
- Expand after one complete pilot billing cycle reconciles and support costs are understood.

## 2. Provider choice and costs

Official public prices checked 6 November 2026; USD provider costs and proposed
NZD retail prices below are different currencies. Recheck account/region pricing
and provider terms before launch. No FX rate is assumed here.

| Component | Published requirement/cost | Plan |
| --- | --- | --- |
| Cloudflare Email Sending | Workers Paid; 3,000 emails/account/month included, then US$0.35/1,000 | Primary provider |
| Cloudflare DNS | Required for Email Service sending domains | Onboard customer zones and verify sending setup |
| Event subscriptions and Queues | Additional usage/service costs to validate | Delivery, bounce and complaint ingestion |
| Email Routing | Inbound forwarding service | Optional later; preserve current mailbox MX |

The included allowance is shared by the Cloudflare account, not granted to each
customer. Sends to verified destination addresses are free at provider level;
accepted hard-bounced mail counts toward provider usage. Validate the exact
multi-recipient charging unit and reconcile it against our per-recipient retail
ledger before launch. Daily sending quotas are account based and may constrain pilots.

Sources: [Cloudflare pricing](https://developers.cloudflare.com/email-service/platform/pricing/),
[sending setup and DNS prerequisite](https://developers.cloudflare.com/email-service/get-started/send-emails/),
[domain configuration](https://developers.cloudflare.com/email-service/configuration/domains/),
[limits](https://developers.cloudflare.com/email-service/platform/limits/),
[event subscriptions](https://developers.cloudflare.com/email-service/reference/event-subscriptions/).

### Proposed launch pricing — draft, not configured

Start with one plan to reduce sales and billing complexity:
**NZ$9/month platform fee + NZ$2 per 1,000 accepted recipient sends**, with no
included sends and no rounding usage up to whole 1,000-email blocks. Include
three verified sending domains; additional domains require a reviewed plan.
Show any applicable tax separately through the existing billing system.

| Monthly accepted recipients | Platform | Usage | Total before tax |
| --- | --- | --- | --- |
| 0 | NZ$9 | NZ$0 | NZ$9 |
| 1,000 | NZ$9 | NZ$2 | NZ$11 |
| 10,000 | NZ$9 | NZ$20 | NZ$29 |
| 100,000 | NZ$9 | NZ$200 | NZ$209 |

Usage amount in NZ cents = round-half-up(accepted recipients × 200 / 1,000),
rounded once per billing period. For example, 1,001 recipients cost NZ$2.00 in
usage; 1,005 cost NZ$2.01. Store the integer count and snapshotted rate so invoices
are reproducible. Use integer/rational arithmetic, never floating-point money.

This is a pricing hypothesis, not a profit forecast. At 100,000 provider-billable
emails, assuming the full 3,000 allowance remains available, outbound usage costs
US$33.95 before Workers Paid, Queues, compute, storage and other charges.
If another application consumes the allowance, allocate the shared benefit
explicitly. Convert actual costs to NZD and include payment fees, support,
refunds and abuse losses before assessing contribution margin. Keep the retail
pricing provisional until the first pilot invoice reconciles.

Default pilot usage cap: NZ$20/month excluding the platform fee; show the resulting
maximum invoice clearly. Reserve usage atomically before enqueueing so concurrent
requests cannot exceed the cap. Stop new sends at the cap; increasing it requires
an authenticated customer action within staff-approved account limits.

## 3. What already exists

Repository inspection, not a production readiness assessment:

- `apps/portal/src/app/email/page.tsx` creates/lists mailboxes through
  `createMailbox`; it has no sending-domain, usage or email-provider controls.
  The local `/email` route returned HTTP 200 during planning.
- `apps/api/src/identity/me.controller.ts` exposes customer mailbox operations;
  preserve these routes while adding a separate email sending module.
- `packages/db/prisma/schema.prisma` contains domains, mailboxes, invoices and
  usage records. Existing `UsageRecord` is keyed to a hosting account, so a
  standalone email subscription needs its own ledger/aggregation relationship.
- `packages/billing` already handles invoices, payment flows and service lifecycle.
  Reuse these mechanisms, with explicit email references and invoice types.
- `apps/worker`, `apps/scheduler` and `packages/jobs` are integration points for
  dispatch, reconciliation and billing tasks; do not send inline in portal requests.
- Reference service: `/Users/udeshikasenarathna/Devlopment/tui24/Membership24/email-service`.
  Its config supports SES and **Mailchimp Transactional**, not Mailgun.
  It provides preview/send modes, client tokens/IP restrictions, limits, a sending
  switch and rich-message sending. Its sender is fixed by runtime configuration.
  Its README explicitly says there is no API-wide idempotency.
- Reuse reviewed delivery/validation patterns, not the deployed Membership service,
  its credentials, sender or customer traffic. Multi-tenant domains, durable usage
  billing and API-wide idempotency need new implementation here.
- No usable `graphify-out/graph.json` was present; findings above came from source reads.

## 4. Portal experience and controls

Keep `/email` with two clearly labelled areas: **Mailboxes** and **Email sending**.
Sending setup should work for a customer who has no hosting subscription and for
an externally registered domain after Cloudflare DNS onboarding and verification.

1. Activate the email subscription: show pricing, billing cycle, usage definition,
   cap, acceptable-use terms and cancellation rules before acceptance.
2. Add a domain, preferably a dedicated sending subdomain such as `notify.example.nz`.
3. Require the sending domain to use Cloudflare DNS. Confirm whether its zone
   belongs to the managed Kiwi account or a customer account with an approved
   connection. Do not assume arbitrary external DNS is supported. Show exact provider-issued DNS names, types, values, purpose, copy buttons,
   last check and individual verification status. Explain required nameserver
   migration where applicable; preserve all existing zone records.
4. Explain DKIM, SPF/custom MAIL FROM and DMARC with provider-specific instructions.
   Never create a second SPF record at the same name or overwrite existing MX.
   An outbound bounce subdomain may need its own MX; this must not replace mailbox MX.
5. Preview Cloudflare onboarding changes, including `cf-bounce` records and any
   DMARC changes, before applying them; preserve existing mailbox MX and policies.
   Offer **Check verification** with background polling, pending/error explanations
   and retry controls. Provider status is authoritative; a local DNS match alone
   must not enable sending. Recheck periodically and block new sends if invalid.
6. Add permitted sender addresses on the verified domain and an optional Reply-To.
   Enforce the exact tenant-approved domain policy regardless of provider identity inheritance.
7. Create an API key (secret shown once), copy an API example and send a test.
   Live tests follow the disclosed retail acceptance rule even if a verified
   destination is free to us; preview tests do not contact providers or count.
8. Show sending on/off, domain health, accepted/delivered/bounced/complained counts,
   month-to-date charge, remaining cap and a forecast clearly labelled as an estimate.
9. Show message history with status, timestamps and safe errors; API-key rotation,
   revocation, billing CSV and cancellation remain accessible while sending is off.

Customer off stops dispatch of queued and future messages; accepted provider sends
cannot be recalled. Hold pending messages until resumed or their expiry, without
billing unsubmitted recipients. Recheck flags at worker dispatch, not just enqueue.
Turning sending off does not cancel the monthly subscription: show this beside the
switch. Cancellation stops sends immediately and stops renewal; proposed policy is
no platform-fee refund for the started period, with final accepted usage invoiced.

Staff controls: global kill switch, provider enabled/disabled, active provider per
subscription, customer suspension, limits and auditable cap adjustments. Preview is
a separate mode. Effective permission requires all applicable switches, account
payment/approval, verified sender, quota and reputation checks to pass. Disabling a
provider must pause affected queues, never silently reroute them.

### How clients use Cloudflare through Kiwi Hosting

For the MVP, customers use the Kiwi Hosting portal while our backend manages
Cloudflare resources in a dedicated Kiwi-managed Cloudflare account. Customers
need no Cloudflare login or Cloudflare API token for this model. Their applications
receive Kiwi email API keys only. Domain registration remains owned by the client;
DNS hosting does not transfer their registrar ownership.

1. **Add domain:** accept an existing domain, confirm customer authorization and
   bind it to the customer before provisioning any provider resource.
2. **Connect DNS:** detect existing delegation. For domains moving to our managed
   account, inventory and copy existing DNS records, review conflicts and provide
   the assigned nameservers with registrar-specific guidance where practical.
   Tell the customer when they must update nameservers at their registrar.
3. **Wait for activation:** display pending/active/error states and recheck delegation.
   A submitted nameserver change is not proof of activation. Handle existing
   DNSSEC/DS configuration in the migration runbook to avoid broken resolution.
4. **Manage DNS:** allow authorized users to manage supported records in the portal,
   with clear descriptions, validated changes and protected service records.
5. **Enable email:** show pricing and cap, configure the required sending records,
   check provider verification and allow approved sender addresses.
6. **Connect application:** issue a scoped Kiwi API key, show a copyable send example
   and offer a clearly labelled test. Cloudflare credentials stay on our backend.
7. **Operate service:** show delivery history, usage, estimated charges and remaining
   budget; allow sending on/off, API-key rotation and subscription cancellation.
8. **Leave or transfer:** provide a DNS export and a documented account/domain
   handover process. Explain how delegation, DNSSEC, email verification and pending
   messages must be handled; subscription cancellation must not silently delete a
   customer's DNS zone or break their separately paid website/mailbox services.

Connecting a client's existing Cloudflare account is a later capability. Detect
this case during onboarding and explain the supported migration or assisted path;
do not silently move a zone between accounts or request their global API key.
Design a separately reviewed, scoped connection before offering self-service
customer-account access. Validate provider terms and managed-account suitability
before onboarding paying clients.

```mermaid
flowchart LR
    Client[Client] --> Portal[Kiwi Hosting portal]
    Portal --> Backend[Tenant authorized backend]
    Backend --> DNS[Cloudflare DNS API]
    Backend --> Email[Cloudflare Email Service]
    Client --> Registrar[Client owned registrar]
    Registrar --> Delegation[Nameserver delegation]
    Delegation --> DNS
    App[Client application] -->|Kiwi API key| Backend
```

### Cloudflare DNS API management

Use Cloudflare's DNS API for the portal's general DNS management and email DNS
setup. Reuse `packages/adapters-dns` and its existing `CloudflareDns` adapter,
which already supports finding/creating zones and listing, upserting and deleting
records. This is existing integration code, not a completed email onboarding flow.

- Provide tenant-owned domain DNS screens to list, add, edit and delete A, AAAA,
  CNAME, MX and TXT records with TTL, MX priority and validation appropriate to type.
- Resolve zone IDs from server-side customer/domain mappings, never directly trust
  a customer-supplied Cloudflare zone or record ID. Scope API tokens to permitted
  zones and the necessary DNS permissions; zone creation needs separately reviewed
  permissions. Store secrets server-side and audit each mutation without tokens.
- Offer **Configure email DNS** after showing the exact proposed changes. Fetch
  authoritative provider instructions, compare existing records and add only the
  required missing records. Do not invent DKIM values or treat DNS writes as
  successful sending-domain verification.
- Preserve multiple TXT/MX records at the same name. Before reuse, fix the adapter's
  current first-match-by-type/name upsert behavior, which can overwrite an unrelated
  TXT value or MX destination. Use exact record IDs for edits and ownership metadata
  for platform-managed records; do not rely on a comment alone for authorization.
- Add pagination: the current list method reads only 100 records and upsert checks
  only five matches. Return the full relevant record set before planning changes.
- Preserve existing SPF, DKIM selectors, DMARC policies and mailbox MX. Surface
  conflicts rather than replacing them silently. Protect platform-managed records
  from accidental edits and require an explicit reviewed change for removals.
- Record before/after snapshots, re-read before writing to detect intervening edits,
  handle API throttling with bounded retries and make repeated setup idempotent.
  Batch operations do not propagate atomically across DNS; show pending status and
  recheck authoritative DNS/provider status before displaying success.
- Show nameserver activation status for newly onboarded zones. An API-created zone
  still requires registrar delegation; preserve the existing zone before migration.
- Include basic DNS self-service with the hosting offer initially; quote assisted
  migrations separately. Email usage charges apply to sends, not each DNS API call.

References: [DNS record API](https://developers.cloudflare.com/api/resources/dns/),
[record creation and conflicts](https://developers.cloudflare.com/api/resources/dns/subresources/records/methods/create/),
[batch behavior and DNS Write permission](https://developers.cloudflare.com/api/resources/dns/subresources/records/methods/batch/).

## 5. Sending, billing and reliability design

```mermaid
flowchart LR
    Customer[Customer portal] --> API[Tenant authenticated API]
    App[Customer application] --> API
    API --> DB[(Subscription, domains, keys and ledger)]
    API --> Queue[Durable outbox and queue]
    Queue --> Worker[Dispatch gates and reservations]
    Worker --> CF[Cloudflare Email Sending REST API]
    CF --> Subscription[Domain event subscriptions]
    Subscription --> CFQueue[Cloudflare Queue]
    CFQueue --> Events[Authenticated consumer and event ingestion]
    Events --> DB
    DB --> Billing[Reconcile and generate existing invoices]
```

### Charge definition

- One email unit means **one recipient accepted by the provider**, counting To,
  CC and BCC. Deduplicate identical recipient addresses within one request.
- A message to three distinct recipients is three units. A later bounce or complaint
  does not refund acceptance; disclose this because provider sending costs remain.
- Preview, local validation failure, local suppression, definite rejection at the provider API boundary
  and never-submitted queued messages are zero units. Release their reservations.
- A later asynchronous rejection after confirmed acceptance must follow the
  published acceptance billing rule; do not confuse it with an API-boundary rejection.
- Partial provider acceptance bills only accepted recipients, not the entire request.
- API HTTP 202 means queued locally, not provider accepted or delivered. Display and
  document these separate states; acceptance never guarantees inbox placement.
- An idempotency key scoped to customer plus payload digest returns the original
  result on retry; a different payload with the same key returns a conflict.
- Provider timeout or crash after submission becomes `unknown`, with its budget
  reservation held. Do not blindly retry, fail over or invoice uncertain acceptance.
  Reconcile through trusted events/provider records; if still unresolved, expire via
  a staff-reviewed adjustment policy. Track unrecoverable provider cost separately.
- Pin each message to its provider/account/region. Switching affects new messages
  only after that provider has independently verified the domain. Drain or explicitly
  cancel old work before retiring the old provider configuration.
- Capture provider message IDs and immutable per-recipient acceptance entries with
  unique constraints. Duplicate callbacks/retries must never create another charge.
- Use UTC timestamps and explicit stored UTC period boundaries for subscription
  billing; display dates in the customer's timezone. Persist the rate version.
- Close periods idempotently with a unique subscription/period invoice reference;
  reconcile before finalization and carry late confirmations as labelled adjustments
  into the next open period. Corrections are credits/debits, not edited ledger history.

### Proposed persistent entities

| Entity | Minimum responsibility |
| --- | --- |
| EmailSubscription | Customer, lifecycle, provider reference, rate version, cycle, limits and switches |
| EmailSendingDomain | Tenant ownership, canonical name, provider account/zone/domain identity, DNS and verification state |
| EmailApiKey | Tenant, hashed secret, scopes, expiry/revocation and last-used timestamp |
| EmailMessage / recipient | Idempotency, digest, provider pin, safe metadata and recipient outcomes |
| EmailOutbox / reservation | Atomic admission, durable queue handoff, cap reservation and expiry |
| EmailProviderEvent | Authenticated deduplicated delivery/bounce/complaint events |
| EmailUsageLedger | Immutable accepted-recipient charges and explicit adjustments |
| EmailSuppression | Tenant recipient suppression and provider/account suppression references |
| EmailBillingPeriod | Usage/rate snapshot, reconciliation and one invoice linkage |

Choose exact Prisma names during implementation. All resource queries must enforce
customer ownership; provider identifiers supplied by clients cannot bypass it.
Prevent a domain being claimed by another customer while already active; define
an audited transfer/reverification process. Protect parent/subdomain ownership
relationships explicitly rather than relying on provider-wide identity inheritance.

### Suggested API surface

- Portal session: `/api/v1/me/email/subscription`, `/domains`, `/domains/:id/verify`,
  `/senders`, `/keys`, `/usage`, `/messages`, `/test-send`, `/settings` under that email prefix.
- Customer backend: `POST /api/v1/email/send` with scoped bearer key and idempotency key;
  `GET /api/v1/email/messages/:id` for status, limited to the key's tenant.
- Provider events: consume Cloudflare domain event subscriptions through Queues,
  using a scoped authenticated HTTP pull consumer or reviewed Worker bridge.
  Validate schema, deduplicate event IDs and acknowledge only after durable storage.
- Staff: provider readiness, customer approval/suspension, limits and audit views.

Cloudflare event subscriptions are domain scoped. Validate expected account,
zone, domain and stored message IDs before mapping events to a customer.
Handle delivered, deferred, bounced, failed, rejected and complained events.
Use scoped queue credentials and authenticated ingestion; never trust a payload's
customer ID. Confirm retention, retries, dead-letter handling and reconciliation
coverage during the adapter spike rather than assuming an SES-style webhook.

## 6. Ordered implementation TODO

### Phase 0 — agree the offer and isolate infrastructure

- [ ] Confirm transactional-only MVP, proposed price, cap, tax display and cancellation terms.
- [ ] Confirm provider commercial/resale terms and abuse responsibilities before selling.
- [ ] Choose a dedicated Kiwi Cloudflare account, Workers Paid setup, zone ownership,
      beta access, daily quotas and tenant reputation isolation; avoid sharing Membership24's live account/service.
- [ ] Record baseline provider/infrastructure/support cost and pilot success targets.
- [ ] Define retention/deletion rules and review customer terms/privacy for intended markets.

### Phase 1 — subscription, domain verification and switches

- [ ] Add tenant-owned schema/migrations and email contracts without changing mailbox behavior.
- [ ] Spike Cloudflare domain-management API coverage; implement supported onboarding/
      verification operations and document any dashboard-only steps honestly.
- [ ] Separate scoped DNS/domain-management tokens from restricted sending/queue tokens;
      encrypt credentials and never expose Cloudflare secrets to portal customers.
- [ ] Add customer, provider and global sending gates, preview mode and staff audit events.
- [ ] Add portal setup, verification statuses and Cloudflare DNS onboarding instructions.
- [ ] Enforce sender ownership, safe domain transfer and periodic verification checks.

### Phase 1a — client onboarding and account ownership

- [ ] Implement the Kiwi-managed Cloudflare account model with tenant/domain/zone mappings.
- [ ] Build add-domain → DNS migration review → nameserver instructions → activation status.
- [ ] Add migration checks for existing records, DNSSEC/DS and domains already in Cloudflare.
- [ ] Keep registrar ownership with the client and explain required registrar actions.
- [ ] Add guided email activation, Kiwi API-key creation, send example and test-send steps.
- [ ] Add customer help explaining managed DNS, email sending, billing and on/off behavior.
- [ ] Document DNS export, transfer/offboarding and cancellation without unrelated DNS deletion.
- [ ] Test pending/failed delegation, duplicate domain claims and safe resume after partial setup.
- [ ] Track customer-owned Cloudflare account connections as a later phase, not an MVP promise.

### Phase 1b — DNS API management

- [ ] Reuse the existing DNS adapter; fix pagination and record identity handling.
- [ ] Add tenant-scoped record CRUD routes and DNS screens with type validation.
- [ ] Add zone ownership mappings, scoped tokens and auditable before/after changes.
- [ ] Add email DNS preview/apply/recheck with conflict detection and idempotency.
- [ ] Test multiple TXT/MX records, more than 100 records, cross-tenant IDs, concurrent
      edits, API failures, protected records and preserved SPF/MX/DMARC settings.
- [ ] Document zone onboarding, nameserver migration and recovery from partial setup.

### Phase 2 — authenticated sending and feedback

- [ ] Add scoped hashed API keys with one-time reveal, rotation and revocation.
- [ ] Add validated API/test send, message-size/recipient limits and per-tenant rate limits.
- [ ] Implement durable outbox, atomic cap reservations and request idempotency.
- [ ] Implement Cloudflare REST dispatch with explicit accepted/rejected/unknown states and safe retries.
- [ ] Configure domain event subscriptions, Queues consumption and event deduplication.
- [ ] Suppress hard bounces/complaints before future dispatch, enforce provider suppression,
      and add conservative reputation alerts/automatic suspension thresholds for review.
- [ ] Add history, usage counts and test-send UI with explicit preview/live distinction.

### Phase 3 — usage billing and lifecycle

- [ ] Implement immutable per-recipient ledger, rate snapshots and budget alerts.
- [ ] Reconcile counts against provider evidence; alert on missing or unmatched events.
- [ ] Add existing invoice/payment integration with unique email billing-period linkage.
- [ ] Handle late events, credits, final usage, failed payment suspension and cancellation.
- [ ] Add itemized usage export, charge estimate and understandable invoice descriptions.

### Phase 4 — validate and pilot

- [ ] Verify tenant/key isolation, unverified/forged sender denial and key revocation.
- [ ] Verify customer/global/provider off also stops already queued work at dispatch.
- [ ] Test 1/3 recipients, partial acceptance, suppression, rejection and bounce billing rules.
- [ ] Test duplicate keys/events, worker crashes, provider timeout and no automatic failover.
- [ ] Test concurrent cap admission, rate rounding, period boundaries and repeated invoice jobs.
- [ ] Test webhook signature/replay/confirmation URL attacks and provider-account mismatch.
- [ ] Test Cloudflare zone onboarding, cross-account access boundaries, existing SPF/MX
      preservation, verification loss and DNS changes requiring customer action.
- [ ] Complete local mock-provider end-to-end setup → verify → send → event → invoice.
- [ ] Prepare an operational runbook for abuse, provider outage, unknown sends and rollback.
- [ ] Obtain specific live activation authorization before production configuration or real tests.
- [ ] Run the approved pilot, reconcile the first invoice cycle and decide whether to launch.

### Phase 5 — expand only after the Cloudflare pilot

- [ ] Review beta stability, account-level reputation exposure and quota increases.
- [ ] Validate customer-owned Cloudflare account connections if managed-account zones
      do not cover demand; document credential ownership and disconnection behavior.
- [ ] Consider SES/Mailgun only if customer demand or Cloudflare limitations justify it.
- [ ] Independently verify domains and test deliberate migration before any new provider.


## 7. Launch boundaries

No campaign builder, newsletter audience manager, dedicated IP offering, inbound
mail processing or customer SMTP gateway in the initial release. Consider these
only after validated demand. Keep message bodies out of routine logs; retain only
what dispatch needs, encrypted with a defined expiry. Redact BCC and recipient data
from unauthorized views. Do not promise inbox delivery or an SLA before measuring it.

This document authorizes no deployment, provider configuration changes or real
email sends. The referenced Membership24 repository also explicitly requires a
specific request before live actions. This task creates a plan only.