Skip to content

Email for professionals and teams

Add support for Resend + AWS SES

Hieu Nguyen (Jack)be1fe4e3fc87
diff --git a/CLAUDE.md b/CLAUDE.md
index 7c9930d..c07875f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -50,6 +50,16 @@ Composer: `src/components/compose/rich-text-editor.tsx` is a contentEditable HTM
Threading: `resolveThreadId` in `src/lib/email/threading.ts` files an inbound or imported message under the thread of the stored message its `In-Reply-To`/`References` name (matched against `providerMessageId` in the same mailbox); otherwise its own Message-ID seeds a new thread. Outbound replies carry `inReplyTo`/`references`/`threadId` from the draft, and a fresh send is keyed by the Message-ID Cloudflare returns. `/api/messages/[id]/thread` returns the conversation. Lists pass `group=thread` (the "conversation view" toggle, `use-conversation-view.ts`) to get one row per thread plus `threadMessageIds`, which row actions and bulk actions expand to.
+### Sending and receiving providers are per domain
+
+`domains.sending_provider` (`none | cloudflare | resend | ses`) and `domains.receiving_provider` (`none | cloudflare | resend | ses`, default `cloudflare`) are chosen independently on the Domains page; DNS stays on Cloudflare either way. They record intent: switching a provider never touches DNS, each provider's own Setup does, and a **Clean up** button removes the config of an unselected provider.
+
+- **Sending** goes through `sendThroughProvider` (`src/lib/email/outbound-provider.ts`), which `deliverEmail` and `sendSystemEmail` call after `getOutboundProviderConfig(env, from)` resolves the provider from the From domain (`none` throws). Cloudflare keeps its 5 MiB link fallback; Resend and SES take attachments directly. Resend and SES return different Message-IDs than we send, so `providerMessageId` stores the one replies will carry (`<[email protected]>` or `<[email protected]>` for SES).
+- **Receiving** from a non-Cloudflare provider enters through `intakeProviderMail` (`src/lib/email/provider-intake.ts`) and then the same `intakeIncomingMail` as everything else, once per recipient on a known domain. Providers cannot be rejected to after accepting, so reject and size limits drop the message, and `forward` is unavailable. Inbound endpoints are public and authenticate themselves: `/api/inbound/resend` verifies the Svix signature (`svix.ts`) with the secret Resend returned when `ensureWebhook` created the hook (`app_settings.resend_webhook_secret`), then fetches the raw MIME from `raw.download_url`; `/api/inbound/ses` is an SNS HTTPS endpoint guarded by a secret token in its URL, the topic ARN and reading the object from our own bucket.
+- **Only one MX owner per domain.** `publishMx` (`receiving-dns.ts`) refuses with `MxConflictError` (HTTP 409 `MX_CONFLICT`) when other MX records exist; the UI confirms and retries with `replaceMx`. Cloudflare Worker routes (`ensureMailboxDomainRouting`) are created only for domains whose receiving provider is `cloudflare`.
+- **Resend** keeps one key (`app_settings.resend_api_key`, or `RESEND_API_KEY`) and one Resend domain per hostname carrying both capabilities, so sending cleanup disables only `sending` when the domain still receives through Resend and vice versa. Apex MX values matching `inbound-smtp.*.amazonaws.com` are receiving records; everything else is sending.
+- **AWS** (`src/lib/aws/`) is a hand-rolled SigV4 client (`sigv4.ts`, verified against AWS's published vectors in `tests/provider-aws-resend.test.mjs`) so it runs on Workers and Node without the SDK. Credentials live in `app_settings.aws_config` (or `AWS_*` env vars) and are validated before saving by `validateAwsConfig`, which proves identity with STS then probes SES, SNS and S3, reporting each missing permission with the IAM policy that grants it. SES sending uses SESv2 (`ses.ts`); receipt rules exist only in SES v1 (Query protocol), so receiving uses `awsQuery`. `setupSesReceiving` creates the S3 bucket and policy, SNS topic, policy and HTTPS subscription, then a per-domain receipt rule in the account's active rule set (creating `mailflare-inbound` only when none is active), and the MX. State is in `app_settings.ses_receiving`. SES inbound exists only in some regions (`SES_RECEIVING_REGIONS`) and needs a public HTTPS `APP_URL`.
+
### Routing rules have two scopes
`routing_rules.scope` splits two genuinely different mechanisms, and mixing them up is the easy mistake:
diff --git a/drizzle/migrations/0051_add_outbound_provider.sql b/drizzle/migrations/0051_add_outbound_provider.sql
new file mode 100644
index 0000000..2e6d68d
--- /dev/null
+++ b/drizzle/migrations/0051_add_outbound_provider.sql
@@ -0,0 +1,3 @@
+ALTER TABLE `domains` ADD `sending_provider` text DEFAULT 'none' NOT NULL;--> statement-breakpoint
+UPDATE `domains` SET `sending_provider` = 'cloudflare' WHERE `sending_requested` = 1 OR `sending_enabled` = 1 OR `sending_subdomain_tag` IS NOT NULL;--> statement-breakpoint
+ALTER TABLE `app_settings` ADD `resend_api_key` text;
diff --git a/drizzle/migrations/0052_add_receiving_provider.sql b/drizzle/migrations/0052_add_receiving_provider.sql
new file mode 100644
index 0000000..946dd83
--- /dev/null
+++ b/drizzle/migrations/0052_add_receiving_provider.sql
@@ -0,0 +1,5 @@
+ALTER TABLE `domains` ADD `receiving_provider` text DEFAULT 'cloudflare' NOT NULL;--> statement-breakpoint
+ALTER TABLE `app_settings` ADD `aws_config` text;--> statement-breakpoint
+ALTER TABLE `app_settings` ADD `ses_receiving` text;--> statement-breakpoint
+ALTER TABLE `app_settings` ADD `resend_webhook_id` text;--> statement-breakpoint
+ALTER TABLE `app_settings` ADD `resend_webhook_secret` text;
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index 7cbf8dc..11b723f 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -302,6 +302,20 @@
"when": 1788850800014,
"tag": "0050_add_show_full_recipient_addresses",
"breakpoints": true
+ },
+ {
+ "idx": 43,
+ "version": "6",
+ "when": 1788850800015,
+ "tag": "0051_add_outbound_provider",
+ "breakpoints": true
+ },
+ {
+ "idx": 44,
+ "version": "6",
+ "when": 1788850800016,
+ "tag": "0052_add_receiving_provider",
+ "breakpoints": true
}
]
}
diff --git a/src/app/(admin)/domains/AwsCredentialsPanel.tsx b/src/app/(admin)/domains/AwsCredentialsPanel.tsx
new file mode 100644
index 0000000..98dc32d
--- /dev/null
+++ b/src/app/(admin)/domains/AwsCredentialsPanel.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import type { AwsCapabilityReport, AwsConfigStatus } from "@/lib/aws/aws-types";
+import { requestJson } from "./api";
+import { StatusRow } from "./status-row";
+
+type Props = {
+ /** Which capabilities the caller needs, so only those rows are shown. */
+ need: "sending" | "receiving";
+ onChanged?: (configured: boolean, report: AwsCapabilityReport | null) => void;
+};
+
+type PanelResponse = { status: AwsConfigStatus; policy: unknown };
+
+const REGION_HINTS = ["us-east-1", "us-east-2", "us-west-2", "eu-west-1", "eu-west-2", "eu-central-1", "ap-southeast-2", "ap-northeast-1", "ca-central-1"];
+
+/**
+ * AWS credentials shared by SES sending and receiving. Saving validates them
+ * with AWS (identity, then a harmless call per service) and lists any permission
+ * the key lacks, along with the IAM policy that grants everything.
+ */
+export default function AwsCredentialsPanel({ need, onChanged }: Props) {
+ const [status, setStatus] = useState<AwsConfigStatus | null>(null);
+ const [policy, setPolicy] = useState<unknown>(null);
+ const [report, setReport] = useState<AwsCapabilityReport | null>(null);
+ const [editing, setEditing] = useState(false);
+ const [accessKeyId, setAccessKeyId] = useState("");
+ const [secretAccessKey, setSecretAccessKey] = useState("");
+ const [region, setRegion] = useState("us-east-1");
+ const [busy, setBusy] = useState<"save" | "check" | "remove" | null>(null);
+ const [error, setError] = useState("");
+
+ useEffect(() => {
+ let active = true;
+ requestJson<PanelResponse>("/api/admin/aws", "GET")
+ .then(async (data) => {
+ if (!active) return;
+ setStatus(data.status);
+ setPolicy(data.policy);
+ if (data.status.region) setRegion(data.status.region);
+ if (!data.status.configured) { onChanged?.(false, null); return; }
+ const checked = await requestJson<{ report: AwsCapabilityReport }>("/api/admin/aws", "POST", {});
+ if (active) { setReport(checked.report); onChanged?.(true, checked.report); }
+ })
+ .catch((err) => { if (active) { setError(err instanceof Error ? err.message : "Could not load AWS settings"); setStatus((current) => current ?? { configured: false, source: null, region: null, accessKeyHint: null, accountId: null }); } });
+ return () => { active = false; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ async function run(kind: "save" | "check" | "remove", action: () => Promise<void>) {
+ setBusy(kind);
+ setError("");
+ try { await action(); } catch (err) { setError(err instanceof Error ? err.message : "Request failed"); } finally { setBusy(null); }
+ }
+
+ const save = () => run("save", async () => {
+ const data = await requestJson<{ status: AwsConfigStatus; report: AwsCapabilityReport }>("/api/admin/aws", "PUT", { accessKeyId, secretAccessKey, region });
+ setStatus(data.status);
+ setReport(data.report);
+ setEditing(false);
+ setSecretAccessKey("");
+ setAccessKeyId("");
+ onChanged?.(true, data.report);
+ });
+ const check = () => run("check", async () => {
+ const data = await requestJson<{ report: AwsCapabilityReport }>("/api/admin/aws", "POST", {});
+ setReport(data.report);
+ onChanged?.(true, data.report);
+ });
+ const remove = () => run("remove", async () => {
+ if (!window.confirm("Remove the AWS credentials? Domains using Amazon SES will stop sending and receiving. Resources already created in AWS are left in place.")) return;
+ const data = await requestJson<{ status: AwsConfigStatus }>("/api/admin/aws", "DELETE", {});
+ setStatus(data.status);
+ setReport(null);
+ onChanged?.(false, null);
+ });
+
+ const configured = !!status?.configured;
+ const showForm = status !== null && (!configured || editing);
+ const fromEnvironment = status?.source === "environment";
+
+ return (
+ <div className="space-y-2">
+ <ul className="space-y-2">
+ <StatusRow
+ ok={configured && !editing}
+ title="AWS credentials"
+ hint="Shared by every domain using Amazon SES"
+ action={configured && !editing ? (
+ <>
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => void check()}>{busy === "check" ? "Checking…" : "Re-check"}</Button>
+ {!fromEnvironment && <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => setEditing(true)}>Replace</Button>}
+ {!fromEnvironment && <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => void remove()}>Remove</Button>}
+ </>
+ ) : undefined}
+ >
+ {showForm ? (
+ <form className="grid gap-2" onSubmit={(event) => { event.preventDefault(); void save(); }}>
+ <Input autoComplete="off" placeholder="Access key ID (AKIA…)" value={accessKeyId} onChange={(event) => setAccessKeyId(event.target.value)} className="max-w-sm bg-white" />
+ <Input type="password" autoComplete="off" placeholder="Secret access key" value={secretAccessKey} onChange={(event) => setSecretAccessKey(event.target.value)} className="max-w-sm bg-white" />
+ <Input list="aws-regions" placeholder="Region (us-east-1)" value={region} onChange={(event) => setRegion(event.target.value)} className="max-w-[12rem] bg-white" />
+ <datalist id="aws-regions">{REGION_HINTS.map((hint) => <option key={hint} value={hint} />)}</datalist>
+ <span className="flex gap-2">
+ <Button type="submit" size="sm" disabled={!accessKeyId.trim() || !secretAccessKey.trim() || !region.trim() || busy !== null}>{busy === "save" ? "Validating…" : "Validate and save"}</Button>
+ {editing && <Button type="button" size="sm" variant="outline" className="bg-white" onClick={() => { setEditing(false); setError(""); }}>Cancel</Button>}
+ </span>
+ </form>
+ ) : configured ? `Access key …${status?.accessKeyHint} · ${status?.region}${status?.accountId ? ` · account ${status.accountId}` : ""}${fromEnvironment ? " · from environment" : ""}` : "Checking…"}
+ </StatusRow>
+
+ {configured && !editing && report && need === "sending" && (
+ <StatusRow ok={report.sending} title="SES sending" hint="Send mail and manage sender identities">
+ {report.sending ? `Allowed in ${report.region}` : "Missing SES permissions"}
+ </StatusRow>
+ )}
+ {configured && !editing && report?.sending && report.productionAccess === false && need === "sending" && (
+ <StatusRow ok={false} title="SES sandbox" hint="New AWS accounts start restricted">
+ Only verified recipients can receive mail until you request production access in the SES console.
+ </StatusRow>
+ )}
+ {configured && !editing && report && need === "receiving" && (
+ <>
+ <StatusRow ok={report.receivingRegion && report.receiving} title="SES receiving" hint="Receipt rules for inbound mail">
+ {!report.receivingRegion ? `${report.region} cannot receive mail. Use us-east-1, us-west-2 or eu-west-1.` : report.receiving ? `Allowed in ${report.region}` : "Missing SES receipt-rule permissions"}
+ </StatusRow>
+ <StatusRow ok={report.s3} title="S3" hint="Bucket where SES stores raw messages">{report.s3 ? "Allowed" : "Missing S3 permissions"}</StatusRow>
+ <StatusRow ok={report.sns} title="SNS" hint="Notifies Mailflare of each message">{report.sns ? "Allowed" : "Missing SNS permissions"}</StatusRow>
+ </>
+ )}
+ </ul>
+ {configured && !editing && report && report.missing.length > 0 && (
+ <details className="rounded-lg bg-white px-3 py-2 text-xs text-neutral-600">
+ <summary className="cursor-pointer font-medium text-neutral-800">Missing permissions and the IAM policy that grants them</summary>
+ <p className="mt-2">Missing: {report.missing.join(", ")}</p>
+ <pre className="mt-2 max-h-64 overflow-auto rounded bg-neutral-50 p-2">{JSON.stringify(policy, null, 2)}</pre>
+ </details>
+ )}
+ {showForm && (
+ <p className="text-xs text-neutral-500">
+ Create an IAM user with programmatic access in the AWS console and attach a policy with the permissions Mailflare needs (shown after you save, if any are missing). Credentials are checked with AWS before they are stored.
+ </p>
+ )}
+ {error && <p role="alert" className="text-xs text-red-600">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/app/(admin)/domains/CloudflareReceivingConfig.tsx b/src/app/(admin)/domains/CloudflareReceivingConfig.tsx
new file mode 100644
index 0000000..4198bae
--- /dev/null
+++ b/src/app/(admin)/domains/CloudflareReceivingConfig.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { runReceivingSetup } from "./api";
+import { StatusRow } from "./status-row";
+
+type Props = {
+ domainId: string;
+ routingOk: boolean;
+ routingLabel: string;
+ manual: boolean;
+ onChanged?: () => void;
+};
+
+/** Email Routing status for the zone, with a setup that also deals with conflicting MX records. */
+export default function CloudflareReceivingConfig({ domainId, routingOk, routingLabel, manual, onChanged }: Props) {
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+
+ async function setup() {
+ setBusy(true);
+ setError("");
+ try {
+ if (await runReceivingSetup(domainId, "cloudflare")) onChanged?.();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Setup failed");
+ } finally { setBusy(false); }
+ }
+
+ return (
+ <div className="space-y-2">
+ <ul className="space-y-2">
+ <StatusRow
+ ok={routingOk}
+ title="Email Routing"
+ hint="Routes incoming email to Mailflare"
+ action={!routingOk ? (
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy || manual} title={manual ? "DNS for this domain is managed manually" : undefined} onClick={() => void setup()}>
+ {busy ? "Setting up…" : "Setup"}
+ </Button>
+ ) : undefined}
+ >
+ {routingLabel}
+ </StatusRow>
+ </ul>
+ {error && <p role="alert" className="text-xs text-red-600">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/app/(admin)/domains/DomainDnsDetails.tsx b/src/app/(admin)/domains/DomainDnsDetails.tsx
index 730dad5..743db79 100644
--- a/src/app/(admin)/domains/DomainDnsDetails.tsx
+++ b/src/app/(admin)/domains/DomainDnsDetails.tsx
@@ -1,7 +1,10 @@
-import { AlertTriangle, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { dnsAuthDescriptions, dnsAuthRecords, getDnsAuthItemClass, getDnsAuthStatusLabel } from "./utils";
-import type { DomainDnsDetailsProps } from "./types";
+import { dnsAuthDescriptions, getDnsAuthItemClass } from "./utils";
+import { ROW_GRID, StatusBadge, StatusRow } from "./status-row";
+import CloudflareReceivingConfig from "./CloudflareReceivingConfig";
+import ReceivingSetupSection from "./ReceivingSetupSection";
+import SendingSetupSection from "./SendingSetupSection";
+import type { DnsAuthRecord, DomainDnsDetailsProps } from "./types";
export default function DomainDnsDetails({
domain,
@@ -9,6 +12,13 @@ export default function DomainDnsDetails({
onSetup,
setupRecord,
setupMessage,
+ onSendingProviderChange,
+ sendingProviderBusy,
+ sendingProviderMessage,
+ onReceivingProviderChange,
+ receivingProviderBusy,
+ receivingProviderMessage,
+ onDnsChanged,
}: DomainDnsDetailsProps) {
const audit = dns.audit;
const manual = domain.zoneId === "manual";
@@ -27,97 +37,57 @@ export default function DomainDnsDetails({
: dns.routing.missing.length > 0
? `${dns.routing.missing.length} DNS record${dns.routing.missing.length === 1 ? "" : "s"} missing`
: "No routing DNS records found";
+
+ const auditRow = (record: DnsAuthRecord) => {
+ if (!audit) return null;
+ const item = audit[record];
+ const ok = item.status === "ok";
+ return (
+ <li key={record} className={`${ROW_GRID} ${getDnsAuthItemClass(item.status)}`}>
+ <StatusBadge ok={ok} tone={item.status === "missing" ? "red" : "neutral"} />
+ <span className="min-w-0">
+ <span className="block font-medium text-neutral-900">{item.label} record</span>
+ <span className="block text-xs text-neutral-500">{dnsAuthDescriptions[record]}</span>
+ </span>
+ {ok ? (
+ <span className="min-w-0 break-all text-neutral-500">{item.found.length > 0 ? item.found.join(", ") : item.name}</span>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0 bg-white"
+ disabled={manual || setupRecord === record}
+ title={manual ? "DNS for this domain is managed manually" : `Create the ${item.label} record`}
+ onClick={() => onSetup?.(record)}
+ >
+ {setupRecord === record ? "Setting up..." : "Setup"}
+ </Button>
+ )}
+ </li>
+ );
+ };
+
+ const cloudflareConfig = (
+ <ul className="space-y-2">
+ <StatusRow ok={!!sendingOk} title="Email Sending" hint="Sends outgoing email from this domain">{sendingLabel}</StatusRow>
+ {auditRow("dkim")}
+ </ul>
+ );
+
+ const cloudflareReceiving = (
+ <CloudflareReceivingConfig domainId={domain.id} routingOk={routingOk} routingLabel={routingLabel} manual={manual} onChanged={onDnsChanged} />
+ );
+
return (
<div className="px-4 pb-4 pt-4 sm:px-5 sm:pb-5">
{audit && (
<section>
<h2 className="text-base font-semibold text-neutral-900">Domain setup</h2>
<p className="mt-0.5 text-sm text-neutral-500">
- Review routing, sending, and DNS authentication for reliable email delivery.
+ Review the DNS authentication that keeps mail deliverable, whichever services send and receive it.
</p>
<ul className="mt-3 space-y-2">
- <li
- className={`grid gap-3 rounded-xl px-4 py-3 text-sm sm:grid-cols-[auto_minmax(8rem,14rem)_minmax(0,1fr)_auto] sm:items-start ${routingOk ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}
- >
- {routingOk ? (
- <span className="flex h-7 w-7 items-center justify-center rounded-full bg-green-600 text-white">
- <Check className="h-4 w-4" />
- </span>
- ) : (
- <span className="flex h-7 w-7 items-center justify-center rounded-full bg-white/70">
- <AlertTriangle className="h-4 w-4 text-red-600" />
- </span>
- )}
- <span className="min-w-0">
- <span className="block font-medium text-neutral-900">Email Routing</span>
- <span className="block text-xs text-neutral-500">Routes incoming email to Mailflare</span>
- </span>
- <span className="min-w-0 break-all text-neutral-500">{routingLabel}</span>
- </li>
-
- <li
- className={`grid gap-3 rounded-xl px-4 py-3 text-sm sm:grid-cols-[auto_minmax(8rem,14rem)_minmax(0,1fr)_auto] sm:items-start ${sendingOk ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}
- >
- {sendingOk ? (
- <span className="flex h-7 w-7 items-center justify-center rounded-full bg-green-600 text-white">
- <Check className="h-4 w-4" />
- </span>
- ) : (
- <span className="flex h-7 w-7 items-center justify-center rounded-full bg-white/70">
- <AlertTriangle className="h-4 w-4 text-red-600" />
- </span>
- )}
- <span className="min-w-0">
- <span className="block font-medium text-neutral-900">Email Sending</span>
- <span className="block text-xs text-neutral-500">Sends outgoing email from this domain</span>
- </span>
- <span className="min-w-0 break-all text-neutral-500">{sendingLabel}</span>
- </li>
-
- {dnsAuthRecords.map((record) => {
- const item = audit[record];
- const ok = item.status === "ok";
-
- return (
- <li
- key={record}
- className={`grid gap-3 rounded-xl px-4 py-3 text-sm sm:grid-cols-[auto_minmax(8rem,14rem)_minmax(0,1fr)_auto] sm:items-start ${getDnsAuthItemClass(item.status)}`}
- >
- {ok ? (
- <span className="flex h-7 w-7 items-center justify-center rounded-full bg-green-600 text-white">
- <Check className="h-4 w-4" />
- </span>
- ) : (
- <span className="flex h-7 w-7 items-center justify-center rounded-full bg-white/70">
- <AlertTriangle className={`h-4 w-4 ${item.status === "missing" ? "text-red-600" : "text-neutral-400"}`} />
- </span>
- )}
- <span className="min-w-0">
- <span className="block font-medium text-neutral-900">{item.label} record</span>
- <span className="block text-xs text-neutral-500">{dnsAuthDescriptions[record]}</span>
- </span>
-
- {ok ? <span className="min-w-0 break-all text-neutral-500">
- {item.found.length > 0 ? item.found.join(", ") : item.name}
- </span> : (
- <Button
- variant="outline"
- size="sm"
- className="shrink-0 bg-white"
- disabled={manual || setupRecord === record}
- title={
- manual
- ? "DNS for this domain is managed manually"
- : `Create the ${item.label} record`
- }
- onClick={() => onSetup?.(record)}
- >
- {setupRecord === record ? "Setting up..." : "Setup"}
- </Button>
- )}
- </li>
- );
- })}
+ {(["mx", "spf", "dmarc"] as DnsAuthRecord[]).map(auditRow)}
</ul>
{manual && (
<p className="text-xs text-neutral-500">
@@ -128,6 +98,22 @@ export default function DomainDnsDetails({
{setupMessage && <p className="text-xs text-red-600">{setupMessage}</p>}
</section>
)}
+ <ReceivingSetupSection
+ domain={domain}
+ onChange={onReceivingProviderChange}
+ busy={receivingProviderBusy}
+ message={receivingProviderMessage}
+ cloudflareConfig={cloudflareReceiving}
+ cloudflareOk={routingOk}
+ />
+ <SendingSetupSection
+ domain={domain}
+ onChange={onSendingProviderChange}
+ busy={sendingProviderBusy}
+ message={sendingProviderMessage}
+ cloudflareConfig={cloudflareConfig}
+ cloudflareOk={!!sendingOk && audit?.dkim.status === "ok"}
+ />
</div>
);
}
diff --git a/src/app/(admin)/domains/DomainItemCard.tsx b/src/app/(admin)/domains/DomainItemCard.tsx
index 3a54fef..1e67d7f 100644
--- a/src/app/(admin)/domains/DomainItemCard.tsx
+++ b/src/app/(admin)/domains/DomainItemCard.tsx
@@ -27,6 +27,13 @@ export default function DomainItemCard({
item,
dns,
dnsDetails,
+ onSendingProviderChange,
+ sendingProviderBusy,
+ sendingProviderMessage,
+ onReceivingProviderChange,
+ receivingProviderBusy,
+ receivingProviderMessage,
+ onDnsChanged,
dnsLoading = false,
dnsError,
expanded = false,
@@ -64,20 +71,41 @@ export default function DomainItemCard({
<StatusIcon ok={item.status === "active"} className="h-3 w-3" />
{item.status}
</Badge>
- <Badge
- variant={item.routingEnabled ? "outline" : "secondary"}
- className={cn("gap-1", !item.routingEnabled && "opacity-50")}
- >
- <StatusIcon ok={item.routingEnabled} className="h-3 w-3" />
- routing
- </Badge>
- <Badge
- variant={item.sendingEnabled ? "outline" : "secondary"}
- className={cn("gap-1", !item.sendingEnabled && "opacity-50")}
- >
- <StatusIcon ok={item.sendingEnabled} className="h-3 w-3" />
- sending
- </Badge>
+ {item.receivingProvider === "cloudflare" ? (
+ <Badge
+ variant={item.routingEnabled ? "outline" : "secondary"}
+ className={cn("gap-1", !item.routingEnabled && "opacity-50")}
+ >
+ <StatusIcon ok={item.routingEnabled} className="h-3 w-3" />
+ routing
+ </Badge>
+ ) : item.receivingProvider === "none" ? (
+ <Badge variant="secondary" className="gap-1 opacity-50">
+ sending only
+ </Badge>
+ ) : (
+ <Badge variant="outline" className="gap-1">
+ receiving via {item.receivingProvider === "ses" ? "Amazon SES" : "Resend"}
+ </Badge>
+ )}
+ {item.sendingProvider === "resend" || item.sendingProvider === "ses" ? (
+ <Badge variant="outline" className="gap-1">
+ <StatusIcon ok className="h-3 w-3" />
+ sending via {item.sendingProvider === "ses" ? "Amazon SES" : "Resend"}
+ </Badge>
+ ) : item.sendingProvider === "none" ? (
+ <Badge variant="secondary" className="gap-1 opacity-50">
+ receiving only
+ </Badge>
+ ) : (
+ <Badge
+ variant={item.sendingEnabled ? "outline" : "secondary"}
+ className={cn("gap-1", !item.sendingEnabled && "opacity-50")}
+ >
+ <StatusIcon ok={item.sendingEnabled} className="h-3 w-3" />
+ sending
+ </Badge>
+ )}
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
@@ -121,6 +149,13 @@ export default function DomainItemCard({
<DomainDnsDetails
domain={item}
dns={dnsDetails}
+ onSendingProviderChange={onSendingProviderChange}
+ sendingProviderBusy={sendingProviderBusy}
+ sendingProviderMessage={sendingProviderMessage}
+ onReceivingProviderChange={onReceivingProviderChange}
+ receivingProviderBusy={receivingProviderBusy}
+ receivingProviderMessage={receivingProviderMessage}
+ onDnsChanged={onDnsChanged}
onSetup={onSetup}
setupRecord={setupRecord}
setupMessage={setupMessage}
diff --git a/src/app/(admin)/domains/ProviderCard.tsx b/src/app/(admin)/domains/ProviderCard.tsx
new file mode 100644
index 0000000..1423aba
--- /dev/null
+++ b/src/app/(admin)/domains/ProviderCard.tsx
@@ -0,0 +1,45 @@
+import type { ReactNode } from "react";
+import { AlertTriangle, Check } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+
+type Props = {
+ title: string;
+ description: string;
+ /** true = set up, false = needs setup, null = unknown or not applicable (no icon). */
+ ok: boolean | null;
+ selected: boolean;
+ disabled?: boolean;
+ onToggle: (on: boolean) => void;
+ /** Configuration shown while the option is selected. */
+ children?: ReactNode;
+ /** Shown on an unselected option that still has configuration. */
+ cleanup?: { present: boolean; busy: boolean; disabled?: boolean; onClick: () => void } | null;
+};
+
+/** One selectable provider: icon-left header with a switch, its config when on, a clean-up bar when off but configured. */
+export default function ProviderCard({ title, description, ok, selected, disabled, onToggle, children, cleanup }: Props) {
+ return (
+ <li className="rounded-xl bg-neutral-50 px-4 py-3 text-sm">
+ <div className="flex items-center justify-between gap-3">
+ {ok !== null && (ok
+ ? <span title="Set up" className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-green-600 text-white"><Check className="h-4 w-4" /></span>
+ : <span title="Needs setup" className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-amber-100"><AlertTriangle className="h-4 w-4 text-amber-600" /></span>)}
+ <span className="min-w-0 flex-1">
+ <span className="block font-medium text-neutral-900">{title}</span>
+ <span className="block text-xs text-neutral-500">{description}</span>
+ </span>
+ <Switch aria-label={title} checked={selected} disabled={disabled} onCheckedChange={onToggle} />
+ </div>
+ {selected && children && <div className="mt-3 border-t border-neutral-200 pt-3">{children}</div>}
+ {!selected && cleanup?.present && (
+ <div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t border-neutral-200 pt-3 text-xs text-neutral-500">
+ <span>{title} is still set up for this domain but not used.</span>
+ <Button size="sm" variant="outline" className="bg-white" disabled={cleanup.busy || cleanup.disabled} onClick={cleanup.onClick}>
+ {cleanup.busy ? "Removing…" : "Clean up"}
+ </Button>
+ </div>
+ )}
+ </li>
+ );
+}
diff --git a/src/app/(admin)/domains/ReceivingProviderConfig.tsx b/src/app/(admin)/domains/ReceivingProviderConfig.tsx
new file mode 100644
index 0000000..98d0ad3
--- /dev/null
+++ b/src/app/(admin)/domains/ReceivingProviderConfig.tsx
@@ -0,0 +1,104 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import type { ReceivingStep } from "@/lib/aws/ses-receiving-types";
+import AwsCredentialsPanel from "./AwsCredentialsPanel";
+import ResendKeyRow from "./ResendKeyRow";
+import { requestJson, runReceivingSetup } from "./api";
+import { StatusRow } from "./status-row";
+
+type ViewResponse = {
+ credentials?: boolean;
+ view?: { steps: ReceivingStep[]; ready: boolean; mx: string | null; restrictedKey?: boolean } | null;
+ error?: string;
+};
+
+type Props = {
+ domainId: string;
+ provider: "resend" | "ses";
+ /** Reports whether the provider is fully ready (null while unknown). */
+ onReady?: (ready: boolean | null) => void;
+};
+
+const COPY = {
+ resend: { setup: "Setup receiving", hint: "Enables receiving on the domain, points MX at Resend and registers the webhook." },
+ ses: { setup: "Setup receiving", hint: "Creates the S3 bucket, SNS topic and receipt rule, then points MX at SES." },
+} as const;
+
+/** Checklist and setup button for receiving through Resend or Amazon SES. */
+export default function ReceivingProviderConfig({ domainId, provider, onReady }: Props) {
+ const [credentials, setCredentials] = useState<boolean | null>(null);
+ const [view, setView] = useState<ViewResponse["view"]>(null);
+ const [loading, setLoading] = useState(true);
+ const [reload, setReload] = useState(0);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [notice, setNotice] = useState("");
+
+ useEffect(() => {
+ let active = true;
+ requestJson<ViewResponse & { keyConfigured?: boolean }>(`/api/domains/${domainId}/receiving/${provider}`, "GET")
+ .then((data) => {
+ if (!active) return;
+ // Resend has no separate credentials call: the key is the first step of its checklist.
+ const keyStep = data.view?.steps.find((step) => step.key === "key");
+ setCredentials(provider === "resend" && keyStep ? keyStep.ok : (data.credentials ?? true));
+ setView(data.view ?? null);
+ setError(data.error ?? "");
+ })
+ .catch((err) => { if (active) setError(err instanceof Error ? err.message : "Could not reach the provider"); })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [domainId, provider, reload]);
+
+ useEffect(() => { if (!loading) onReady?.(view ? view.ready : credentials === false ? false : null); }, [loading, view, credentials, onReady]);
+
+ const refresh = useCallback(() => { setLoading(true); setReload((value) => value + 1); }, []);
+
+ async function setup() {
+ setBusy(true);
+ setError("");
+ setNotice("");
+ try {
+ const done = await runReceivingSetup(domainId, provider);
+ if (done) setNotice("Setup finished. It can take a few minutes for DNS to propagate; use Check again to refresh.");
+ refresh();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Setup failed");
+ } finally { setBusy(false); }
+ }
+
+ const needsSetup = !!view && !view.ready;
+ return (
+ <div className="space-y-2">
+ {provider === "ses"
+ ? <AwsCredentialsPanel need="receiving" onChanged={(configured) => { setCredentials(configured); refresh(); }} />
+ : (
+ <ul className="space-y-2">
+ <ResendKeyRow configured={credentials} onChanged={(configured) => { setCredentials(configured); refresh(); }} onError={setError} />
+ </ul>
+ )}
+ {credentials && (
+ <ul className="space-y-2">
+ {loading && !view && <li className="list-none text-sm text-neutral-500">Checking…</li>}
+ {view?.steps.filter((step) => provider !== "resend" || step.key !== "key").map((step) => (
+ <StatusRow key={step.key} ok={step.ok} title={step.label} hint="">{step.detail ?? (step.ok ? "OK" : "Not set up")}</StatusRow>
+ ))}
+ </ul>
+ )}
+ {credentials && view?.restrictedKey && <p className="text-xs text-neutral-500">This Resend key can only send mail, so Mailflare can&apos;t set up receiving. Use a full-access key, or enable receiving, add the MX record and create the <code>email.received</code> webhook in the Resend dashboard.</p>}
+ {credentials && !view?.restrictedKey && (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="text-xs text-neutral-500">{COPY[provider].hint}</p>
+ <span className="flex gap-2">
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy || loading} onClick={refresh}>{loading ? "Checking…" : "Check again"}</Button>
+ {needsSetup && <Button size="sm" disabled={busy || loading} onClick={() => void setup()}>{busy ? "Working…" : COPY[provider].setup}</Button>}
+ </span>
+ </div>
+ )}
+ {notice && <p role="status" className="text-xs text-green-700">{notice}</p>}
+ {error && <p role="alert" className="text-xs text-red-600">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/app/(admin)/domains/ReceivingSetupSection.tsx b/src/app/(admin)/domains/ReceivingSetupSection.tsx
new file mode 100644
index 0000000..e70f43e
--- /dev/null
+++ b/src/app/(admin)/domains/ReceivingSetupSection.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { useEffect, useState, type ReactNode } from "react";
+import { requestJson } from "./api";
+import ProviderCard from "./ProviderCard";
+import ReceivingProviderConfig from "./ReceivingProviderConfig";
+import type { Domain, ReceivingProvider } from "./types";
+
+type Option = Exclude<ReceivingProvider, "none">;
+type Present = Record<Option, boolean | null>;
+
+const OPTIONS: { id: Option; title: string; description: string }[] = [
+ { id: "cloudflare", title: "Cloudflare Email Routing", description: "Mail arrives through this domain's Cloudflare zone. The default." },
+ { id: "resend", title: "Resend", description: "Resend receives mail and delivers it to Mailflare by webhook." },
+ { id: "ses", title: "Amazon SES", description: "SES receives mail into S3 and notifies Mailflare." },
+];
+
+type Props = {
+ domain: Domain;
+ onChange?: (provider: ReceivingProvider) => void;
+ busy?: boolean;
+ message?: string | null;
+ /** Cloudflare routing status and setup, rendered by the parent that owns the DNS view. */
+ cloudflareConfig: ReactNode;
+ cloudflareOk: boolean;
+};
+
+export default function ReceivingSetupSection({ domain, onChange, busy, message, cloudflareConfig, cloudflareOk }: Props) {
+ const [present, setPresent] = useState<Present>({ cloudflare: null, resend: null, ses: null });
+ const [ready, setReady] = useState<Record<"resend" | "ses", boolean | null>>({ resend: null, ses: null });
+ const [reload, setReload] = useState(0);
+ const [removing, setRemoving] = useState<Option | null>(null);
+ const [error, setError] = useState("");
+
+ useEffect(() => {
+ let active = true;
+ requestJson<Present>(`/api/domains/${domain.id}/receiving`, "GET")
+ .then((data) => { if (active) setPresent({ cloudflare: data.cloudflare ?? null, resend: data.resend ?? null, ses: data.ses ?? null }); })
+ .catch(() => { if (active) setPresent({ cloudflare: null, resend: null, ses: null }); });
+ return () => { active = false; };
+ }, [domain.id, domain.receivingProvider, reload]);
+
+ async function cleanUp(option: Option, title: string) {
+ if (!window.confirm(`Remove the ${title} receiving setup for ${domain.hostname}? This deletes its MX record and routing, so mail will not arrive through it.`)) return;
+ setRemoving(option);
+ setError("");
+ try {
+ await requestJson(`/api/domains/${domain.id}/receiving`, "DELETE", { target: option });
+ setReload((value) => value + 1);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not remove configuration");
+ } finally { setRemoving(null); }
+ }
+
+ return (
+ <section className="mt-6">
+ <h2 className="text-base font-semibold text-neutral-900">Setup receiving email</h2>
+ <p className="mt-0.5 text-sm text-neutral-500">
+ Choose what receives mail for this domain. Only one service can own the MX record; setting up another asks before replacing it.
+ </p>
+ <ul className="mt-3 space-y-2">
+ {OPTIONS.map((option) => {
+ const selected = domain.receivingProvider === option.id;
+ const ok = !selected ? null : option.id === "cloudflare" ? cloudflareOk : ready[option.id];
+ return (
+ <ProviderCard
+ key={option.id}
+ title={option.title}
+ description={option.description}
+ ok={ok}
+ selected={selected}
+ disabled={busy}
+ onToggle={(on) => onChange?.(on ? option.id : "none")}
+ cleanup={{ present: !!present[option.id], busy: removing === option.id, disabled: removing !== null, onClick: () => void cleanUp(option.id, option.title) }}
+ >
+ {option.id === "cloudflare"
+ ? cloudflareConfig
+ : <ReceivingProviderConfig domainId={domain.id} provider={option.id} onReady={(value) => setReady((current) => current[option.id as "resend" | "ses"] === value ? current : { ...current, [option.id]: value })} />}
+ </ProviderCard>
+ );
+ })}
+ </ul>
+ {domain.receivingProvider === "none" && <p className="mt-2 text-xs text-neutral-500">No receiving service selected: this domain only sends.</p>}
+ {message && <p className="mt-2 text-xs text-red-600">{message}</p>}
+ {error && <p role="alert" className="mt-2 text-xs text-red-600">{error}</p>}
+ </section>
+ );
+}
diff --git a/src/app/(admin)/domains/ResendDomainSection.tsx b/src/app/(admin)/domains/ResendDomainSection.tsx
new file mode 100644
index 0000000..cc23e3e
--- /dev/null
+++ b/src/app/(admin)/domains/ResendDomainSection.tsx
@@ -0,0 +1,152 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { authFetch } from "@/lib/auth/client";
+import type { ResendDomainView } from "@/lib/domains/resend-domain-types";
+import ResendKeyRow from "./ResendKeyRow";
+import { StatusRow } from "./status-row";
+
+type ResendResponse = { keyConfigured?: boolean; canManageDomains?: boolean; resend?: ResendDomainView | null; error?: string };
+
+async function postJson<T>(url: string, method: string, body: unknown): Promise<T> {
+ const response = await authFetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ const data = (await response.json()) as T & { error?: string };
+ if (!response.ok) throw new Error(data.error ?? "Request failed");
+ return data;
+}
+
+export default function ResendDomainSection({ domainId, onStatus }: { domainId: string; onStatus?: (status: string | null) => void }) {
+ const [keyConfigured, setKeyConfigured] = useState<boolean | null>(null);
+ const [view, setView] = useState<ResendDomainView | null>(null);
+ const [canManage, setCanManage] = useState(true);
+ const [loading, setLoading] = useState(true);
+ const [reload, setReload] = useState(0);
+ const [busy, setBusy] = useState<"setup" | "verify" | "test" | null>(null);
+ const [error, setError] = useState("");
+ const [notice, setNotice] = useState("");
+
+ useEffect(() => {
+ let active = true;
+ authFetch(`/api/domains/${domainId}/resend`, { cache: "no-store" })
+ .then(async (response) => ({ response, data: (await response.json()) as ResendResponse }))
+ .then(({ response, data }) => {
+ if (!active) return;
+ if (!response.ok && data.keyConfigured === undefined) throw new Error(data.error ?? "Could not reach Resend");
+ setKeyConfigured(data.keyConfigured ?? true);
+ setCanManage(data.canManageDomains ?? true);
+ setView(data.resend ?? null);
+ setError(response.ok ? "" : data.error ?? "");
+ })
+ .catch((err) => { if (active) { setKeyConfigured(true); setError(err instanceof Error ? err.message : "Could not reach Resend"); } })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [domainId, reload]);
+
+ useEffect(() => {
+ if (loading) return;
+ onStatus?.(keyConfigured === false ? "no_key" : canManage ? (view?.status ?? null) : null);
+ }, [loading, keyConfigured, canManage, view, onStatus]);
+
+ async function run(kind: "setup" | "verify" | "test", action: () => Promise<void>) {
+ setBusy(kind);
+ setError("");
+ setNotice("");
+ try { await action(); }
+ catch (err) { setError(err instanceof Error ? err.message : "Request failed"); }
+ finally { setBusy(null); }
+ }
+
+ const domainAction = (action: "setup" | "verify") => run(action, async () => {
+ const data = await postJson<ResendResponse>(`/api/domains/${domainId}/resend`, "POST", { action });
+ setView(data.resend ?? null);
+ });
+ const sendTest = () => run("test", async () => {
+ const data = await postJson<{ to: string }>(`/api/domains/${domainId}/resend`, "POST", { action: "test" });
+ setNotice(`Test email sent to ${data.to}`);
+ });
+
+ const verified = view?.status === "verified";
+ const needsFullKey = "Needs a full-access Resend API key";
+ const domainLabel = loading
+ ? "Checking Resend…"
+ : !canManage
+ ? "Cannot check: this key can only send mail"
+ : !view
+ ? "Could not read the domain from Resend"
+ : verified
+ ? "Domain verified in Resend"
+ : view.registered
+ ? view.missingDns === 0
+ ? `DNS records added, waiting for Resend to verify (${view.status.replace(/_/g, " ")})`
+ : view.missingDns
+ ? `${view.missingDns} DNS record${view.missingDns === 1 ? "" : "s"} missing in Cloudflare`
+ : `DNS check: ${view.status.replace(/_/g, " ")}`
+ : "Domain is not added to Resend yet";
+ const domainButton = !canManage
+ ? "Setup domain"
+ : !view
+ ? null
+ : view.registered && !view.dnsManaged
+ ? "Verify"
+ : !view.registered
+ ? view.dnsManaged ? "Setup domain and DNS" : "Setup domain"
+ : view.dnsManaged && view.missingDns !== 0
+ ? "Create missing DNS and verify"
+ : "Check status";
+
+ return (
+ <div className="space-y-2">
+ <ul className="space-y-2">
+ <ResendKeyRow
+ configured={keyConfigured}
+ onChanged={(configured) => { setKeyConfigured(configured); if (!configured) setView(null); setLoading(true); setReload((value) => value + 1); }}
+ onError={setError}
+ />
+
+ {keyConfigured && (
+ <StatusRow
+ ok={verified}
+ title="Domain"
+ hint="Verified sender domain in Resend"
+ action={verified ? (
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => void sendTest()}>{busy === "test" ? "Sending…" : "Send test email"}</Button>
+ ) : domainButton && !loading ? (
+ <Button
+ size="sm"
+ variant="outline"
+ className="bg-white"
+ disabled={!canManage || busy !== null}
+ title={canManage ? undefined : needsFullKey}
+ onClick={() => void domainAction(view?.registered && (!view.dnsManaged || view.missingDns === 0) ? "verify" : "setup")}
+ >
+ {busy === "verify" ? "Checking…" : busy === "setup" ? "Working…" : domainButton}
+ </Button>
+ ) : undefined}
+ >
+ {domainLabel}
+ </StatusRow>
+ )}
+ </ul>
+
+ {!loading && !canManage && keyConfigured && <p className="text-xs text-neutral-500">Add this domain at resend.com/domains and create the DNS records it shows, then send a test email. Or replace the key with a full-access one so Mailflare can set it up.</p>}
+ {view && view.registered && !verified && !view.dnsManaged && <p className="text-xs text-neutral-500">Add these records where this domain&apos;s DNS is hosted, then verify.</p>}
+ {view && view.registered && !verified && view.dnsManaged && view.missingDns === 0 && <p className="text-xs text-neutral-500">DNS changes can take a few minutes to propagate. Check again shortly.</p>}
+
+ {view && view.records.length > 0 && !verified && (
+ <ul className="space-y-1 text-xs text-neutral-600">
+ {view.records.map((record) => (
+ <li key={`${record.type}-${record.name}-${record.value}`} className="grid gap-1 rounded-lg bg-white px-3 py-2 sm:grid-cols-[4rem_minmax(8rem,14rem)_minmax(0,1fr)_auto]">
+ <span className="font-medium">{record.type}</span>
+ <span className="break-all">{record.name}</span>
+ <span className="break-all">{record.priority !== null ? `${record.priority} ` : ""}{record.value}</span>
+ <span className="uppercase text-neutral-400">{record.status.replace(/_/g, " ")}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ {notice && <p role="status" className="text-xs text-green-700">{notice}</p>}
+ {error && <p role="alert" className="text-xs text-red-600">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/app/(admin)/domains/ResendKeyRow.tsx b/src/app/(admin)/domains/ResendKeyRow.tsx
new file mode 100644
index 0000000..b119131
--- /dev/null
+++ b/src/app/(admin)/domains/ResendKeyRow.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { postJson } from "./api";
+import { StatusRow } from "./status-row";
+
+type Props = {
+ configured: boolean | null;
+ /** Called after the key was saved (true) or removed (false). */
+ onChanged: (configured: boolean) => void;
+ onError: (message: string) => void;
+};
+
+/** The shared Resend API key, used by both the sending and receiving setup. */
+export default function ResendKeyRow({ configured, onChanged, onError }: Props) {
+ const [apiKey, setApiKey] = useState("");
+ const [editing, setEditing] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const showForm = configured === false || editing;
+
+ async function run(action: () => Promise<void>) {
+ setBusy(true);
+ onError("");
+ try { await action(); } catch (error) { onError(error instanceof Error ? error.message : "Request failed"); } finally { setBusy(false); }
+ }
+
+ const save = () => run(async () => {
+ await postJson("/api/admin/resend-key", "PUT", { apiKey });
+ setApiKey("");
+ setEditing(false);
+ onChanged(true);
+ });
+ const remove = () => run(async () => {
+ if (!window.confirm("Remove the Resend API key? Every domain using Resend will stop sending and receiving.")) return;
+ await postJson("/api/admin/resend-key", "DELETE", {});
+ onChanged(false);
+ });
+
+ return (
+ <>
+ <StatusRow
+ ok={!!configured && !editing}
+ title="API key"
+ hint="Shared by every domain using Resend"
+ action={configured && !editing ? (
+ <>
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy} onClick={() => setEditing(true)}>Replace</Button>
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy} onClick={() => void remove()}>Remove</Button>
+ </>
+ ) : undefined}
+ >
+ {showForm ? (
+ <form className="flex flex-wrap gap-2" onSubmit={(event) => { event.preventDefault(); void save(); }}>
+ <Input type="password" autoComplete="off" placeholder="re_..." value={apiKey} onChange={(event) => setApiKey(event.target.value)} className="max-w-xs bg-white" />
+ <Button type="submit" size="sm" disabled={!apiKey.trim() || busy}>{busy ? "Checking…" : "Save key"}</Button>
+ {editing && <Button type="button" size="sm" variant="outline" className="bg-white" onClick={() => { setEditing(false); setApiKey(""); }}>Cancel</Button>}
+ </form>
+ ) : configured ? "API key saved" : "Checking…"}
+ </StatusRow>
+ {showForm && <li className="list-none px-1 text-xs text-neutral-500">Create a key at resend.com/api-keys. A full-access key lets Mailflare add the domain, its DNS and the receiving webhook for you; a sending-only key works for sending, but you add the domain in Resend yourself.</li>}
+ </>
+ );
+}
diff --git a/src/app/(admin)/domains/SendingSetupSection.tsx b/src/app/(admin)/domains/SendingSetupSection.tsx
new file mode 100644
index 0000000..64ccf7b
--- /dev/null
+++ b/src/app/(admin)/domains/SendingSetupSection.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { useEffect, useState, type ReactNode } from "react";
+import { requestJson } from "./api";
+import ProviderCard from "./ProviderCard";
+import ResendDomainSection from "./ResendDomainSection";
+import SesSendingConfig from "./SesSendingConfig";
+import type { Domain, SendingProvider } from "./types";
+
+type Option = Exclude<SendingProvider, "none">;
+type Present = Record<Option, boolean | null>;
+
+const OPTIONS: { id: Option; title: string; description: string }[] = [
+ { id: "cloudflare", title: "Cloudflare Email", description: "Cloudflare Email Sending. Configured on this domain's zone." },
+ { id: "resend", title: "Resend", description: "Send through your Resend account." },
+ { id: "ses", title: "Amazon SES", description: "Send through your AWS account with SES." },
+];
+
+type Props = {
+ domain: Domain;
+ onChange?: (provider: SendingProvider) => void;
+ busy?: boolean;
+ message?: string | null;
+ /** Config UI for Cloudflare sending, rendered by the parent which owns the DNS audit. */
+ cloudflareConfig: ReactNode;
+ /** Whether Cloudflare sending is fully set up (subdomain enabled, DKIM present). */
+ cloudflareOk: boolean;
+};
+
+type PresenceResponse = Partial<Present> & { resendStatus?: string | null; sesVerified?: boolean | null };
+
+export default function SendingSetupSection({ domain, onChange, busy, message, cloudflareConfig, cloudflareOk }: Props) {
+ const [present, setPresent] = useState<Present>({ cloudflare: null, resend: null, ses: null });
+ const [resendStatus, setResendStatus] = useState<string | null>(null);
+ const [sesStatus, setSesStatus] = useState<string | null>(null);
+ const [reload, setReload] = useState(0);
+ const [removing, setRemoving] = useState<Option | null>(null);
+ const [error, setError] = useState("");
+
+ useEffect(() => {
+ let active = true;
+ requestJson<PresenceResponse>(`/api/domains/${domain.id}/sending`, "GET")
+ .then((data) => {
+ if (!active) return;
+ setPresent({ cloudflare: data.cloudflare ?? null, resend: data.resend ?? null, ses: data.ses ?? null });
+ setResendStatus(data.resendStatus ?? null);
+ setSesStatus(data.sesVerified === null || data.sesVerified === undefined ? null : data.sesVerified ? "verified" : "pending");
+ })
+ .catch(() => { if (active) setPresent({ cloudflare: null, resend: null, ses: null }); });
+ return () => { active = false; };
+ }, [domain.id, domain.sendingProvider, reload]);
+
+ async function cleanUp(option: Option, title: string) {
+ if (!window.confirm(`Remove the ${title} setup for ${domain.hostname}? This deletes its DNS records.`)) return;
+ setRemoving(option);
+ setError("");
+ try {
+ await requestJson(`/api/domains/${domain.id}/sending`, "DELETE", { target: option });
+ setReload((value) => value + 1);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not remove configuration");
+ } finally { setRemoving(null); }
+ }
+
+ // true/false when we know whether the option is set up, null when we cannot tell.
+ const okFor = (option: Option): boolean | null =>
+ option === "cloudflare" ? cloudflareOk
+ : option === "resend" ? (resendStatus === null ? null : resendStatus === "verified")
+ : (sesStatus === null ? null : sesStatus === "verified");
+
+ return (
+ <section className="mt-6">
+ <h2 className="text-base font-semibold text-neutral-900">Setup sending email</h2>
+ <p className="mt-0.5 text-sm text-neutral-500">
+ {domain.sendingProvider === "none" ? "This domain only receives mail. Turn on one option to send from it." : "Choose what sends outgoing mail from this domain. Receiving is not affected."}
+ </p>
+ <ul className="mt-3 space-y-2">
+ {OPTIONS.map((option) => {
+ const selected = domain.sendingProvider === option.id;
+ return (
+ <ProviderCard
+ key={option.id}
+ title={option.title}
+ description={option.description}
+ ok={selected || present[option.id] ? okFor(option.id) : null}
+ selected={selected}
+ disabled={busy}
+ onToggle={(on) => onChange?.(on ? option.id : "none")}
+ cleanup={{ present: !!present[option.id], busy: removing === option.id, disabled: removing !== null, onClick: () => void cleanUp(option.id, option.title) }}
+ >
+ {option.id === "cloudflare" ? cloudflareConfig
+ : option.id === "resend" ? <ResendDomainSection domainId={domain.id} onStatus={setResendStatus} />
+ : <SesSendingConfig domainId={domain.id} onStatus={setSesStatus} />}
+ </ProviderCard>
+ );
+ })}
+ </ul>
+ {message && <p className="mt-2 text-xs text-red-600">{message}</p>}
+ {error && <p role="alert" className="mt-2 text-xs text-red-600">{error}</p>}
+ </section>
+ );
+}
diff --git a/src/app/(admin)/domains/SesSendingConfig.tsx b/src/app/(admin)/domains/SesSendingConfig.tsx
new file mode 100644
index 0000000..b78595f
--- /dev/null
+++ b/src/app/(admin)/domains/SesSendingConfig.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import type { SesSendingView } from "@/lib/aws/ses-sending-types";
+import AwsCredentialsPanel from "./AwsCredentialsPanel";
+import { requestJson } from "./api";
+import { StatusRow } from "./status-row";
+
+type SesResponse = { credentials?: boolean; ses?: SesSendingView | null; error?: string };
+
+export default function SesSendingConfig({ domainId, onStatus }: { domainId: string; onStatus?: (status: string | null) => void }) {
+ const [credentials, setCredentials] = useState<boolean | null>(null);
+ const [view, setView] = useState<SesSendingView | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [reload, setReload] = useState(0);
+ const [busy, setBusy] = useState<"setup" | "verify" | "test" | null>(null);
+ const [error, setError] = useState("");
+ const [notice, setNotice] = useState("");
+
+ useEffect(() => {
+ let active = true;
+ requestJson<SesResponse>(`/api/domains/${domainId}/ses`, "GET")
+ .then((data) => { if (active) { setCredentials(data.credentials ?? true); setView(data.ses ?? null); setError(data.error ?? ""); } })
+ .catch((err) => { if (active) setError(err instanceof Error ? err.message : "Could not reach AWS"); })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [domainId, reload]);
+
+ useEffect(() => {
+ if (loading) return;
+ onStatus?.(credentials === false ? "no_credentials" : view ? (view.verified ? "verified" : view.registered ? "pending" : "not_registered") : null);
+ }, [loading, credentials, view, onStatus]);
+
+ const run = useCallback(async (kind: "setup" | "verify" | "test", action: () => Promise<void>) => {
+ setBusy(kind);
+ setError("");
+ setNotice("");
+ try { await action(); } catch (err) { setError(err instanceof Error ? err.message : "Request failed"); } finally { setBusy(null); }
+ }, []);
+
+ const domainAction = (action: "setup" | "verify") => run(action, async () => {
+ const data = await requestJson<SesResponse>(`/api/domains/${domainId}/ses`, "POST", { action });
+ setView(data.ses ?? null);
+ });
+ const sendTest = () => run("test", async () => {
+ const data = await requestJson<{ to: string }>(`/api/domains/${domainId}/ses`, "POST", { action: "test" });
+ setNotice(`Test email sent to ${data.to}`);
+ });
+
+ const onCredentials = useCallback((configured: boolean) => {
+ setCredentials(configured);
+ setLoading(true);
+ setReload((value) => value + 1);
+ }, []);
+
+ const label = loading ? "Checking Amazon SES…"
+ : !view ? "Could not read the domain from SES"
+ : view.verified ? "Domain verified in SES"
+ : !view.registered ? "Domain is not added to SES yet"
+ : view.missingDns === 0 ? `DNS records added, waiting for SES to verify (DKIM ${view.dkimStatus.toLowerCase()})`
+ : view.missingDns ? `${view.missingDns} DKIM record${view.missingDns === 1 ? "" : "s"} missing in Cloudflare`
+ : `DKIM ${view.dkimStatus.toLowerCase()}`;
+ const buttonLabel = !view ? null
+ : !view.registered ? (view.dnsManaged ? "Setup domain and DNS" : "Setup domain")
+ : view.dnsManaged && view.missingDns !== 0 ? "Create missing DNS and verify"
+ : "Check status";
+
+ return (
+ <div className="space-y-2">
+ <AwsCredentialsPanel need="sending" onChanged={onCredentials} />
+ {credentials && (
+ <ul className="space-y-2">
+ <StatusRow
+ ok={!!view?.verified}
+ title="Domain"
+ hint="Verified sender identity in SES"
+ action={view?.verified ? (
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => void sendTest()}>{busy === "test" ? "Sending…" : "Send test email"}</Button>
+ ) : buttonLabel && !loading ? (
+ <Button size="sm" variant="outline" className="bg-white" disabled={busy !== null} onClick={() => void domainAction(view?.registered && (!view.dnsManaged || view.missingDns === 0) ? "verify" : "setup")}>
+ {busy === "verify" ? "Checking…" : busy === "setup" ? "Working…" : buttonLabel}
+ </Button>
+ ) : undefined}
+ >
+ {label}
+ </StatusRow>
+ {view?.productionAccess === false && (
+ <StatusRow ok={false} title="SES sandbox" hint="Account-wide restriction">
+ In the sandbox SES delivers only to verified addresses. Request production access in the SES console before sending to anyone else.
+ </StatusRow>
+ )}
+ </ul>
+ )}
+ {view && view.registered && !view.verified && !view.dnsManaged && <p className="text-xs text-neutral-500">Add these CNAME records where this domain&apos;s DNS is hosted, then check status.</p>}
+ {view && view.registered && !view.verified && view.dnsManaged && view.missingDns === 0 && <p className="text-xs text-neutral-500">DNS changes can take a few minutes to propagate. Check again shortly.</p>}
+ {view && view.registered && !view.verified && view.records.length > 0 && (
+ <ul className="space-y-1 text-xs text-neutral-600">
+ {view.records.map((record) => (
+ <li key={record.name} className="grid gap-1 rounded-lg bg-white px-3 py-2 sm:grid-cols-[4rem_minmax(8rem,18rem)_minmax(0,1fr)]">
+ <span className="font-medium">{record.type}</span>
+ <span className="break-all">{record.name}</span>
+ <span className="break-all">{record.value}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ {notice && <p role="status" className="text-xs text-green-700">{notice}</p>}
+ {error && <p role="alert" className="text-xs text-red-600">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/app/(admin)/domains/api.ts b/src/app/(admin)/domains/api.ts
new file mode 100644
index 0000000..85289c7
--- /dev/null
+++ b/src/app/(admin)/domains/api.ts
@@ -0,0 +1,41 @@
+import { authFetch } from "@/lib/auth/client";
+
+export async function requestJson<T>(url: string, method: string, body?: unknown): Promise<T> {
+ const response = await authFetch(url, {
+ method,
+ headers: { "Content-Type": "application/json" },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ cache: "no-store",
+ });
+ const data = (await response.json()) as T & { error?: string };
+ if (!response.ok) throw new Error(data.error ?? "Request failed");
+ return data;
+}
+
+export const postJson = <T,>(url: string, method: string, body: unknown) => requestJson<T>(url, method, body);
+
+type SetupResponse = { error?: string; code?: string; records?: { content: string; priority: number }[] };
+
+/**
+ * Runs a receiving provider's setup. Other MX records would shadow the new one,
+ * so the server refuses (409) until the user agrees to replace them.
+ * Returns false when the user declined.
+ */
+export async function runReceivingSetup(domainId: string, provider: "cloudflare" | "resend" | "ses"): Promise<boolean> {
+ const call = async (replaceMx: boolean) => {
+ const response = await authFetch(`/api/domains/${domainId}/receiving/${provider}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ replaceMx }),
+ });
+ return { response, data: (await response.json()) as SetupResponse };
+ };
+ let { response, data } = await call(false);
+ if (response.status === 409 && data.code === "MX_CONFLICT") {
+ const list = (data.records ?? []).map((record) => ` ${record.priority} ${record.content}`).join("\n");
+ if (!window.confirm(`${data.error}\n\n${list}\n\nReplace them? Mail will stop going to the current service.`)) return false;
+ ({ response, data } = await call(true));
+ }
+ if (!response.ok) throw new Error(data.error ?? "Setup failed");
+ return true;
+}
diff --git a/src/app/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
index f7e492f..fbca232 100644
--- a/src/app/(admin)/domains/page.tsx
+++ b/src/app/(admin)/domains/page.tsx
@@ -18,7 +18,7 @@ import { Switch } from "@/components/ui/switch";
import { List } from "@/components/ui/list";
import { CheckCircle2, LoaderCircle, Plus } from "lucide-react";
import { authFetch } from "@/lib/auth/client";
-import type { DnsAuthRecord, DnsStatusSummary, Domain, DomainDnsCache, DomainDnsView, DomainPreflight } from "./types";
+import type { DnsAuthRecord, DnsStatusSummary, Domain, DomainDnsCache, DomainDnsView, DomainPreflight, ReceivingProvider, SendingProvider } from "./types";
import DomainItemCard from "./DomainItemCard";
import { SectionRowSkeleton } from "@/components/page-skeletons";
import { checkDomain } from "./utils";
@@ -35,6 +35,7 @@ export default function DomainsPage() {
const [domainCheck, setDomainCheck] = useState<DomainPreflight | null>(null);
const [domainChecking, setDomainChecking] = useState(false);
const [enableSending, setEnableSending] = useState(false);
+ const [receivingProvider, setReceivingProvider] = useState<ReceivingProvider>("cloudflare");
const [domainCheckError, setDomainCheckError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [setupRecord, setSetupRecord] = useState<DnsAuthRecord | null>(null);
@@ -80,6 +81,7 @@ export default function DomainsPage() {
hostname: checkedDomain.hostname,
enableRouting: true,
enableSending: sendingRequested,
+ receivingProvider,
}),
});
const json = (await res.json()) as { error?: string };
@@ -90,6 +92,7 @@ export default function DomainsPage() {
setHostname("");
setDomainCheck(null);
setEnableSending(false);
+ setReceivingProvider("cloudflare");
setDomainCheckError(null);
setCreateOpen(false);
qc.invalidateQueries({ queryKey: ["domains"] });
@@ -150,6 +153,63 @@ export default function DomainsPage() {
}
};
+ const [sendingBusy, setSendingBusy] = useState(false);
+ const [sendingMessage, setSendingMessage] = useState<string | null>(null);
+
+ const changeSendingProvider = async (provider: SendingProvider) => {
+ if (!expandedDomainId) return;
+ const id = expandedDomainId;
+ setSendingBusy(true);
+ setSendingMessage(null);
+ try {
+ const res = await authFetch(`/api/domains/${id}/sending`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider }),
+ });
+ const json = (await res.json()) as { warning?: string; error?: string };
+ if (!res.ok) throw new Error(json.error ?? "Failed to change sending provider");
+ if (json.warning) setSendingMessage(json.warning);
+ await loadDns(id);
+ qc.invalidateQueries({ queryKey: ["domains"] });
+ } catch (error) {
+ setSendingMessage(error instanceof Error ? error.message : "Failed to change sending provider");
+ } finally {
+ setSendingBusy(false);
+ }
+ };
+
+ const [receivingBusy, setReceivingBusy] = useState(false);
+ const [receivingMessage, setReceivingMessage] = useState<string | null>(null);
+
+ const changeReceivingProvider = async (provider: ReceivingProvider) => {
+ if (!expandedDomainId) return;
+ const id = expandedDomainId;
+ setReceivingBusy(true);
+ setReceivingMessage(null);
+ try {
+ const res = await authFetch(`/api/domains/${id}/receiving`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider }),
+ });
+ const json = (await res.json()) as { error?: string };
+ if (!res.ok) throw new Error(json.error ?? "Failed to change receiving provider");
+ await loadDns(id);
+ qc.invalidateQueries({ queryKey: ["domains"] });
+ } catch (error) {
+ setReceivingMessage(error instanceof Error ? error.message : "Failed to change receiving provider");
+ } finally {
+ setReceivingBusy(false);
+ }
+ };
+
+ const refreshExpandedDns = () => {
+ if (!expandedDomainId) return;
+ void loadDns(expandedDomainId).catch(() => undefined);
+ qc.invalidateQueries({ queryKey: ["domains"] });
+ };
+
const setupDns = async (record: DnsAuthRecord) => {
if (!expandedDomainId) return;
const dnsView = dnsViews[expandedDomainId];
@@ -209,7 +269,7 @@ export default function DomainsPage() {
<h1 className="text-2xl md:text-3xl font-medium">Domains</h1>
<p className="mt-1 text-sm text-neutral-500">
{managesDns
- ? "Domains must be on your Cloudflare account. Email Routing is enabled automatically, and Email Sending can be enabled when available."
+ ? "Domains must be on your Cloudflare account, which manages their DNS. Choose per domain whether Cloudflare, Resend or Amazon SES receives and sends its mail."
: "Add the domains this server receives mail for. Open DNS on a domain to see the MX, SPF and DMARC records to create."}
</p>
</div>
@@ -224,8 +284,8 @@ export default function DomainsPage() {
<DialogHeader>
<DialogTitle>Add domain</DialogTitle>
<DialogDescription>
- Connect a Cloudflare zone and choose whether Mailflare should
- provision Email Sending.
+ Connect a Cloudflare zone, then choose which service receives
+ its mail and whether Mailflare should provision Email Sending.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
@@ -245,6 +305,29 @@ export default function DomainsPage() {
placeholder="example.com"
/>
</div>
+ <div className="flex items-center justify-between gap-4 rounded-xl bg-neutral-50 px-4 py-3">
+ <div>
+ <Label htmlFor="receiving-provider">Receive mail with</Label>
+ <p className="mt-1 text-xs leading-5 text-neutral-500">
+ {receivingProvider === "cloudflare"
+ ? "Cloudflare Email Routing is enabled on the zone."
+ : receivingProvider === "none"
+ ? "The domain only sends. Add a receiving service later."
+ : "Add your credentials and set it up from the domain page after adding."}
+ </p>
+ </div>
+ <select
+ id="receiving-provider"
+ value={receivingProvider}
+ onChange={(e) => setReceivingProvider(e.target.value as ReceivingProvider)}
+ className="h-9 shrink-0 rounded-md border border-neutral-200 bg-white px-3 text-sm"
+ >
+ <option value="cloudflare">Cloudflare Email Routing</option>
+ <option value="resend">Resend</option>
+ <option value="ses">Amazon SES</option>
+ <option value="none">Not selected</option>
+ </select>
+ </div>
<div className="flex items-center justify-between gap-4 rounded-xl bg-neutral-50 px-4 py-3">
<div>
<Label htmlFor="enable-sending">Enable sending</Label>
@@ -330,6 +413,13 @@ export default function DomainsPage() {
key={d.id}
dns={dns}
dnsDetails={dnsViews[d.id]?.dns}
+ onSendingProviderChange={changeSendingProvider}
+ sendingProviderBusy={sendingBusy}
+ sendingProviderMessage={expandedDomainId === d.id ? sendingMessage : null}
+ onReceivingProviderChange={changeReceivingProvider}
+ receivingProviderBusy={receivingBusy}
+ receivingProviderMessage={expandedDomainId === d.id ? receivingMessage : null}
+ onDnsChanged={refreshExpandedDns}
dnsLoading={expandedDomainId === d.id && dnsLoading}
dnsError={expandedDomainId === d.id ? dnsError : null}
expanded={expandedDomainId === d.id}
diff --git a/src/app/(admin)/domains/status-row.tsx b/src/app/(admin)/domains/status-row.tsx
new file mode 100644
index 0000000..423f4c2
--- /dev/null
+++ b/src/app/(admin)/domains/status-row.tsx
@@ -0,0 +1,34 @@
+import type { ReactNode } from "react";
+import { AlertTriangle, Check } from "lucide-react";
+
+export const ROW_GRID = "grid gap-3 rounded-xl px-4 py-3 text-sm sm:grid-cols-[auto_minmax(8rem,14rem)_minmax(0,1fr)_auto] sm:items-start";
+
+export function StatusBadge({ ok, tone = "red" }: { ok: boolean; tone?: "red" | "neutral" }) {
+ if (ok) {
+ return (
+ <span className="flex h-7 w-7 items-center justify-center rounded-full bg-green-600 text-white">
+ <Check className="h-4 w-4" />
+ </span>
+ );
+ }
+ return (
+ <span className="flex h-7 w-7 items-center justify-center rounded-full bg-white/70">
+ <AlertTriangle className={`h-4 w-4 ${tone === "red" ? "text-red-600" : "text-neutral-400"}`} />
+ </span>
+ );
+}
+
+/** An icon-left status line shared by the domain setup and sending setup lists. */
+export function StatusRow({ ok, title, hint, children, action }: { ok: boolean; title: string; hint: string; children?: ReactNode; action?: ReactNode }) {
+ return (
+ <li className={`${ROW_GRID} ${ok ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}>
+ <StatusBadge ok={ok} />
+ <span className="min-w-0">
+ <span className="block font-medium text-neutral-900">{title}</span>
+ <span className="block text-xs text-neutral-500">{hint}</span>
+ </span>
+ <span className="min-w-0 break-words text-neutral-500">{children}</span>
+ {action && <span className="flex flex-wrap items-center gap-2">{action}</span>}
+ </li>
+ );
+}
diff --git a/src/app/(admin)/domains/types.d.ts b/src/app/(admin)/domains/types.d.ts
index 6b7c964..b19e9c7 100644
--- a/src/app/(admin)/domains/types.d.ts
+++ b/src/app/(admin)/domains/types.d.ts
@@ -1,3 +1,6 @@
+export type SendingProvider = "none" | "cloudflare" | "resend" | "ses";
+export type ReceivingProvider = "none" | "cloudflare" | "resend" | "ses";
+
export type Domain = {
id: string;
hostname: string;
@@ -5,6 +8,8 @@ export type Domain = {
routingEnabled: boolean;
sendingEnabled: boolean;
sendingRequested: boolean;
+ sendingProvider: SendingProvider;
+ receivingProvider: ReceivingProvider;
zoneId: string;
};
@@ -64,6 +69,14 @@ export type DomainDnsCache = Record<string, { domain: Domain; dns: DomainDnsView
export type DomainDnsDetailsProps = {
domain: Domain;
dns: DomainDnsView;
+ onSendingProviderChange?: (provider: SendingProvider) => void;
+ sendingProviderBusy?: boolean;
+ sendingProviderMessage?: string | null;
+ onReceivingProviderChange?: (provider: ReceivingProvider) => void;
+ receivingProviderBusy?: boolean;
+ receivingProviderMessage?: string | null;
+ /** Reload the DNS view after a setup that changed the zone. */
+ onDnsChanged?: () => void;
onSetup?: (record: DnsAuthRecord) => void;
setupRecord?: DnsAuthRecord | null;
setupMessage?: string | null;
@@ -73,6 +86,13 @@ export type DomainItemCardProps = {
item: Domain;
dns?: DnsStatusSummary;
dnsDetails?: DomainDnsView;
+ onSendingProviderChange?: (provider: SendingProvider) => void;
+ sendingProviderBusy?: boolean;
+ sendingProviderMessage?: string | null;
+ onReceivingProviderChange?: (provider: ReceivingProvider) => void;
+ receivingProviderBusy?: boolean;
+ receivingProviderMessage?: string | null;
+ onDnsChanged?: () => void;
dnsLoading?: boolean;
dnsError?: string | null;
expanded?: boolean;
diff --git a/src/app/api/admin/aws/route.ts b/src/app/api/admin/aws/route.ts
new file mode 100644
index 0000000..3e75aa7
--- /dev/null
+++ b/src/app/api/admin/aws/route.ts
@@ -0,0 +1,69 @@
+import { z } from "zod";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { isPrimaryAdmin } from "@/lib/auth/admin";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { AWS_IAM_POLICY, AwsCredentialsError, validateAwsConfig } from "@/lib/aws/validate";
+import { clearAwsConfig, getAwsConfig, getAwsConfigStatus, saveAwsConfig } from "@/lib/aws/config";
+
+const schema = z.object({
+ accessKeyId: z.string().trim().regex(/^[A-Z0-9]{16,128}$/, "That does not look like an AWS access key ID"),
+ secretAccessKey: z.string().trim().min(20).max(200),
+ region: z.string().trim().toLowerCase(),
+});
+
+async function authorize(request: Request, mutation: boolean) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return { env, error: auth.error };
+ if (!isPrimaryAdmin(auth.user)) return { env, error: Response.json({ error: "Only the primary administrator can manage AWS credentials" }, { status: 403 }) };
+ if (mutation && !hasValidSessionMutationOrigin(request)) return { env, error: Response.json({ error: "Invalid origin" }, { status: 403 }) };
+ return { env, error: null };
+}
+
+const noStore = { "Cache-Control": "no-store" };
+
+export async function GET(request: Request) {
+ const access = await authorize(request, false);
+ if (access.error) return access.error;
+ return Response.json({ status: await getAwsConfigStatus(access.env), policy: AWS_IAM_POLICY }, { headers: noStore });
+}
+
+/** Validates the credentials against AWS before saving them. */
+export async function PUT(request: Request) {
+ const access = await authorize(request, true);
+ if (access.error) return access.error;
+ const parsed = schema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: parsed.error.issues[0]?.message ?? "Enter an access key ID, secret and region" }, { status: 400 });
+ try {
+ const report = await validateAwsConfig(parsed.data);
+ if (!report.sending && !report.receiving) {
+ return Response.json({ error: "These credentials work but have no SES permissions. Attach the policy shown below.", report }, { status: 400 });
+ }
+ await saveAwsConfig(access.env, parsed.data, report.accountId);
+ return Response.json({ status: await getAwsConfigStatus(access.env), report }, { headers: noStore });
+ } catch (error) {
+ if (error instanceof AwsCredentialsError) return Response.json({ error: error.message }, { status: 400 });
+ return Response.json({ error: error instanceof Error ? error.message : "Could not reach AWS" }, { status: 502 });
+ }
+}
+
+/** Re-runs the capability checks against the saved credentials. */
+export async function POST(request: Request) {
+ const access = await authorize(request, true);
+ if (access.error) return access.error;
+ const config = await getAwsConfig(access.env);
+ if (!config) return Response.json({ error: "No AWS credentials are configured" }, { status: 400 });
+ try {
+ return Response.json({ report: await validateAwsConfig(config) }, { headers: noStore });
+ } catch (error) {
+ return Response.json({ error: error instanceof Error ? error.message : "Could not reach AWS" }, { status: error instanceof AwsCredentialsError ? 400 : 502 });
+ }
+}
+
+export async function DELETE(request: Request) {
+ const access = await authorize(request, true);
+ if (access.error) return access.error;
+ await clearAwsConfig(access.env);
+ return Response.json({ status: await getAwsConfigStatus(access.env) }, { headers: noStore });
+}
diff --git a/src/app/api/admin/resend-key/route.ts b/src/app/api/admin/resend-key/route.ts
new file mode 100644
index 0000000..c8a06d7
--- /dev/null
+++ b/src/app/api/admin/resend-key/route.ts
@@ -0,0 +1,52 @@
+import { eq } from "drizzle-orm";
+import { z } from "zod";
+import { getDb } from "@/db";
+import { appSettings } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { isPrimaryAdmin } from "@/lib/auth/admin";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { getResendKeyStatus } from "@/lib/email/outbound-provider";
+import { checkResendKey } from "@/lib/email/resend-api";
+
+const schema = z.object({ apiKey: z.string().trim().min(1).max(500) });
+
+async function authorize(request: Request, mutation: boolean) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return { env, error: auth.error };
+ if (!isPrimaryAdmin(auth.user)) return { env, error: Response.json({ error: "Only the primary administrator can manage the Resend API key" }, { status: 403 }) };
+ if (mutation && !hasValidSessionMutationOrigin(request)) return { env, error: Response.json({ error: "Invalid origin" }, { status: 403 }) };
+ return { env, error: null };
+}
+
+async function status(env: CloudflareEnv) {
+ const { configured, source } = await getResendKeyStatus(env);
+ return { configured, source };
+}
+
+export async function GET(request: Request) {
+ const access = await authorize(request, false);
+ if (access.error) return access.error;
+ return Response.json(await status(access.env), { headers: { "Cache-Control": "no-store" } });
+}
+
+export async function PUT(request: Request) {
+ const access = await authorize(request, true);
+ if (access.error) return access.error;
+ const parsed = schema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Enter a Resend API key" }, { status: 400 });
+ const check = await checkResendKey(parsed.data.apiKey).catch(() => null);
+ if (!check) return Response.json({ error: "Could not reach Resend to check the key" }, { status: 502 });
+ if (!check.valid) return Response.json({ error: "Resend rejected this API key" }, { status: 400 });
+ const values = { resendApiKey: parsed.data.apiKey, updatedAt: new Date() };
+ await getDb(access.env).insert(appSettings).values({ id: "default", ...values }).onConflictDoUpdate({ target: appSettings.id, set: values });
+ return Response.json({ ...(await status(access.env)), canManageDomains: check.canManageDomains }, { headers: { "Cache-Control": "no-store" } });
+}
+
+export async function DELETE(request: Request) {
+ const access = await authorize(request, true);
+ if (access.error) return access.error;
+ await getDb(access.env).update(appSettings).set({ resendApiKey: null, updatedAt: new Date() }).where(eq(appSettings.id, "default"));
+ return Response.json(await status(access.env), { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/domains/[id]/receiving/[provider]/route.ts b/src/app/api/domains/[id]/receiving/[provider]/route.ts
new file mode 100644
index 0000000..ee3ca20
--- /dev/null
+++ b/src/app/api/domains/[id]/receiving/[provider]/route.ts
@@ -0,0 +1,59 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { getEnv } from "@/lib/cloudflare";
+import { requireUser } from "@/lib/auth/cookies";
+import { canManageDomains } from "@/lib/auth/admin";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { getAwsConfig } from "@/lib/aws/config";
+import { getSesReceivingView } from "@/lib/aws/ses-receiving";
+import { getDomainForUser } from "@/lib/domains/service";
+import { setupReceiving } from "@/lib/domains/receiving";
+import { MxConflictError } from "@/lib/domains/receiving-dns";
+import { getResendReceivingView } from "@/lib/domains/resend-receiving";
+
+type Params = { params: Promise<{ id: string; provider: string }> };
+const noStore = { "Cache-Control": "no-store" };
+const providerSchema = z.enum(["cloudflare", "resend", "ses"]);
+
+const originOf = (env: CloudflareEnv, request: Request) => env.APP_URL?.trim() || new URL(request.url).origin;
+
+/** Setup status for a receiving provider: a checklist of what exists and what is missing. */
+export async function GET(request: Request, { params }: Params) {
+ const { id, provider: rawProvider } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const provider = providerSchema.safeParse(rawProvider);
+ if (!provider.success || provider.data === "cloudflare") return NextResponse.json({ error: "Unknown provider" }, { status: 400 });
+ try {
+ if (provider.data === "ses") {
+ if (!(await getAwsConfig(env))) return NextResponse.json({ credentials: false, view: null }, { headers: noStore });
+ return NextResponse.json({ credentials: true, view: await getSesReceivingView(env, domain) }, { headers: noStore });
+ }
+ return NextResponse.json({ credentials: true, view: await getResendReceivingView(env, domain, originOf(env, request)) }, { headers: noStore });
+ } catch (error) {
+ return NextResponse.json({ error: error instanceof Error ? error.message : "Could not reach the provider" }, { status: 502 });
+ }
+}
+
+/** Creates what the provider needs and points the domain's MX at it. 409 MX_CONFLICT asks the caller to confirm replacing other MX records. */
+export async function POST(request: Request, { params }: Params) {
+ const { id, provider: rawProvider } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ if (!canManageDomains(user)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const provider = providerSchema.safeParse(rawProvider);
+ if (!provider.success) return NextResponse.json({ error: "Unknown provider" }, { status: 400 });
+ const body = (await request.json().catch(() => ({}))) as { replaceMx?: boolean };
+ try {
+ await setupReceiving(env, domain, provider.data, originOf(env, request), { replaceMx: body.replaceMx === true });
+ return NextResponse.json({ ok: true }, { headers: noStore });
+ } catch (error) {
+ if (error instanceof MxConflictError) return NextResponse.json({ error: error.message, code: error.code, records: error.records }, { status: 409 });
+ return NextResponse.json({ error: error instanceof Error ? error.message : "Setup failed" }, { status: 502 });
+ }
+}
diff --git a/src/app/api/domains/[id]/receiving/route.ts b/src/app/api/domains/[id]/receiving/route.ts
new file mode 100644
index 0000000..bad3e84
--- /dev/null
+++ b/src/app/api/domains/[id]/receiving/route.ts
@@ -0,0 +1,58 @@
+import { NextResponse } from "next/server";
+import { eq } from "drizzle-orm";
+import { z } from "zod";
+import { getDb } from "@/db";
+import { domains } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { requireUser } from "@/lib/auth/cookies";
+import { canManageDomains } from "@/lib/auth/admin";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { getDomainForUser } from "@/lib/domains/service";
+import { receivingPresence, removeReceiving } from "@/lib/domains/receiving";
+
+type Params = { params: Promise<{ id: string }> };
+
+/** Chooses which provider receives mail for this domain. DNS is changed by that provider's own Setup. */
+export async function PUT(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ if (!canManageDomains(user)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const parsed = z.object({ provider: z.enum(["none", "cloudflare", "resend", "ses"]) }).safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: "Unknown receiving provider" }, { status: 400 });
+ await getDb(env).update(domains).set({ receivingProvider: parsed.data.provider }).where(eq(domains.id, domain.id));
+ return NextResponse.json({ domain: await getDomainForUser(env, user.id, id) }, { headers: { "Cache-Control": "no-store" } });
+}
+
+/** Which providers still have receiving configuration for this domain. */
+export async function GET(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ return NextResponse.json(await receivingPresence(env, domain), { headers: { "Cache-Control": "no-store" } });
+}
+
+/** Removes the configuration of a provider this domain is not receiving through. */
+export async function DELETE(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ if (!canManageDomains(user)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const parsed = z.object({ target: z.enum(["cloudflare", "resend", "ses"]) }).safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: "Unknown provider" }, { status: 400 });
+ if (parsed.data.target === domain.receivingProvider) return NextResponse.json({ error: "Switch to another provider before removing this one" }, { status: 400 });
+ try {
+ await removeReceiving(env, domain, parsed.data.target);
+ return NextResponse.json({ ok: true });
+ } catch (error) {
+ return NextResponse.json({ error: error instanceof Error ? error.message : "Could not remove configuration" }, { status: 502 });
+ }
+}
diff --git a/src/app/api/domains/[id]/resend/route.ts b/src/app/api/domains/[id]/resend/route.ts
new file mode 100644
index 0000000..ddf1b62
--- /dev/null
+++ b/src/app/api/domains/[id]/resend/route.ts
@@ -0,0 +1,58 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { requireUser } from "@/lib/auth/cookies";
+import { canManageDomains } from "@/lib/auth/admin";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { getDomainForUser } from "@/lib/domains/service";
+import { ResendRestrictedKeyError } from "@/lib/email/resend-api";
+import { getResendKeyStatus } from "@/lib/email/outbound-provider";
+import { sendSystemEmail } from "@/lib/email/system-mail";
+import { getResendDomainView, setupResendDomain, verifyResendDomainView } from "@/lib/domains/resend-domain";
+
+type Params = { params: Promise<{ id: string }> };
+
+export async function GET(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ if (domain.sendingProvider !== "resend") return NextResponse.json({ error: "Resend is not selected for this domain" }, { status: 400 });
+ const key = await getResendKeyStatus(env);
+ if (!key.configured) return NextResponse.json({ keyConfigured: false, resend: null }, { headers: { "Cache-Control": "no-store" } });
+ try {
+ return NextResponse.json({ keyConfigured: true, resend: await getResendDomainView(env, domain) }, { headers: { "Cache-Control": "no-store" } });
+ } catch (error) {
+ // A send-only key is valid; it just cannot look at domains.
+ if (error instanceof ResendRestrictedKeyError) return NextResponse.json({ keyConfigured: true, canManageDomains: false, resend: null }, { headers: { "Cache-Control": "no-store" } });
+ return NextResponse.json({ error: error instanceof Error ? error.message : "Could not reach Resend" }, { status: 502 });
+ }
+}
+
+export async function POST(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ if (!canManageDomains(user)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const body = (await request.json().catch(() => ({}))) as { action?: string };
+ if (body.action !== "setup" && body.action !== "verify" && body.action !== "test") return NextResponse.json({ error: "Unknown action" }, { status: 400 });
+ try {
+ if (body.action === "test") {
+ const sent = await sendSystemEmail(env, {
+ to: user.email,
+ subject: "Mailflare test email",
+ text: `This message confirms ${domain.hostname} can send mail through Resend.`,
+ hostname: domain.hostname,
+ });
+ if (!sent) return NextResponse.json({ error: `Create a mailbox on ${domain.hostname} to send the test from.` }, { status: 400 });
+ return NextResponse.json({ ok: true, to: user.email });
+ }
+ const resend = body.action === "setup" ? await setupResendDomain(env, domain) : await verifyResendDomainView(env, domain);
+ return NextResponse.json({ resend }, { headers: { "Cache-Control": "no-store" } });
+ } catch (error) {
+ return NextResponse.json({ error: error instanceof Error ? error.message : "Resend request failed" }, { status: 502 });
+ }
+}
diff --git a/src/app/api/domains/[id]/sending/route.ts b/src/app/api/domains/[id]/sending/route.ts
new file mode 100644
index 0000000..18f9d38
--- /dev/null
+++ b/src/app/api/domains/[id]/sending/route.ts
@@ -0,0 +1,98 @@
+import { NextResponse } from "next/server";
+import { eq } from "drizzle-orm";
+import { z } from "zod";
+import { getDb } from "@/db";
+import { domains } from "@/db/schema";
+import { getEnv } from "@/lib/cloudflare";
+import { requireUser } from "@/lib/auth/cookies";
+import { canManageDomains } from "@/lib/auth/admin";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { getDomainForUser } from "@/lib/domains/service";
+import { isManualZone } from "@/lib/domains/provision";
+import { findCloudflareSending, removeCloudflareSending } from "@/lib/domains/cloudflare-sending";
+import { getAwsConfig } from "@/lib/aws/config";
+import { getSesIdentity } from "@/lib/aws/ses";
+import { removeSesSending } from "@/lib/aws/ses-sending";
+import { getResendDomainStatus, removeResendConfig } from "@/lib/domains/resend-domain";
+import { setupDomainDnsRecord } from "@/lib/domains/dns-setup";
+
+type Params = { params: Promise<{ id: string }> };
+
+const schema = z.object({ provider: z.enum(["none", "cloudflare", "resend", "ses"]) });
+
+/** Chooses what sends mail for this domain. Receiving is unaffected. */
+export async function PUT(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ if (!canManageDomains(user)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const parsed = schema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: "Unknown sending provider" }, { status: 400 });
+ const { provider } = parsed.data;
+
+ await getDb(env)
+ .update(domains)
+ .set({ sendingProvider: provider, sendingRequested: provider === "cloudflare" ? true : domain.sendingRequested })
+ .where(eq(domains.id, domain.id));
+
+ let warning: string | undefined;
+ if (provider === "cloudflare" && !isManualZone(domain.zoneId)) {
+ // Enable the zone's sending subdomain right away; failure is reported but the
+ // choice is kept so the setup buttons on the domain page can finish the job.
+ try { await setupDomainDnsRecord(env, { ...domain, sendingProvider: provider }, "dkim"); }
+ catch (error) { warning = error instanceof Error ? error.message : "Could not enable Cloudflare sending"; }
+ }
+ const updated = await getDomainForUser(env, user.id, id);
+ return NextResponse.json({ domain: updated, warning }, { headers: { "Cache-Control": "no-store" } });
+}
+
+/** Which providers have leftover configuration for this domain (null = could not tell). */
+export async function GET(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const [cloudflare, resendStatus, ses] = await Promise.all([
+ findCloudflareSending(env, domain),
+ getResendDomainStatus(env, domain),
+ sesSendingStatus(env, domain.hostname),
+ ]);
+ const resend = resendStatus === null ? null : resendStatus !== "not_registered";
+ return NextResponse.json({ cloudflare: !!cloudflare, resend, resendStatus, ses: ses === null ? null : ses.registered, sesVerified: ses?.verified ?? null }, { headers: { "Cache-Control": "no-store" } });
+}
+
+async function sesSendingStatus(env: CloudflareEnv, hostname: string) {
+ const config = await getAwsConfig(env);
+ if (!config) return null;
+ try { return await getSesIdentity(config, hostname); } catch { return null; }
+}
+
+const removeSchema = z.object({ target: z.enum(["cloudflare", "resend", "ses"]) });
+
+/** Removes the config of a provider this domain is not using. */
+export async function DELETE(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ if (!canManageDomains(user)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const parsed = removeSchema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: "Unknown provider" }, { status: 400 });
+ if (parsed.data.target === domain.sendingProvider) {
+ return NextResponse.json({ error: "Switch to another provider before removing this one" }, { status: 400 });
+ }
+ try {
+ if (parsed.data.target === "cloudflare") await removeCloudflareSending(env, domain);
+ else if (parsed.data.target === "resend") await removeResendConfig(env, domain);
+ else await removeSesSending(env, domain);
+ return NextResponse.json({ ok: true });
+ } catch (error) {
+ return NextResponse.json({ error: error instanceof Error ? error.message : "Could not remove configuration" }, { status: 502 });
+ }
+}
diff --git a/src/app/api/domains/[id]/ses/route.ts b/src/app/api/domains/[id]/ses/route.ts
new file mode 100644
index 0000000..279728a
--- /dev/null
+++ b/src/app/api/domains/[id]/ses/route.ts
@@ -0,0 +1,52 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { requireUser } from "@/lib/auth/cookies";
+import { canManageDomains } from "@/lib/auth/admin";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { getAwsConfig } from "@/lib/aws/config";
+import { getSesSendingView, setupSesSending } from "@/lib/aws/ses-sending";
+import { AwsError } from "@/lib/aws/client";
+import { getDomainForUser } from "@/lib/domains/service";
+import { sendSystemEmail } from "@/lib/email/system-mail";
+
+type Params = { params: Promise<{ id: string }> };
+const noStore = { "Cache-Control": "no-store" };
+
+/** SES sending status for a domain: identity, DKIM, DNS and sandbox state. */
+export async function GET(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ if (!(await getAwsConfig(env))) return NextResponse.json({ credentials: false, ses: null }, { headers: noStore });
+ try {
+ return NextResponse.json({ credentials: true, ses: await getSesSendingView(env, domain) }, { headers: noStore });
+ } catch (error) {
+ if (error instanceof AwsError && error.accessDenied) return NextResponse.json({ credentials: true, ses: null, error: "These AWS credentials cannot manage SES identities. Re-check them under AWS credentials." }, { headers: noStore });
+ return NextResponse.json({ error: error instanceof Error ? error.message : "Could not reach AWS" }, { status: 502 });
+ }
+}
+
+export async function POST(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ if (!canManageDomains(user)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ const body = (await request.json().catch(() => ({}))) as { action?: string };
+ try {
+ if (body.action === "test") {
+ const sent = await sendSystemEmail(env, { to: user.email, subject: "Mailflare test email", text: `This message confirms ${domain.hostname} can send mail through Amazon SES.`, hostname: domain.hostname });
+ if (!sent) return NextResponse.json({ error: `Create a mailbox on ${domain.hostname} to send the test from.` }, { status: 400 });
+ return NextResponse.json({ ok: true, to: user.email });
+ }
+ if (body.action === "setup") return NextResponse.json({ ses: await setupSesSending(env, domain) }, { headers: noStore });
+ if (body.action === "verify") return NextResponse.json({ ses: await getSesSendingView(env, domain) }, { headers: noStore });
+ return NextResponse.json({ error: "Unknown action" }, { status: 400 });
+ } catch (error) {
+ return NextResponse.json({ error: error instanceof Error ? error.message : "AWS request failed" }, { status: 502 });
+ }
+}
diff --git a/src/app/api/domains/route.ts b/src/app/api/domains/route.ts
index 66ece4e..5b6fb4b 100644
--- a/src/app/api/domains/route.ts
+++ b/src/app/api/domains/route.ts
@@ -57,6 +57,7 @@ export async function POST(request: Request) {
enableRouting: parsed.data.enableRouting,
enableSending: parsed.data.enableSending,
replaceMxRecords: parsed.data.replaceMxRecords,
+ receivingProvider: parsed.data.receivingProvider,
});
return NextResponse.json(result);
} catch (err) {
diff --git a/src/app/api/inbound/resend/route.ts b/src/app/api/inbound/resend/route.ts
new file mode 100644
index 0000000..3fe3f36
--- /dev/null
+++ b/src/app/api/inbound/resend/route.ts
@@ -0,0 +1,47 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { getEmailAddress, getEmailAddressList } from "@/lib/email/address";
+import { getResendApiKey } from "@/lib/email/outbound-provider";
+import { intakeProviderMail } from "@/lib/email/provider-intake";
+import { getReceivedEmail } from "@/lib/email/resend-api";
+import { verifySvixSignature } from "@/lib/email/svix";
+import { getResendWebhookSecret } from "@/lib/domains/resend-receiving";
+
+export const dynamic = "force-dynamic";
+
+type ReceivedEvent = { type?: string; data?: { email_id?: string; id?: string } };
+
+/**
+ * Resend's `email.received` webhook. The event only names the message, so fetch
+ * it, download the raw MIME and run it through the normal intake. Authenticated
+ * by the Svix signature of the secret Resend returned when the webhook was created.
+ */
+export async function POST(request: Request) {
+ const env = getEnv();
+ const secret = await getResendWebhookSecret(env);
+ if (!secret) return NextResponse.json({ error: "Resend receiving is not set up" }, { status: 503 });
+ const body = await request.text();
+ const valid = await verifySvixSignature(secret, {
+ id: request.headers.get("svix-id"),
+ timestamp: request.headers.get("svix-timestamp"),
+ signature: request.headers.get("svix-signature"),
+ }, body);
+ if (!valid) return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
+
+ let event: ReceivedEvent;
+ try { event = JSON.parse(body) as ReceivedEvent; } catch { return NextResponse.json({ error: "Invalid body" }, { status: 400 }); }
+ if (event.type !== "email.received") return NextResponse.json({ ignored: true });
+ const emailId = event.data?.email_id ?? event.data?.id;
+ if (!emailId) return NextResponse.json({ error: "Missing email id" }, { status: 400 });
+
+ const apiKey = await getResendApiKey(env);
+ const email = await getReceivedEmail(apiKey, emailId);
+ const download = email.raw?.download_url;
+ if (!download) return NextResponse.json({ error: "Resend did not provide the raw message" }, { status: 502 });
+ const rawResponse = await fetch(download);
+ if (!rawResponse.ok) return NextResponse.json({ error: "Could not download the raw message" }, { status: 502 });
+
+ const recipients = [...(email.to ?? []), ...(email.cc ?? []), ...(email.bcc ?? [])].flatMap((value) => getEmailAddressList(value));
+ const result = await intakeProviderMail(env, { from: getEmailAddress(email.from), recipients, raw: await rawResponse.arrayBuffer() });
+ return NextResponse.json(result);
+}
diff --git a/src/app/api/inbound/ses/route.ts b/src/app/api/inbound/ses/route.ts
new file mode 100644
index 0000000..537c087
--- /dev/null
+++ b/src/app/api/inbound/ses/route.ts
@@ -0,0 +1,54 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { requireAwsConfig } from "@/lib/aws/config";
+import { deleteObject, getObject } from "@/lib/aws/s3";
+import { getSesReceivingState, SES_OBJECT_PREFIX } from "@/lib/aws/ses-receiving";
+import { intakeProviderMail } from "@/lib/email/provider-intake";
+import { parseSesNotification, safeEqual, type SnsEnvelope } from "@/lib/aws/ses-notification";
+
+export const dynamic = "force-dynamic";
+
+/**
+ * Amazon SNS endpoint for SES inbound mail. SNS posts JSON as text/plain.
+ * Trust comes from three things rather than SNS's certificate signature: the
+ * secret token in the URL that only the subscription we created knows, the topic
+ * ARN matching ours, and the message itself being read from our own S3 bucket
+ * with our credentials, so a forged notification cannot inject content.
+ */
+export async function POST(request: Request) {
+ const env = getEnv();
+ const state = await getSesReceivingState(env);
+ const token = new URL(request.url).searchParams.get("token") ?? "";
+ if (!state || !safeEqual(token, state.token)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+
+ let envelope: SnsEnvelope;
+ try { envelope = JSON.parse(await request.text()) as SnsEnvelope; } catch { return NextResponse.json({ error: "Invalid body" }, { status: 400 }); }
+ if (envelope.TopicArn !== state.topicArn) return NextResponse.json({ error: "Unknown topic" }, { status: 403 });
+
+ if (envelope.Type === "SubscriptionConfirmation") {
+ const url = envelope.SubscribeURL ? new URL(envelope.SubscribeURL) : null;
+ if (!url || url.protocol !== "https:" || !/^sns\.[a-z0-9-]+\.amazonaws\.com$/.test(url.hostname)) {
+ return NextResponse.json({ error: "Invalid subscription URL" }, { status: 400 });
+ }
+ const confirmed = await fetch(url);
+ return NextResponse.json({ confirmed: confirmed.ok }, { status: confirmed.ok ? 200 : 502 });
+ }
+ if (envelope.Type !== "Notification") return NextResponse.json({ ignored: true });
+
+ const notification = parseSesNotification(envelope.Message ?? "");
+ if (!notification) return NextResponse.json({ ignored: true });
+ if (notification.bucket !== state.bucket || !notification.key.startsWith(SES_OBJECT_PREFIX)) {
+ return NextResponse.json({ error: "Unexpected object" }, { status: 400 });
+ }
+
+ const config = await requireAwsConfig(env);
+ if (notification.virusFailed) {
+ await deleteObject(config, state.bucket, notification.key);
+ return NextResponse.json({ dropped: "Message failed the virus scan" });
+ }
+ const raw = await getObject(config, state.bucket, notification.key);
+ const result = await intakeProviderMail(env, { from: notification.from, recipients: notification.recipients, raw, headers: notification.headers });
+ // Only after intake succeeded: a failure above returns 500 so SNS retries with the object intact.
+ await deleteObject(config, state.bucket, notification.key);
+ return NextResponse.json(result);
+}
diff --git a/src/app/api/v1/domains/route.ts b/src/app/api/v1/domains/route.ts
index 4a99fec..c9d1a91 100644
--- a/src/app/api/v1/domains/route.ts
+++ b/src/app/api/v1/domains/route.ts
@@ -51,6 +51,7 @@ export async function POST(request: Request) {
enableRouting: parsed.data.enableRouting,
enableSending: parsed.data.enableSending,
replaceMxRecords: parsed.data.replaceMxRecords,
+ receivingProvider: parsed.data.receivingProvider,
});
let dns = result.dns;
try {
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 2aac42f..4b1724d 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -50,6 +50,8 @@ export const domains = sqliteTable(
.default("pending"),
routingStatus: text("routing_status"),
sendingSubdomainTag: text("sending_subdomain_tag"),
+ sendingProvider: text("sending_provider", { enum: ["none", "cloudflare", "resend", "ses"] }).notNull().default("none"),
+ receivingProvider: text("receiving_provider", { enum: ["none", "cloudflare", "resend", "ses"] }).notNull().default("cloudflare"),
sendingRequested: integer("sending_requested", { mode: "boolean" }).notNull().default(false),
sendingEnabled: integer("sending_enabled", { mode: "boolean" }).notNull().default(false),
routingEnabled: integer("routing_enabled", { mode: "boolean" }).notNull().default(false),
@@ -639,6 +641,13 @@ export const appSettings = sqliteTable("app_settings", {
id: text("id").primaryKey(),
appName: text("app_name").notNull().default("Mailflare"),
outboundAttachmentMaxMb: integer("outbound_attachment_max_mb").notNull().default(25),
+ resendApiKey: text("resend_api_key"),
+ /** JSON: AWS access key, secret and region (see src/lib/aws/config.ts). */
+ awsConfig: text("aws_config"),
+ /** JSON: the shared SES inbound resources Mailflare created (bucket, topic, rule set, webhook token). */
+ sesReceiving: text("ses_receiving"),
+ resendWebhookId: text("resend_webhook_id"),
+ resendWebhookSecret: text("resend_webhook_secret"),
iconKey: text("icon_key"),
agentEnabled: integer("agent_enabled", { mode: "boolean" }).notNull().default(true),
agentProvider: text("agent_provider", { enum: ["cloudflare", "compatible"] }),
diff --git a/src/lib/aws/aws-types.d.ts b/src/lib/aws/aws-types.d.ts
new file mode 100644
index 0000000..9b1dd5b
--- /dev/null
+++ b/src/lib/aws/aws-types.d.ts
@@ -0,0 +1,53 @@
+export type AwsCredentials = {
+ accessKeyId: string;
+ secretAccessKey: string;
+ sessionToken?: string;
+};
+
+export type AwsConfig = AwsCredentials & {
+ region: string;
+};
+
+export type AwsConfigStatus = {
+ configured: boolean;
+ source: "settings" | "environment" | null;
+ region: string | null;
+ /** Last four characters of the access key id, for display. */
+ accessKeyHint: string | null;
+ accountId: string | null;
+};
+
+export type AwsCapabilityReport = {
+ accountId: string;
+ arn: string;
+ region: string;
+ /** SES can send (ses:GetAccount). */
+ sending: boolean;
+ /** The account is out of the SES sandbox; sandbox accounts reach verified recipients only. */
+ productionAccess: boolean | null;
+ /** SES inbound is offered in this region. */
+ receivingRegion: boolean;
+ receiving: boolean;
+ sns: boolean;
+ s3: boolean;
+ /** Capabilities the key lacks, as AWS actions, for the admin to grant. */
+ missing: string[];
+};
+
+export type SesReceivingState = {
+ region: string;
+ bucket: string;
+ topicArn: string;
+ ruleSet: string;
+ /** Secret in the SNS endpoint URL. */
+ token: string;
+ endpoint: string;
+ accountId: string;
+};
+
+export type SesIdentityStatus = {
+ registered: boolean;
+ verified: boolean;
+ dkimStatus: string;
+ records: { type: "CNAME"; name: string; value: string }[];
+};
diff --git a/src/lib/aws/client.ts b/src/lib/aws/client.ts
new file mode 100644
index 0000000..0c1790a
--- /dev/null
+++ b/src/lib/aws/client.ts
@@ -0,0 +1,87 @@
+import { signAwsRequest } from "@/lib/aws/sigv4";
+import { xmlTag } from "@/lib/aws/xml";
+import type { AwsConfig } from "@/lib/aws/aws-types";
+
+export class AwsError extends Error {
+ constructor(message: string, readonly status: number, readonly code: string) {
+ super(message);
+ }
+
+ get accessDenied(): boolean {
+ return /AccessDenied|UnauthorizedOperation|AuthorizationError|NotAuthorized|Forbidden/i.test(this.code) || this.status === 403;
+ }
+}
+
+async function parseError(response: Response): Promise<AwsError> {
+ const text = await response.text().catch(() => "");
+ let code = response.headers.get("x-amzn-errortype")?.split(":")[0] ?? "";
+ let message = "";
+ try {
+ const json = JSON.parse(text) as { __type?: string; message?: string; Message?: string };
+ code ||= json.__type?.split("#").pop() ?? "";
+ message = json.message ?? json.Message ?? "";
+ } catch {
+ code ||= xmlTag(text, "Code") ?? "";
+ message = xmlTag(text, "Message") ?? "";
+ }
+ return new AwsError(message || `AWS request failed (${response.status})`, response.status, code || `HTTP${response.status}`);
+}
+
+export type AwsRequest = {
+ config: AwsConfig;
+ service: string;
+ /** Defaults to `${service}.${region}.amazonaws.com`. */
+ host?: string;
+ method?: string;
+ path?: string;
+ query?: Record<string, string>;
+ body?: string | ArrayBuffer;
+ headers?: Record<string, string>;
+ /** Region used to sign; defaults to the config's. */
+ region?: string;
+};
+
+export async function awsRequest(request: AwsRequest): Promise<Response> {
+ const { config, service } = request;
+ const region = request.region ?? config.region;
+ const url = new URL(`https://${request.host ?? `${service}.${region}.amazonaws.com`}${request.path ?? "/"}`);
+ for (const [name, value] of Object.entries(request.query ?? {})) url.searchParams.set(name, value);
+ const body = request.body ?? "";
+ const method = request.method ?? "GET";
+ const headers = await signAwsRequest({ method, url, headers: request.headers ?? {}, body, region, service, credentials: config, });
+ const response = await fetch(url, { method, headers, body: method === "GET" || method === "HEAD" ? undefined : body });
+ if (!response.ok) throw await parseError(response);
+ return response;
+}
+
+/** AWS JSON REST (SES v2). */
+export async function awsJson<T>(request: AwsRequest & { json?: unknown }): Promise<T> {
+ const response = await awsRequest({
+ ...request,
+ body: request.json === undefined ? request.body : JSON.stringify(request.json),
+ headers: { "Content-Type": "application/json", ...request.headers },
+ });
+ const text = await response.text();
+ return (text ? JSON.parse(text) : {}) as T;
+}
+
+/** AWS Query protocol (STS, SNS, SES v1): form-encoded POST, XML back. */
+export async function awsQuery(
+ config: AwsConfig,
+ service: string,
+ version: string,
+ action: string,
+ params: Record<string, string> = {},
+ options: { host?: string; signingService?: string } = {},
+): Promise<string> {
+ const body = new URLSearchParams({ Action: action, Version: version, ...params }).toString();
+ const response = await awsRequest({
+ config,
+ service: options.signingService ?? service,
+ host: options.host ?? `${service}.${config.region}.amazonaws.com`,
+ method: "POST",
+ body,
+ headers: { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" },
+ });
+ return response.text();
+}
diff --git a/src/lib/aws/config.ts b/src/lib/aws/config.ts
new file mode 100644
index 0000000..ad33d93
--- /dev/null
+++ b/src/lib/aws/config.ts
@@ -0,0 +1,65 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { appSettings } from "@/db/schema";
+import type { AwsConfig, AwsConfigStatus } from "@/lib/aws/aws-types";
+
+/** Regions where SES can receive mail (SES inbound is not offered everywhere). */
+export const SES_RECEIVING_REGIONS = [
+ "us-east-1", "us-east-2", "us-west-2", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ap-northeast-1",
+ "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", "sa-east-1", "us-gov-west-1",
+];
+
+const REGION_PATTERN = /^[a-z]{2}(-gov)?-[a-z]+-\d$/;
+
+export function isValidRegion(region: string): boolean {
+ return REGION_PATTERN.test(region);
+}
+
+type StoredAws = { accessKeyId?: string; secretAccessKey?: string; region?: string; accountId?: string };
+
+async function readStored(env: CloudflareEnv): Promise<StoredAws | null> {
+ const [row] = await getDb(env).select({ awsConfig: appSettings.awsConfig }).from(appSettings).where(eq(appSettings.id, "default")).limit(1);
+ if (!row?.awsConfig) return null;
+ try { return JSON.parse(row.awsConfig) as StoredAws; } catch { return null; }
+}
+
+/** The saved AWS credentials, falling back to AWS_* environment variables. */
+export async function getAwsConfig(env: CloudflareEnv): Promise<AwsConfig | null> {
+ const stored = await readStored(env);
+ if (stored?.accessKeyId && stored.secretAccessKey && stored.region) {
+ return { accessKeyId: stored.accessKeyId, secretAccessKey: stored.secretAccessKey, region: stored.region };
+ }
+ const vars = env as unknown as Record<string, string | undefined>;
+ const accessKeyId = vars.AWS_ACCESS_KEY_ID?.trim();
+ const secretAccessKey = vars.AWS_SECRET_ACCESS_KEY?.trim();
+ const region = (vars.AWS_REGION ?? vars.AWS_DEFAULT_REGION)?.trim();
+ return accessKeyId && secretAccessKey && region ? { accessKeyId, secretAccessKey, region } : null;
+}
+
+export async function requireAwsConfig(env: CloudflareEnv): Promise<AwsConfig> {
+ const config = await getAwsConfig(env);
+ if (!config) throw new Error("AWS is selected but no credentials are configured");
+ return config;
+}
+
+export async function getAwsConfigStatus(env: CloudflareEnv): Promise<AwsConfigStatus> {
+ const stored = await readStored(env);
+ const config = await getAwsConfig(env);
+ if (!config) return { configured: false, source: null, region: null, accessKeyHint: null, accountId: null };
+ return {
+ configured: true,
+ source: stored?.accessKeyId ? "settings" : "environment",
+ region: config.region,
+ accessKeyHint: config.accessKeyId.slice(-4),
+ accountId: stored?.accountId ?? null,
+ };
+}
+
+export async function saveAwsConfig(env: CloudflareEnv, config: AwsConfig, accountId: string): Promise<void> {
+ const values = { awsConfig: JSON.stringify({ ...config, accountId }), updatedAt: new Date() };
+ await getDb(env).insert(appSettings).values({ id: "default", ...values }).onConflictDoUpdate({ target: appSettings.id, set: values });
+}
+
+export async function clearAwsConfig(env: CloudflareEnv): Promise<void> {
+ await getDb(env).update(appSettings).set({ awsConfig: null, updatedAt: new Date() }).where(eq(appSettings.id, "default"));
+}
diff --git a/src/lib/aws/s3.ts b/src/lib/aws/s3.ts
new file mode 100644
index 0000000..45696af
--- /dev/null
+++ b/src/lib/aws/s3.ts
@@ -0,0 +1,43 @@
+import { awsRequest, AwsError } from "@/lib/aws/client";
+import { sha256Hex } from "@/lib/aws/sigv4";
+import type { AwsConfig } from "@/lib/aws/aws-types";
+
+const bucketHost = (config: AwsConfig, bucket: string) => `${bucket}.s3.${config.region}.amazonaws.com`;
+
+export async function listBuckets(config: AwsConfig): Promise<void> {
+ await awsRequest({ config, service: "s3", host: `s3.${config.region}.amazonaws.com` });
+}
+
+export async function bucketExists(config: AwsConfig, bucket: string): Promise<boolean> {
+ try { await awsRequest({ config, service: "s3", host: bucketHost(config, bucket), method: "HEAD" }); return true; }
+ catch (error) { if (error instanceof AwsError && error.status === 404) return false; throw error; }
+}
+
+export async function createBucket(config: AwsConfig, bucket: string): Promise<void> {
+ const body = config.region === "us-east-1" ? "" : `<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>${config.region}</LocationConstraint></CreateBucketConfiguration>`;
+ try { await awsRequest({ config, service: "s3", host: bucketHost(config, bucket), method: "PUT", body }); }
+ catch (error) { if (!(error instanceof AwsError && error.code === "BucketAlreadyOwnedByYou")) throw error; }
+}
+
+export async function putBucketPolicy(config: AwsConfig, bucket: string, policy: unknown): Promise<void> {
+ await awsRequest({ config, service: "s3", host: bucketHost(config, bucket), method: "PUT", query: { policy: "" }, body: JSON.stringify(policy), headers: { "Content-Type": "application/json" } });
+}
+
+/** Expires leftover raw messages; best effort, since we delete each object after intake. */
+export async function putExpiryLifecycle(config: AwsConfig, bucket: string, prefix: string, days: number): Promise<void> {
+ const body = `<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><ID>mailflare-expire-inbound</ID><Filter><Prefix>${prefix}</Prefix></Filter><Status>Enabled</Status><Expiration><Days>${days}</Days></Expiration></Rule></LifecycleConfiguration>`;
+ const digest = new Uint8Array((await sha256Hex(body)).match(/../g)!.map((byte) => parseInt(byte, 16)));
+ await awsRequest({
+ config, service: "s3", host: bucketHost(config, bucket), method: "PUT", query: { lifecycle: "" }, body,
+ headers: { "Content-Type": "application/xml", "x-amz-sdk-checksum-algorithm": "SHA256", "x-amz-checksum-sha256": btoa(String.fromCharCode(...digest)) },
+ });
+}
+
+export async function getObject(config: AwsConfig, bucket: string, key: string): Promise<ArrayBuffer> {
+ const response = await awsRequest({ config, service: "s3", host: bucketHost(config, bucket), path: `/${key.split("/").map(encodeURIComponent).join("/")}` });
+ return response.arrayBuffer();
+}
+
+export async function deleteObject(config: AwsConfig, bucket: string, key: string): Promise<void> {
+ await awsRequest({ config, service: "s3", host: bucketHost(config, bucket), method: "DELETE", path: `/${key.split("/").map(encodeURIComponent).join("/")}` });
+}
diff --git a/src/lib/aws/ses-notification.ts b/src/lib/aws/ses-notification.ts
new file mode 100644
index 0000000..1f76468
--- /dev/null
+++ b/src/lib/aws/ses-notification.ts
@@ -0,0 +1,49 @@
+export type SnsEnvelope = {
+ Type?: string;
+ TopicArn?: string;
+ Message?: string;
+ SubscribeURL?: string;
+};
+
+export type SesNotification = {
+ from: string;
+ recipients: string[];
+ bucket: string;
+ key: string;
+ virusFailed: boolean;
+ headers: Record<string, string>;
+};
+
+type RawNotification = {
+ notificationType?: string;
+ mail?: { source?: string; destination?: string[]; headers?: { name: string; value: string }[] };
+ receipt?: {
+ recipients?: string[];
+ virusVerdict?: { status?: string };
+ action?: { type?: string; bucketName?: string; objectKey?: string };
+ };
+};
+
+/** Reads the JSON an SES S3 receipt action publishes to SNS; null for anything else. */
+export function parseSesNotification(message: string): SesNotification | null {
+ let parsed: RawNotification;
+ try { parsed = JSON.parse(message) as RawNotification; } catch { return null; }
+ const action = parsed.receipt?.action;
+ if (parsed.notificationType !== "Received" || action?.type !== "S3" || !action.bucketName || !action.objectKey) return null;
+ const recipients = parsed.receipt?.recipients ?? parsed.mail?.destination ?? [];
+ return {
+ from: parsed.mail?.source ?? "",
+ recipients,
+ bucket: action.bucketName,
+ key: action.objectKey,
+ virusFailed: parsed.receipt?.virusVerdict?.status === "FAIL",
+ headers: Object.fromEntries((parsed.mail?.headers ?? []).map((header) => [header.name.toLowerCase(), header.value])),
+ };
+}
+
+export function safeEqual(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+ let diff = 0;
+ for (let index = 0; index < a.length; index += 1) diff |= a.charCodeAt(index) ^ b.charCodeAt(index);
+ return diff === 0;
+}
diff --git a/src/lib/aws/ses-receiving-types.d.ts b/src/lib/aws/ses-receiving-types.d.ts
new file mode 100644
index 0000000..089aac0
--- /dev/null
+++ b/src/lib/aws/ses-receiving-types.d.ts
@@ -0,0 +1,15 @@
+export type ReceivingStep = {
+ key: string;
+ label: string;
+ ok: boolean;
+ detail?: string;
+};
+
+export type SesReceivingView = {
+ steps: ReceivingStep[];
+ ready: boolean;
+ region: string;
+ /** MX the domain must point at. */
+ mx: string;
+ dnsManaged: boolean;
+};
diff --git a/src/lib/aws/ses-receiving.ts b/src/lib/aws/ses-receiving.ts
new file mode 100644
index 0000000..c8af438
--- /dev/null
+++ b/src/lib/aws/ses-receiving.ts
@@ -0,0 +1,173 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { appSettings } from "@/db/schema";
+import { requireAwsConfig, SES_RECEIVING_REGIONS } from "@/lib/aws/config";
+import { AwsError } from "@/lib/aws/client";
+import { activateRuleSet, createRuleSet, deleteReceiptRule, describeActiveRuleSet, describeReceiptRule, upsertReceiptRule } from "@/lib/aws/ses";
+import { bucketExists, createBucket, putBucketPolicy, putExpiryLifecycle } from "@/lib/aws/s3";
+import { createTopic, listSubscriptions, setTopicPolicy, subscribeHttps } from "@/lib/aws/sns";
+import { getCallerIdentity } from "@/lib/aws/sts";
+import { hasMx, isInboundSmtpMx, publishMx, removeMx } from "@/lib/domains/receiving-dns";
+import { isManualZone } from "@/lib/domains/provision";
+import type { SesReceivingState } from "@/lib/aws/aws-types";
+import type { ReceivingStep, SesReceivingView } from "@/lib/aws/ses-receiving-types";
+import type { DomainRow } from "@/lib/domains/types";
+
+export const SES_OBJECT_PREFIX = "inbound/";
+const RULE_SET = "mailflare-inbound";
+const TOPIC_NAME = "mailflare-inbound";
+
+export const sesInboundMx = (region: string) => `inbound-smtp.${region}.amazonaws.com`;
+const ruleName = (hostname: string) => `mailflare-${hostname.replace(/[^a-zA-Z0-9-_]/g, "-")}`.slice(0, 64);
+
+export async function getSesReceivingState(env: CloudflareEnv): Promise<SesReceivingState | null> {
+ const [row] = await getDb(env).select({ value: appSettings.sesReceiving }).from(appSettings).where(eq(appSettings.id, "default")).limit(1);
+ if (!row?.value) return null;
+ try { return JSON.parse(row.value) as SesReceivingState; } catch { return null; }
+}
+
+async function saveState(env: CloudflareEnv, state: SesReceivingState): Promise<void> {
+ const values = { sesReceiving: JSON.stringify(state), updatedAt: new Date() };
+ await getDb(env).insert(appSettings).values({ id: "default", ...values }).onConflictDoUpdate({ target: appSettings.id, set: values });
+}
+
+function isPublicHttps(origin: string): boolean {
+ try {
+ const url = new URL(origin);
+ return url.protocol === "https:" && !/^(localhost|127\.|\[::1\]|.*\.localhost$|.*\.test$)/.test(url.hostname);
+ } catch { return false; }
+}
+
+/**
+ * Creates what SES needs to hand Mailflare a message: an S3 bucket SES may write
+ * to, an SNS topic SES may publish to (subscribed to this app's signed endpoint),
+ * and a receipt rule for the domain, then points the domain's MX at SES.
+ * Everything is idempotent, so running it again repairs a partial setup.
+ */
+export async function setupSesReceiving(
+ env: CloudflareEnv,
+ domain: DomainRow,
+ origin: string,
+ options: { replaceMx: boolean },
+): Promise<void> {
+ const config = await requireAwsConfig(env);
+ if (!SES_RECEIVING_REGIONS.includes(config.region)) {
+ throw new Error(`Amazon SES cannot receive mail in ${config.region}. Use a region such as us-east-1, us-west-2 or eu-west-1.`);
+ }
+ if (!isPublicHttps(origin)) {
+ throw new Error("SES delivers mail by calling this app over public HTTPS. Set APP_URL to your public address (localhost will not work).");
+ }
+ const { accountId } = await getCallerIdentity(config);
+ const previous = await getSesReceivingState(env);
+ const state: SesReceivingState = {
+ region: config.region,
+ accountId,
+ bucket: `mailflare-inbound-${accountId}-${config.region}`,
+ topicArn: "",
+ ruleSet: previous?.ruleSet ?? RULE_SET,
+ token: previous?.token ?? crypto.randomUUID().replace(/-/g, ""),
+ endpoint: `${origin.replace(/\/$/, "")}/api/inbound/ses?token=`,
+ };
+ state.endpoint += state.token;
+
+ await createBucket(config, state.bucket);
+ await putBucketPolicy(config, state.bucket, {
+ Version: "2012-10-17",
+ Statement: [{
+ Sid: "AllowSESPuts",
+ Effect: "Allow",
+ Principal: { Service: "ses.amazonaws.com" },
+ Action: "s3:PutObject",
+ Resource: `arn:aws:s3:::${state.bucket}/*`,
+ Condition: { StringEquals: { "aws:Referer": accountId } },
+ }],
+ });
+ await putExpiryLifecycle(config, state.bucket, SES_OBJECT_PREFIX, 1).catch(() => undefined);
+
+ state.topicArn = await createTopic(config, TOPIC_NAME);
+ await setTopicPolicy(config, state.topicArn, {
+ Version: "2008-10-17",
+ Statement: [
+ {
+ Sid: "AllowOwner",
+ Effect: "Allow",
+ Principal: { AWS: "*" },
+ Action: ["SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission", "SNS:RemovePermission", "SNS:DeleteTopic", "SNS:Subscribe", "SNS:ListSubscriptionsByTopic", "SNS:Publish"],
+ Resource: state.topicArn,
+ Condition: { StringEquals: { "AWS:SourceOwner": accountId } },
+ },
+ {
+ Sid: "AllowSESPublish",
+ Effect: "Allow",
+ Principal: { Service: "ses.amazonaws.com" },
+ Action: "SNS:Publish",
+ Resource: state.topicArn,
+ Condition: { StringEquals: { "AWS:SourceAccount": accountId } },
+ },
+ ],
+ });
+ const subscriptions = await listSubscriptions(config, state.topicArn);
+ if (!subscriptions.some((subscription) => subscription.endpoint === state.endpoint)) {
+ await subscribeHttps(config, state.topicArn, state.endpoint);
+ }
+
+ // Only one rule set is active per region. Use the account's own if it has one
+ // (adding our rule beside theirs); otherwise create and activate ours.
+ const active = await describeActiveRuleSet(config);
+ if (active.name) state.ruleSet = active.name;
+ else {
+ await createRuleSet(config, state.ruleSet);
+ await activateRuleSet(config, state.ruleSet);
+ }
+ await upsertReceiptRule(config, {
+ ruleSet: state.ruleSet,
+ name: ruleName(domain.hostname),
+ recipient: domain.hostname,
+ bucket: state.bucket,
+ prefix: SES_OBJECT_PREFIX,
+ topicArn: state.topicArn,
+ });
+ await saveState(env, state);
+
+ await publishMx(env, domain, sesInboundMx(config.region), { replace: options.replaceMx });
+}
+
+export async function getSesReceivingView(env: CloudflareEnv, domain: DomainRow): Promise<SesReceivingView> {
+ const config = await requireAwsConfig(env);
+ const state = await getSesReceivingState(env);
+ const mx = sesInboundMx(config.region);
+ const steps: ReceivingStep[] = [];
+ const regionOk = SES_RECEIVING_REGIONS.includes(config.region);
+ steps.push({ key: "region", label: "Region supports receiving", ok: regionOk, detail: regionOk ? config.region : `${config.region} cannot receive mail` });
+
+ const attempt = async (run: () => Promise<boolean>): Promise<boolean> => {
+ try { return await run(); } catch (error) { if (error instanceof AwsError) return false; throw error; }
+ };
+ const bucketOk = !!state && await attempt(() => bucketExists(config, state.bucket));
+ steps.push({ key: "bucket", label: "S3 bucket for raw mail", ok: bucketOk, detail: state?.bucket });
+ const subscribed = !!state && await attempt(async () => (await listSubscriptions(config, state.topicArn)).some((subscription) => subscription.endpoint === state.endpoint && subscription.confirmed));
+ steps.push({ key: "topic", label: "SNS topic delivering to Mailflare", ok: subscribed, detail: state && !subscribed ? "Subscription not confirmed yet" : undefined });
+ const ruleOk = !!state && await attempt(() => describeReceiptRule(config, state.ruleSet, ruleName(domain.hostname)));
+ steps.push({ key: "rule", label: "SES receipt rule for this domain", ok: ruleOk, detail: ruleOk ? state?.ruleSet : undefined });
+ const mxOk = await hasMx(env, domain, mx);
+ steps.push({ key: "mx", label: "MX record points to SES", ok: mxOk === true, detail: mxOk === null ? "Add the MX record in your DNS" : mx });
+
+ return { steps, ready: steps.every((step) => step.ok), region: config.region, mx, dnsManaged: !isManualZone(domain.zoneId) };
+}
+
+/** Removes this domain's rule and MX. The shared bucket and topic stay for other domains. */
+export async function removeSesReceiving(env: CloudflareEnv, domain: DomainRow): Promise<void> {
+ const config = await requireAwsConfig(env);
+ const state = await getSesReceivingState(env);
+ if (state) await deleteReceiptRule(config, state.ruleSet, ruleName(domain.hostname));
+ await removeMx(env, domain, isInboundSmtpMx);
+}
+
+export async function hasSesReceivingConfig(env: CloudflareEnv, domain: DomainRow): Promise<boolean | null> {
+ try {
+ const config = await requireAwsConfig(env);
+ const state = await getSesReceivingState(env);
+ if (!state) return false;
+ return await describeReceiptRule(config, state.ruleSet, ruleName(domain.hostname));
+ } catch { return null; }
+}
diff --git a/src/lib/aws/ses-sending-types.d.ts b/src/lib/aws/ses-sending-types.d.ts
new file mode 100644
index 0000000..57be83e
--- /dev/null
+++ b/src/lib/aws/ses-sending-types.d.ts
@@ -0,0 +1,11 @@
+export type SesSendingView = {
+ registered: boolean;
+ verified: boolean;
+ dkimStatus: string;
+ records: { type: "CNAME"; name: string; value: string }[];
+ dnsManaged: boolean;
+ missingDns: number | null;
+ /** False while the account is in the SES sandbox. */
+ productionAccess: boolean | null;
+ region: string;
+};
diff --git a/src/lib/aws/ses-sending.ts b/src/lib/aws/ses-sending.ts
new file mode 100644
index 0000000..76ab5a9
--- /dev/null
+++ b/src/lib/aws/ses-sending.ts
@@ -0,0 +1,66 @@
+import { createDnsRecord, deleteDnsRecord, listDnsRecords } from "@/lib/cloudflare-dns";
+import { isManualZone } from "@/lib/domains/provision";
+import { requireAwsConfig } from "@/lib/aws/config";
+import { createSesIdentity, deleteSesIdentity, getSesAccount, getSesIdentity } from "@/lib/aws/ses";
+import type { DomainRow } from "@/lib/domains/types";
+import type { SesSendingView } from "@/lib/aws/ses-sending-types";
+
+const same = (a: string, b: string) => a.trim().toLowerCase().replace(/\.$/, "") === b.trim().toLowerCase().replace(/\.$/, "");
+
+async function missingRecords(env: CloudflareEnv, domain: DomainRow, records: { name: string; value: string }[]): Promise<number | null> {
+ if (isManualZone(domain.zoneId)) return null;
+ try {
+ const present = await Promise.all(records.map(async (record) => {
+ const existing = await listDnsRecords(env, domain.zoneId, { type: "CNAME", name: record.name });
+ return existing.some((item) => same(item.content ?? "", record.value));
+ }));
+ return present.filter((exists) => !exists).length;
+ } catch { return null; }
+}
+
+async function view(env: CloudflareEnv, domain: DomainRow): Promise<SesSendingView> {
+ const config = await requireAwsConfig(env);
+ const [identity, account] = await Promise.all([
+ getSesIdentity(config, domain.hostname),
+ getSesAccount(config).catch(() => null),
+ ]);
+ return {
+ registered: identity.registered,
+ verified: identity.verified,
+ dkimStatus: identity.dkimStatus,
+ records: identity.records,
+ dnsManaged: !isManualZone(domain.zoneId),
+ missingDns: identity.registered ? await missingRecords(env, domain, identity.records) : null,
+ productionAccess: account?.productionAccess ?? null,
+ region: config.region,
+ };
+}
+
+export const getSesSendingView = view;
+
+/** Registers the domain identity in SES and publishes its DKIM CNAMEs to the Cloudflare zone. */
+export async function setupSesSending(env: CloudflareEnv, domain: DomainRow): Promise<SesSendingView> {
+ const config = await requireAwsConfig(env);
+ const identity = await createSesIdentity(config, domain.hostname);
+ if (!isManualZone(domain.zoneId)) {
+ for (const record of identity.records) {
+ const existing = await listDnsRecords(env, domain.zoneId, { type: "CNAME", name: record.name });
+ if (existing.some((item) => same(item.content ?? "", record.value))) continue;
+ await createDnsRecord(env, domain.zoneId, { type: "CNAME", name: record.name, content: record.value, ttl: 3600, proxied: false });
+ }
+ }
+ return view(env, domain);
+}
+
+export async function removeSesSending(env: CloudflareEnv, domain: DomainRow): Promise<void> {
+ const config = await requireAwsConfig(env);
+ const identity = await getSesIdentity(config, domain.hostname);
+ if (!isManualZone(domain.zoneId)) {
+ for (const record of identity.records) {
+ for (const item of await listDnsRecords(env, domain.zoneId, { type: "CNAME", name: record.name })) {
+ if (item.id && same(item.content ?? "", record.value)) await deleteDnsRecord(env, domain.zoneId, item.id);
+ }
+ }
+ }
+ await deleteSesIdentity(config, domain.hostname);
+}
diff --git a/src/lib/aws/ses.ts b/src/lib/aws/ses.ts
new file mode 100644
index 0000000..ef6baba
--- /dev/null
+++ b/src/lib/aws/ses.ts
@@ -0,0 +1,173 @@
+import { awsJson, awsQuery, AwsError } from "@/lib/aws/client";
+import { xmlBlocks, xmlTag, xmlTags } from "@/lib/aws/xml";
+import type { AwsConfig, SesIdentityStatus } from "@/lib/aws/aws-types";
+
+// --- SES v2 (sending, identities) -------------------------------------------------
+
+export async function getSesAccount(config: AwsConfig): Promise<{ productionAccess: boolean; sendingEnabled: boolean }> {
+ const account = await awsJson<{ ProductionAccessEnabled?: boolean; SendingEnabled?: boolean }>({ config, service: "ses", host: `email.${config.region}.amazonaws.com`, path: "/v2/email/account" });
+ return { productionAccess: !!account.ProductionAccessEnabled, sendingEnabled: account.SendingEnabled !== false };
+}
+
+type SesIdentity = {
+ VerifiedForSendingStatus?: boolean;
+ DkimAttributes?: { Status?: string; Tokens?: string[] };
+};
+
+function toIdentityStatus(hostname: string, identity: SesIdentity | null): SesIdentityStatus {
+ if (!identity) return { registered: false, verified: false, dkimStatus: "NOT_REGISTERED", records: [] };
+ return {
+ registered: true,
+ verified: !!identity.VerifiedForSendingStatus,
+ dkimStatus: identity.DkimAttributes?.Status ?? "NOT_STARTED",
+ records: (identity.DkimAttributes?.Tokens ?? []).map((token) => ({
+ type: "CNAME" as const,
+ name: `${token}._domainkey.${hostname}`,
+ value: `${token}.dkim.amazonses.com`,
+ })),
+ };
+}
+
+const sesV2 = (config: AwsConfig, path: string) => ({ config, service: "ses", host: `email.${config.region}.amazonaws.com`, path });
+
+export async function getSesIdentity(config: AwsConfig, hostname: string): Promise<SesIdentityStatus> {
+ try {
+ const identity = await awsJson<SesIdentity>(sesV2(config, `/v2/email/identities/${encodeURIComponent(hostname)}`));
+ return toIdentityStatus(hostname, identity);
+ } catch (error) {
+ if (error instanceof AwsError && (error.code === "NotFoundException" || error.status === 404)) return toIdentityStatus(hostname, null);
+ throw error;
+ }
+}
+
+export async function createSesIdentity(config: AwsConfig, hostname: string): Promise<SesIdentityStatus> {
+ try {
+ const identity = await awsJson<SesIdentity>({ ...sesV2(config, "/v2/email/identities"), method: "POST", json: { EmailIdentity: hostname, DkimSigningAttributes: { NextSigningKeyLength: "RSA_2048_BIT" } } });
+ return toIdentityStatus(hostname, identity);
+ } catch (error) {
+ if (error instanceof AwsError && error.code === "AlreadyExistsException") return getSesIdentity(config, hostname);
+ throw error;
+ }
+}
+
+export async function deleteSesIdentity(config: AwsConfig, hostname: string): Promise<void> {
+ try {
+ await awsJson({ ...sesV2(config, `/v2/email/identities/${encodeURIComponent(hostname)}`), method: "DELETE" });
+ } catch (error) {
+ if (!(error instanceof AwsError && error.status === 404)) throw error;
+ }
+}
+
+export type SesSendInput = {
+ from: string;
+ to: string[];
+ cc?: string[];
+ bcc?: string[];
+ subject: string;
+ html?: string;
+ text?: string;
+ headers?: Record<string, string>;
+ attachments?: { filename: string; type: string; content: ArrayBuffer; disposition: "attachment" | "inline"; contentId?: string | null }[];
+};
+
+function toBase64(buffer: ArrayBuffer): string {
+ const bytes = new Uint8Array(buffer);
+ let binary = "";
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ return btoa(binary);
+}
+
+export async function sendSesEmail(config: AwsConfig, input: SesSendInput): Promise<{ messageId: string }> {
+ const headers = Object.entries(input.headers ?? {}).filter(([name]) => name.toLowerCase() !== "message-id").map(([Name, Value]) => ({ Name, Value }));
+ const result = await awsJson<{ MessageId: string }>({
+ ...sesV2(config, "/v2/email/outbound-emails"),
+ method: "POST",
+ json: {
+ FromEmailAddress: input.from,
+ Destination: { ToAddresses: input.to, ...(input.cc?.length ? { CcAddresses: input.cc } : {}), ...(input.bcc?.length ? { BccAddresses: input.bcc } : {}) },
+ Content: {
+ Simple: {
+ Subject: { Data: input.subject, Charset: "UTF-8" },
+ Body: {
+ ...(input.text ? { Text: { Data: input.text, Charset: "UTF-8" } } : {}),
+ ...(input.html ? { Html: { Data: input.html, Charset: "UTF-8" } } : {}),
+ },
+ ...(headers.length ? { Headers: headers } : {}),
+ ...(input.attachments?.length ? {
+ Attachments: input.attachments.map((attachment) => ({
+ RawContent: toBase64(attachment.content),
+ FileName: attachment.filename,
+ ContentType: attachment.type,
+ ContentDisposition: attachment.disposition === "inline" ? "INLINE" : "ATTACHMENT",
+ ...(attachment.disposition === "inline" && attachment.contentId ? { ContentId: attachment.contentId } : {}),
+ ContentTransferEncoding: "BASE64",
+ })),
+ } : {}),
+ },
+ },
+ },
+ });
+ // SES rewrites Message-ID to <[email protected]> (us-east-1) or <[email protected]>.
+ const domain = config.region === "us-east-1" ? "email.amazonses.com" : `${config.region}.amazonses.com`;
+ return { messageId: `<${result.MessageId}@${domain}>` };
+}
+
+// --- SES v1 (receipt rules; not available in v2) ---------------------------------
+
+const query = (config: AwsConfig, action: string, params: Record<string, string> = {}) =>
+ awsQuery(config, "email", "2010-12-01", action, params, { host: `email.${config.region}.amazonaws.com`, signingService: "ses" });
+
+export async function describeActiveRuleSet(config: AwsConfig): Promise<{ name: string | null; rules: string[] }> {
+ const xml = await query(config, "DescribeActiveReceiptRuleSet");
+ const metadata = xmlBlocks(xml, "Metadata")[0] ?? "";
+ const rulesXml = xmlBlocks(xml, "Rules")[0] ?? "";
+ return { name: xmlTag(metadata, "Name"), rules: xmlBlocks(rulesXml, "member").map((member) => xmlTag(member, "Name") ?? "").filter(Boolean) };
+}
+
+export async function createRuleSet(config: AwsConfig, name: string): Promise<void> {
+ try { await query(config, "CreateReceiptRuleSet", { RuleSetName: name }); }
+ catch (error) { if (!(error instanceof AwsError && error.code === "AlreadyExists")) throw error; }
+}
+
+export async function activateRuleSet(config: AwsConfig, name: string): Promise<void> {
+ await query(config, "SetActiveReceiptRuleSet", { RuleSetName: name });
+}
+
+export type ReceiptRuleInput = { ruleSet: string; name: string; recipient: string; bucket: string; prefix: string; topicArn: string };
+
+function ruleParams(input: ReceiptRuleInput): Record<string, string> {
+ return {
+ RuleSetName: input.ruleSet,
+ "Rule.Name": input.name,
+ "Rule.Enabled": "true",
+ "Rule.ScanEnabled": "true",
+ "Rule.TlsPolicy": "Optional",
+ "Rule.Recipients.member.1": input.recipient,
+ "Rule.Actions.member.1.S3Action.BucketName": input.bucket,
+ "Rule.Actions.member.1.S3Action.ObjectKeyPrefix": input.prefix,
+ "Rule.Actions.member.1.S3Action.TopicArn": input.topicArn,
+ };
+}
+
+export async function upsertReceiptRule(config: AwsConfig, input: ReceiptRuleInput): Promise<void> {
+ try { await query(config, "CreateReceiptRule", ruleParams(input)); }
+ catch (error) {
+ if (error instanceof AwsError && error.code === "AlreadyExists") await query(config, "UpdateReceiptRule", ruleParams(input));
+ else throw error;
+ }
+}
+
+export async function describeReceiptRule(config: AwsConfig, ruleSet: string, name: string): Promise<boolean> {
+ try { await query(config, "DescribeReceiptRule", { RuleSetName: ruleSet, RuleName: name }); return true; }
+ catch (error) {
+ if (error instanceof AwsError && /DoesNotExist/.test(error.code)) return false;
+ throw error;
+ }
+}
+
+export async function deleteReceiptRule(config: AwsConfig, ruleSet: string, name: string): Promise<void> {
+ try { await query(config, "DeleteReceiptRule", { RuleSetName: ruleSet, RuleName: name }); }
+ catch (error) { if (!(error instanceof AwsError && /DoesNotExist/.test(error.code))) throw error; }
+}
+
+export { xmlTags };
diff --git a/src/lib/aws/sigv4.ts b/src/lib/aws/sigv4.ts
new file mode 100644
index 0000000..36718f6
--- /dev/null
+++ b/src/lib/aws/sigv4.ts
@@ -0,0 +1,76 @@
+import type { AwsCredentials } from "@/lib/aws/aws-types";
+
+const encoder = new TextEncoder();
+
+function hex(buffer: ArrayBuffer): string {
+ return Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0")).join("");
+}
+
+export async function sha256Hex(data: string | ArrayBuffer | Uint8Array): Promise<string> {
+ const bytes = typeof data === "string" ? encoder.encode(data) : data;
+ return hex(await crypto.subtle.digest("SHA-256", bytes as BufferSource));
+}
+
+async function hmac(key: ArrayBuffer | Uint8Array, data: string): Promise<ArrayBuffer> {
+ const imported = await crypto.subtle.importKey("raw", key as BufferSource, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ return crypto.subtle.sign("HMAC", imported, encoder.encode(data));
+}
+
+const rfc3986 = (value: string) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
+
+export type SignInput = {
+ method: string;
+ url: URL;
+ headers: Record<string, string>;
+ body: string | ArrayBuffer | Uint8Array;
+ region: string;
+ service: string;
+ credentials: AwsCredentials;
+ now?: Date;
+};
+
+/**
+ * AWS Signature Version 4. Returns the headers to send, including Authorization.
+ * Web Crypto only, so it runs on Workers and in the Node build alike.
+ */
+export async function signAwsRequest(input: SignInput): Promise<Record<string, string>> {
+ const { method, url, region, service, credentials } = input;
+ const amzDate = (input.now ?? new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
+ const dateStamp = amzDate.slice(0, 8);
+ const payloadHash = await sha256Hex(input.body);
+
+ const headers: Record<string, string> = { ...input.headers, host: url.host, "x-amz-date": amzDate };
+ if (service === "s3") headers["x-amz-content-sha256"] = payloadHash;
+ if (credentials.sessionToken) headers["x-amz-security-token"] = credentials.sessionToken;
+
+ const normalized = Object.entries(headers)
+ .map(([name, value]) => [name.toLowerCase(), value.trim().replace(/\s+/g, " ")] as const)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ const signedHeaders = normalized.map(([name]) => name).join(";");
+ const canonicalHeaders = normalized.map(([name, value]) => `${name}:${value}\n`).join("");
+
+ // S3 signs the path as sent; every other service signs it percent-encoded twice.
+ const canonicalPath = service === "s3"
+ ? url.pathname || "/"
+ : (url.pathname || "/").split("/").map((segment) => rfc3986(decodeURIComponent(segment))).join("/");
+ const canonicalQuery = [...url.searchParams.entries()]
+ .map(([name, value]) => [rfc3986(name), rfc3986(value)] as const)
+ .sort(([a, av], [b, bv]) => (a < b ? -1 : a > b ? 1 : av < bv ? -1 : av > bv ? 1 : 0))
+ .map(([name, value]) => `${name}=${value}`)
+ .join("&");
+
+ const canonicalRequest = [method, canonicalPath, canonicalQuery, canonicalHeaders, signedHeaders, payloadHash].join("\n");
+ const scope = `${dateStamp}/${region}/${service}/aws4_request`;
+ const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, await sha256Hex(canonicalRequest)].join("\n");
+
+ const kDate = await hmac(encoder.encode(`AWS4${credentials.secretAccessKey}`), dateStamp);
+ const kRegion = await hmac(kDate, region);
+ const kService = await hmac(kRegion, service);
+ const kSigning = await hmac(kService, "aws4_request");
+ const signature = hex(await hmac(kSigning, stringToSign));
+
+ return {
+ ...headers,
+ Authorization: `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
+ };
+}
diff --git a/src/lib/aws/sns.ts b/src/lib/aws/sns.ts
new file mode 100644
index 0000000..40a4263
--- /dev/null
+++ b/src/lib/aws/sns.ts
@@ -0,0 +1,34 @@
+import { awsQuery } from "@/lib/aws/client";
+import { xmlBlocks, xmlTag } from "@/lib/aws/xml";
+import type { AwsConfig } from "@/lib/aws/aws-types";
+
+const query = (config: AwsConfig, action: string, params: Record<string, string> = {}) =>
+ awsQuery(config, "sns", "2010-03-31", action, params);
+
+export async function listTopics(config: AwsConfig): Promise<void> {
+ await query(config, "ListTopics");
+}
+
+/** Idempotent: creating a topic that exists returns the same ARN. */
+export async function createTopic(config: AwsConfig, name: string): Promise<string> {
+ const xml = await query(config, "CreateTopic", { Name: name });
+ const arn = xmlTag(xml, "TopicArn");
+ if (!arn) throw new Error("SNS did not return a topic ARN");
+ return arn;
+}
+
+export async function setTopicPolicy(config: AwsConfig, topicArn: string, policy: unknown): Promise<void> {
+ await query(config, "SetTopicAttributes", { TopicArn: topicArn, AttributeName: "Policy", AttributeValue: JSON.stringify(policy) });
+}
+
+export async function subscribeHttps(config: AwsConfig, topicArn: string, endpoint: string): Promise<void> {
+ await query(config, "Subscribe", { TopicArn: topicArn, Protocol: "https", Endpoint: endpoint, ReturnSubscriptionArn: "true" });
+}
+
+export async function listSubscriptions(config: AwsConfig, topicArn: string): Promise<{ endpoint: string; confirmed: boolean }[]> {
+ const xml = await query(config, "ListSubscriptionsByTopic", { TopicArn: topicArn });
+ return xmlBlocks(xml, "member").map((member) => ({
+ endpoint: xmlTag(member, "Endpoint") ?? "",
+ confirmed: !!xmlTag(member, "SubscriptionArn") && xmlTag(member, "SubscriptionArn") !== "PendingConfirmation",
+ }));
+}
diff --git a/src/lib/aws/sts.ts b/src/lib/aws/sts.ts
new file mode 100644
index 0000000..fad2e3c
--- /dev/null
+++ b/src/lib/aws/sts.ts
@@ -0,0 +1,9 @@
+import { awsQuery } from "@/lib/aws/client";
+import { xmlTag } from "@/lib/aws/xml";
+import type { AwsConfig } from "@/lib/aws/aws-types";
+
+/** Proves the credentials are real and says whose they are. */
+export async function getCallerIdentity(config: AwsConfig): Promise<{ accountId: string; arn: string }> {
+ const xml = await awsQuery(config, "sts", "2011-06-15", "GetCallerIdentity");
+ return { accountId: xmlTag(xml, "Account") ?? "", arn: xmlTag(xml, "Arn") ?? "" };
+}
diff --git a/src/lib/aws/validate.ts b/src/lib/aws/validate.ts
new file mode 100644
index 0000000..2d19b48
--- /dev/null
+++ b/src/lib/aws/validate.ts
@@ -0,0 +1,65 @@
+import { AwsError } from "@/lib/aws/client";
+import { isValidRegion, SES_RECEIVING_REGIONS } from "@/lib/aws/config";
+import { describeActiveRuleSet, getSesAccount } from "@/lib/aws/ses";
+import { listBuckets } from "@/lib/aws/s3";
+import { listTopics } from "@/lib/aws/sns";
+import { getCallerIdentity } from "@/lib/aws/sts";
+import type { AwsCapabilityReport, AwsConfig } from "@/lib/aws/aws-types";
+
+async function probe(run: () => Promise<unknown>): Promise<boolean> {
+ try { await run(); return true; }
+ catch (error) {
+ if (error instanceof AwsError && error.accessDenied) return false;
+ throw error;
+ }
+}
+
+/** Thrown for credentials AWS refuses outright, as opposed to missing permissions. */
+export class AwsCredentialsError extends Error {}
+
+/**
+ * Checks the credentials really belong to an account, then probes each service
+ * Mailflare needs with a harmless read, so missing permissions are reported up
+ * front instead of halfway through a setup.
+ */
+export async function validateAwsConfig(config: AwsConfig): Promise<AwsCapabilityReport> {
+ if (!isValidRegion(config.region)) throw new AwsCredentialsError(`"${config.region}" is not a valid AWS region`);
+ let identity: { accountId: string; arn: string };
+ try {
+ identity = await getCallerIdentity(config);
+ } catch (error) {
+ if (error instanceof AwsError) {
+ if (/InvalidClientTokenId|SignatureDoesNotMatch|IncompleteSignature|UnrecognizedClient|InvalidAccessKeyId/i.test(error.code)) {
+ throw new AwsCredentialsError("AWS rejected these credentials. Check the access key ID and secret.");
+ }
+ if (/ExpiredToken/i.test(error.code)) throw new AwsCredentialsError("These AWS credentials have expired.");
+ throw new AwsCredentialsError(`AWS: ${error.message}`);
+ }
+ throw error;
+ }
+
+ const missing: string[] = [];
+ let productionAccess: boolean | null = null;
+ const sending = await probe(async () => { productionAccess = (await getSesAccount(config)).productionAccess; });
+ if (!sending) missing.push("ses:GetAccount", "ses:SendEmail", "ses:CreateEmailIdentity", "ses:GetEmailIdentity");
+ const receivingRegion = SES_RECEIVING_REGIONS.includes(config.region);
+ const receiving = await probe(() => describeActiveRuleSet(config));
+ if (!receiving) missing.push("ses:DescribeActiveReceiptRuleSet", "ses:CreateReceiptRule", "ses:SetActiveReceiptRuleSet");
+ const sns = await probe(() => listTopics(config));
+ if (!sns) missing.push("sns:CreateTopic", "sns:Subscribe", "sns:SetTopicAttributes");
+ const s3 = await probe(() => listBuckets(config));
+ if (!s3) missing.push("s3:CreateBucket", "s3:PutBucketPolicy", "s3:GetObject", "s3:DeleteObject");
+
+ return { ...identity, region: config.region, sending, productionAccess, receivingRegion, receiving, sns, s3, missing };
+}
+
+/** The IAM policy that grants everything Mailflare does, for the admin to attach. */
+export const AWS_IAM_POLICY = {
+ Version: "2012-10-17",
+ Statement: [
+ { Effect: "Allow", Action: ["sts:GetCallerIdentity", "ses:GetAccount", "ses:SendEmail", "ses:CreateEmailIdentity", "ses:GetEmailIdentity", "ses:DeleteEmailIdentity"], Resource: "*" },
+ { Effect: "Allow", Action: ["ses:DescribeActiveReceiptRuleSet", "ses:CreateReceiptRuleSet", "ses:SetActiveReceiptRuleSet", "ses:CreateReceiptRule", "ses:UpdateReceiptRule", "ses:DescribeReceiptRule", "ses:DeleteReceiptRule"], Resource: "*" },
+ { Effect: "Allow", Action: ["sns:ListTopics", "sns:CreateTopic", "sns:SetTopicAttributes", "sns:Subscribe", "sns:ListSubscriptionsByTopic"], Resource: "*" },
+ { Effect: "Allow", Action: ["s3:ListAllMyBuckets", "s3:CreateBucket", "s3:PutBucketPolicy", "s3:PutLifecycleConfiguration", "s3:ListBucket", "s3:GetObject", "s3:DeleteObject"], Resource: "*" },
+ ],
+};
diff --git a/src/lib/aws/xml.ts b/src/lib/aws/xml.ts
new file mode 100644
index 0000000..2a97366
--- /dev/null
+++ b/src/lib/aws/xml.ts
@@ -0,0 +1,18 @@
+/** AWS Query and S3 responses are small flat XML documents; these helpers read them without a parser. */
+
+const unescapeXml = (value: string) =>
+ value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&");
+
+export function xmlTag(xml: string, name: string): string | null {
+ const match = new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`).exec(xml);
+ return match ? unescapeXml(match[1].trim()) : null;
+}
+
+export function xmlTags(xml: string, name: string): string[] {
+ return [...xml.matchAll(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`, "g"))].map((match) => unescapeXml(match[1].trim()));
+}
+
+/** Raw (still escaped) inner XML of each repeated element, for reading nested fields. */
+export function xmlBlocks(xml: string, name: string): string[] {
+ return [...xml.matchAll(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`, "g"))].map((match) => match[1]);
+}
diff --git a/src/lib/cloudflare-dns.types.d.ts b/src/lib/cloudflare-dns.types.d.ts
index 124acac..538a775 100644
--- a/src/lib/cloudflare-dns.types.d.ts
+++ b/src/lib/cloudflare-dns.types.d.ts
@@ -16,4 +16,12 @@ export type CloudflareDnsRecordCreate =
ttl: number;
comment?: string;
tags?: string[];
+ } | {
+ type: "CNAME";
+ name: string;
+ content: string;
+ ttl: number;
+ proxied?: boolean;
+ comment?: string;
+ tags?: string[];
};
diff --git a/src/lib/domains/cloudflare-sending.ts b/src/lib/domains/cloudflare-sending.ts
new file mode 100644
index 0000000..48ab8cf
--- /dev/null
+++ b/src/lib/domains/cloudflare-sending.ts
@@ -0,0 +1,24 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { domains } from "@/db/schema";
+import { deleteSendingSubdomain, listSendingSubdomains } from "@/lib/cloudflare-api";
+import { isManualZone } from "@/lib/domains/provision";
+import { findSendingSubdomain } from "@/lib/domains/sending-status";
+import type { DomainRow } from "@/lib/domains/types";
+
+/** The zone's Cloudflare Email Sending subdomain for this domain, if one exists. */
+export async function findCloudflareSending(env: CloudflareEnv, domain: DomainRow) {
+ if (isManualZone(domain.zoneId)) return null;
+ try { return findSendingSubdomain(domain.hostname, await listSendingSubdomains(env, domain.zoneId)); }
+ catch { return null; }
+}
+
+/** Removes the Cloudflare sending subdomain (and with it the DNS Cloudflare created for it). */
+export async function removeCloudflareSending(env: CloudflareEnv, domain: DomainRow): Promise<void> {
+ const subdomain = await findCloudflareSending(env, domain);
+ if (subdomain) await deleteSendingSubdomain(env, domain.zoneId, subdomain.tag);
+ await getDb(env)
+ .update(domains)
+ .set({ sendingSubdomainTag: null, sendingEnabled: false, sendingRequested: false })
+ .where(eq(domains.id, domain.id));
+}
diff --git a/src/lib/domains/receiving-dns.ts b/src/lib/domains/receiving-dns.ts
new file mode 100644
index 0000000..b2f3399
--- /dev/null
+++ b/src/lib/domains/receiving-dns.ts
@@ -0,0 +1,58 @@
+import { createDnsRecord, deleteDnsRecord, listMxRecords } from "@/lib/cloudflare-dns";
+import { isManualZone } from "@/lib/domains/provision";
+import type { CfDnsRecord } from "@/lib/cloudflare-api.types";
+import type { DomainRow } from "@/lib/domains/types";
+
+/** Thrown when other mail servers' MX records would shadow the one being added. */
+export class MxConflictError extends Error {
+ readonly code = "MX_CONFLICT";
+ constructor(readonly records: { content: string; priority: number }[]) {
+ super("This domain has MX records for another mail service. Replace them to receive mail here.");
+ }
+}
+
+const same = (a: string, b: string) => a.trim().toLowerCase().replace(/\.$/, "") === b.trim().toLowerCase().replace(/\.$/, "");
+
+export async function listDomainMx(env: CloudflareEnv, domain: DomainRow): Promise<CfDnsRecord[]> {
+ if (isManualZone(domain.zoneId)) return [];
+ return listMxRecords(env, domain.zoneId, domain.hostname);
+}
+
+/** Whether an MX record for `content` is in the zone; null when DNS is manual. */
+export async function hasMx(env: CloudflareEnv, domain: DomainRow, content: string): Promise<boolean | null> {
+ if (isManualZone(domain.zoneId)) return null;
+ return (await listDomainMx(env, domain)).some((record) => same(record.content ?? "", content));
+}
+
+/**
+ * Points the domain's MX at `content`. Any other MX record is a conflict (mail
+ * goes to the lowest priority), so without `replace` this throws and nothing changes.
+ * Returns the records it deleted.
+ */
+export async function publishMx(
+ env: CloudflareEnv,
+ domain: DomainRow,
+ content: string,
+ options: { replace: boolean; priority?: number },
+): Promise<CfDnsRecord[]> {
+ if (isManualZone(domain.zoneId)) return [];
+ const existing = await listDomainMx(env, domain);
+ const others = existing.filter((record) => !same(record.content ?? "", content));
+ if (others.length > 0 && !options.replace) {
+ throw new MxConflictError(others.map((record) => ({ content: record.content ?? "", priority: record.priority ?? 0 })));
+ }
+ for (const record of others) if (record.id) await deleteDnsRecord(env, domain.zoneId, record.id);
+ if (!existing.some((record) => same(record.content ?? "", content))) {
+ await createDnsRecord(env, domain.zoneId, { type: "MX", name: domain.hostname, content, priority: options.priority ?? 10, ttl: 3600 });
+ }
+ return others;
+}
+
+export async function removeMx(env: CloudflareEnv, domain: DomainRow, matches: (content: string) => boolean): Promise<void> {
+ if (isManualZone(domain.zoneId)) return;
+ for (const record of await listDomainMx(env, domain)) {
+ if (record.id && matches(record.content ?? "")) await deleteDnsRecord(env, domain.zoneId, record.id);
+ }
+}
+
+export const isInboundSmtpMx = (content: string) => /inbound-smtp\.[a-z0-9-]+\.amazonaws\.com\.?$/i.test(content.trim());
diff --git a/src/lib/domains/receiving.ts b/src/lib/domains/receiving.ts
new file mode 100644
index 0000000..328aba4
--- /dev/null
+++ b/src/lib/domains/receiving.ts
@@ -0,0 +1,79 @@
+import { and, eq, ne, or } from "drizzle-orm";
+import { getDb } from "@/db";
+import { domains, mailboxes } from "@/db/schema";
+import { disableEmailRouting } from "@/lib/cloudflare-api";
+import { deleteDnsRecord } from "@/lib/cloudflare-dns";
+import { deleteEmailRoutingRulesForDomain } from "@/lib/domains/cloudflare-cleanup";
+import { removeMxRecords } from "@/lib/domains/mx-records";
+import { setupDomainDnsRecord } from "@/lib/domains/dns-setup";
+import { isManualZone } from "@/lib/domains/provision";
+import { listDomainMx, MxConflictError } from "@/lib/domains/receiving-dns";
+import { removeResendReceiving, setupResendReceiving, hasResendReceivingConfig } from "@/lib/domains/resend-receiving";
+import { hasSesReceivingConfig, removeSesReceiving, setupSesReceiving } from "@/lib/aws/ses-receiving";
+import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";
+import type { DomainRow } from "@/lib/domains/types";
+
+export type ReceivingProviderId = "none" | "cloudflare" | "resend" | "ses";
+export type ConfigurableReceiving = Exclude<ReceivingProviderId, "none">;
+
+const isCloudflareMx = (content: string) => content.toLowerCase().replace(/\.$/, "").endsWith(".mx.cloudflare.net");
+
+/** Email Routing on the zone, the MX and the Worker routes for this domain's mailboxes. */
+export async function setupCloudflareReceiving(env: CloudflareEnv, domain: DomainRow, options: { replaceMx: boolean }): Promise<void> {
+ if (isManualZone(domain.zoneId)) throw new Error("Cloudflare Email Routing needs a domain on a Cloudflare zone");
+ const foreign = (await listDomainMx(env, domain)).filter((record) => !isCloudflareMx(record.content ?? ""));
+ if (foreign.length > 0 && !options.replaceMx) {
+ throw new MxConflictError(foreign.map((record) => ({ content: record.content ?? "", priority: record.priority ?? 0 })));
+ }
+ if (foreign.length > 0) await removeMxRecords(env, domain.zoneId, domain.hostname, []);
+ await setupDomainDnsRecord(env, domain, "mx");
+
+ // Cleaning up Cloudflare receiving deletes the per-address Worker routes; put them back.
+ const db = getDb(env);
+ const mailboxRows = await db
+ .select({ id: mailboxes.id, domainId: mailboxes.domainId, localPart: mailboxes.localPart, useAllDomains: mailboxes.useAllDomains })
+ .from(mailboxes)
+ .innerJoin(domains, eq(mailboxes.domainId, domains.id))
+ .where(and(eq(domains.userId, domain.userId), or(eq(mailboxes.domainId, domain.id), eq(mailboxes.useAllDomains, true))));
+ await Promise.allSettled(mailboxRows.map((mailbox) => ensureMailboxDomainRouting(env, db, { ...mailbox, useAllDomains: true })));
+}
+
+export async function removeCloudflareReceiving(env: CloudflareEnv, domain: DomainRow): Promise<void> {
+ if (isManualZone(domain.zoneId)) return;
+ await deleteEmailRoutingRulesForDomain(env, domain.zoneId, domain.hostname);
+ await removeCloudflareMx(env, domain);
+ const db = getDb(env);
+ const [otherDomainOnZone] = await db.select({ id: domains.id }).from(domains).where(and(eq(domains.zoneId, domain.zoneId), ne(domains.id, domain.id))).limit(1);
+ if (domain.routingEnabled && !otherDomainOnZone) await disableEmailRouting(env, domain.zoneId);
+ await db.update(domains).set({ routingEnabled: false }).where(eq(domains.id, domain.id));
+}
+
+async function removeCloudflareMx(env: CloudflareEnv, domain: DomainRow): Promise<void> {
+ for (const record of await listDomainMx(env, domain)) {
+ if (record.id && isCloudflareMx(record.content ?? "")) await deleteDnsRecord(env, domain.zoneId, record.id);
+ }
+}
+
+export async function setupReceiving(
+ env: CloudflareEnv,
+ domain: DomainRow,
+ provider: ConfigurableReceiving,
+ origin: string,
+ options: { replaceMx: boolean },
+): Promise<void> {
+ if (provider === "cloudflare") return setupCloudflareReceiving(env, domain, options);
+ if (provider === "resend") return setupResendReceiving(env, domain, origin, options);
+ return setupSesReceiving(env, domain, origin, options);
+}
+
+export async function removeReceiving(env: CloudflareEnv, domain: DomainRow, provider: ConfigurableReceiving): Promise<void> {
+ if (provider === "cloudflare") return removeCloudflareReceiving(env, domain);
+ if (provider === "resend") return removeResendReceiving(env, domain);
+ return removeSesReceiving(env, domain);
+}
+
+/** Which providers have leftover receiving configuration (null = could not tell). */
+export async function receivingPresence(env: CloudflareEnv, domain: DomainRow): Promise<Record<ConfigurableReceiving, boolean | null>> {
+ const [resend, ses] = await Promise.all([hasResendReceivingConfig(env, domain), hasSesReceivingConfig(env, domain)]);
+ return { cloudflare: domain.routingEnabled, resend, ses };
+}
diff --git a/src/lib/domains/resend-domain-types.d.ts b/src/lib/domains/resend-domain-types.d.ts
new file mode 100644
index 0000000..785161f
--- /dev/null
+++ b/src/lib/domains/resend-domain-types.d.ts
@@ -0,0 +1,17 @@
+export type ResendDomainView = {
+ registered: boolean;
+ /** Resend's status (verified, pending, failed, ...) or "not_registered". */
+ status: string;
+ records: {
+ record: string;
+ type: "MX" | "TXT" | "CNAME";
+ name: string;
+ value: string;
+ priority: number | null;
+ status: string;
+ }[];
+ /** Mailflare can write the records to the Cloudflare zone itself. */
+ dnsManaged: boolean;
+ /** Records Resend asked for that are not in the Cloudflare zone; null when DNS is manual or unchecked. */
+ missingDns: number | null;
+};
diff --git a/src/lib/domains/resend-domain.ts b/src/lib/domains/resend-domain.ts
new file mode 100644
index 0000000..e4159c2
--- /dev/null
+++ b/src/lib/domains/resend-domain.ts
@@ -0,0 +1,150 @@
+import { createDnsRecord, deleteDnsRecord, listDnsRecords } from "@/lib/cloudflare-dns";
+import { isManualZone } from "@/lib/domains/provision";
+import { getResendKeyStatus, getResendApiKey } from "@/lib/email/outbound-provider";
+import { createResendDomain, deleteResendDomain, findResendDomain, getResendDomain, updateResendCapabilities, verifyResendDomain } from "@/lib/email/resend-api";
+import { isInboundSmtpMx } from "@/lib/domains/receiving-dns";
+import type { ResendDomain, ResendDomainRecord } from "@/lib/email/resend-api-types";
+import type { DomainRow } from "@/lib/domains/types";
+import type { ResendDomainView } from "@/lib/domains/resend-domain-types";
+
+/** Records for sending only; the apex MX for receiving belongs to the receiving setup. */
+const sendingRecords = (records: ResendDomainRecord[] | undefined) => (records ?? []).filter((record) => !(record.type === "MX" && isInboundSmtpMx(record.value)));
+
+function toView(domain: ResendDomain | null, zoneManaged: boolean, missingDns: number | null = null): ResendDomainView {
+ return {
+ missingDns,
+ registered: !!domain,
+ status: domain?.status ?? "not_registered",
+ records: sendingRecords(domain?.records).map((record) => ({
+ record: record.record,
+ type: record.type,
+ name: record.name,
+ value: record.value,
+ priority: record.priority ?? null,
+ status: record.status ?? "unknown",
+ })),
+ dnsManaged: zoneManaged,
+ };
+}
+
+async function requireResendKey(env: CloudflareEnv, _domain?: DomainRow): Promise<string> {
+ return getResendApiKey(env);
+}
+
+export async function getResendDomainView(env: CloudflareEnv, domain: DomainRow): Promise<ResendDomainView> {
+ const apiKey = await requireResendKey(env, domain);
+ return viewFor(env, domain, await findResendDomain(apiKey, domain.hostname));
+}
+
+async function viewFor(env: CloudflareEnv, domain: DomainRow, resend: ResendDomain | null): Promise<ResendDomainView> {
+ return toView(resend, !isManualZone(domain.zoneId), resend ? await countMissingRecords(env, domain, sendingRecords(resend.records)) : null);
+}
+
+const stripQuotes = (value: string) => value.replace(/^"|"$/g, "").trim().toLowerCase().replace(/\.$/, "");
+
+/**
+ * The domain's status in Resend ("verified", "pending", ... or "not_registered");
+ * null when that cannot be checked (no key, or a send-only key).
+ */
+export async function getResendDomainStatus(env: CloudflareEnv, domain: DomainRow): Promise<string | null> {
+ const { apiKey } = await getResendKeyStatus(env);
+ if (!apiKey) return null;
+ try {
+ const resend = await findResendDomain(apiKey, domain.hostname);
+ // A domain added only for receiving has no sending setup.
+ return !resend || resend.capabilities?.sending === "disabled" ? "not_registered" : resend.status;
+ }
+ catch { return null; }
+}
+
+async function deleteRecordsFromZone(env: CloudflareEnv, domain: DomainRow, records: ResendDomainRecord[]): Promise<void> {
+ if (isManualZone(domain.zoneId)) return;
+ for (const record of records) {
+ const existing = await listDnsRecords(env, domain.zoneId, { type: record.type, name: absoluteName(record, domain.hostname) });
+ for (const item of existing) {
+ if (item.id && stripQuotes(item.content ?? "") === stripQuotes(record.value)) await deleteDnsRecord(env, domain.zoneId, item.id);
+ }
+ }
+}
+
+/**
+ * Removes Resend's sending setup. The Resend domain also carries receiving, so
+ * when the domain still receives through Resend only sending is switched off.
+ */
+export async function removeResendConfig(env: CloudflareEnv, domain: DomainRow): Promise<void> {
+ const apiKey = await getResendApiKey(env);
+ const resend = await findResendDomain(apiKey, domain.hostname);
+ if (!resend) return;
+ if (domain.receivingProvider === "resend") {
+ await deleteRecordsFromZone(env, domain, sendingRecords(resend.records));
+ await updateResendCapabilities(apiKey, resend.id, { sending: false });
+ return;
+ }
+ await deleteRecordsFromZone(env, domain, resend.records ?? []);
+ await deleteResendDomain(apiKey, resend.id);
+}
+
+/** Resend lists names relative to the domain; Cloudflare needs them absolute. */
+function absoluteName(record: ResendDomainRecord, hostname: string): string {
+ const name = record.name.trim();
+ if (!name || name === "@") return hostname;
+ return name.endsWith(`.${hostname}`) || name === hostname ? name : `${name}.${hostname}`;
+}
+
+async function recordExists(env: CloudflareEnv, domain: DomainRow, record: ResendDomainRecord): Promise<boolean> {
+ const existing = await listDnsRecords(env, domain.zoneId, { type: record.type, name: absoluteName(record, domain.hostname) });
+ return existing.some((item) => stripQuotes(item.content ?? "") === stripQuotes(record.value));
+}
+
+/** How many of Resend's records are absent from the zone; null when DNS is not ours to read. */
+async function countMissingRecords(env: CloudflareEnv, domain: DomainRow, records: ResendDomainRecord[]): Promise<number | null> {
+ if (isManualZone(domain.zoneId)) return null;
+ try {
+ const present = await Promise.all(records.map((record) => recordExists(env, domain, record)));
+ return present.filter((exists) => !exists).length;
+ } catch { return null; }
+}
+
+async function publishRecords(env: CloudflareEnv, domain: DomainRow, records: ResendDomainRecord[]): Promise<void> {
+ for (const record of records) {
+ if (await recordExists(env, domain, record)) continue;
+ const name = absoluteName(record, domain.hostname);
+ const ttl = 3600;
+ if (record.type === "MX") {
+ await createDnsRecord(env, domain.zoneId, { type: "MX", name, content: record.value, priority: record.priority ?? 10, ttl });
+ } else if (record.type === "CNAME") {
+ await createDnsRecord(env, domain.zoneId, { type: "CNAME", name, content: record.value, ttl, proxied: false });
+ } else {
+ await createDnsRecord(env, domain.zoneId, { type: "TXT", name, content: record.value, ttl });
+ }
+ }
+}
+
+/**
+ * Registers the domain with Resend if needed, writes its DNS records to the
+ * Cloudflare zone (when Mailflare manages it) and asks Resend to verify.
+ */
+export async function setupResendDomain(env: CloudflareEnv, domain: DomainRow): Promise<ResendDomainView> {
+ const apiKey = await requireResendKey(env, domain);
+ const managed = !isManualZone(domain.zoneId);
+ let resend = await findResendDomain(apiKey, domain.hostname);
+ if (!resend) {
+ const created = await createResendDomain(apiKey, domain.hostname, { sending: true, receiving: domain.receivingProvider === "resend" });
+ resend = await getResendDomain(apiKey, created.id);
+ } else if (resend.capabilities?.sending === "disabled") {
+ // The domain was added for receiving only; sending needs its own DKIM and SPF.
+ await updateResendCapabilities(apiKey, resend.id, { sending: true });
+ resend = await getResendDomain(apiKey, resend.id);
+ }
+ if (managed) await publishRecords(env, domain, sendingRecords(resend.records));
+ await verifyResendDomain(apiKey, resend.id);
+ return viewFor(env, domain, await getResendDomain(apiKey, resend.id));
+}
+
+export async function verifyResendDomainView(env: CloudflareEnv, domain: DomainRow): Promise<ResendDomainView> {
+ const apiKey = await requireResendKey(env, domain);
+ const resend = await findResendDomain(apiKey, domain.hostname);
+ if (!resend) return viewFor(env, domain, null);
+ await verifyResendDomain(apiKey, resend.id);
+ return viewFor(env, domain, await getResendDomain(apiKey, resend.id));
+}
diff --git a/src/lib/domains/resend-receiving-types.d.ts b/src/lib/domains/resend-receiving-types.d.ts
new file mode 100644
index 0000000..6afd751
--- /dev/null
+++ b/src/lib/domains/resend-receiving-types.d.ts
@@ -0,0 +1,10 @@
+import type { ReceivingStep } from "@/lib/aws/ses-receiving-types";
+
+export type ResendReceivingView = {
+ steps: ReceivingStep[];
+ ready: boolean;
+ mx: string | null;
+ dnsManaged: boolean;
+ /** The key cannot manage domains or webhooks, so setup has to happen in the Resend dashboard. */
+ restrictedKey: boolean;
+};
diff --git a/src/lib/domains/resend-receiving.ts b/src/lib/domains/resend-receiving.ts
new file mode 100644
index 0000000..cc7a9db
--- /dev/null
+++ b/src/lib/domains/resend-receiving.ts
@@ -0,0 +1,116 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { appSettings } from "@/db/schema";
+import { isManualZone } from "@/lib/domains/provision";
+import { hasMx, isInboundSmtpMx, publishMx, removeMx } from "@/lib/domains/receiving-dns";
+import { getResendApiKey, getResendKeyStatus } from "@/lib/email/outbound-provider";
+import {
+ createResendDomain, createResendWebhook, deleteResendDomain, deleteResendWebhook, findResendDomain, getResendDomain,
+ listResendWebhooks, ResendRestrictedKeyError, updateResendCapabilities, verifyResendDomain,
+} from "@/lib/email/resend-api";
+import type { ReceivingStep } from "@/lib/aws/ses-receiving-types";
+import type { DomainRow } from "@/lib/domains/types";
+import type { ResendReceivingView } from "@/lib/domains/resend-receiving-types";
+
+export const resendWebhookUrl = (origin: string) => `${origin.replace(/\/$/, "")}/api/inbound/resend`;
+
+export async function getResendWebhookSecret(env: CloudflareEnv): Promise<string | null> {
+ const [row] = await getDb(env).select({ secret: appSettings.resendWebhookSecret }).from(appSettings).where(eq(appSettings.id, "default")).limit(1);
+ return row?.secret ?? null;
+}
+
+async function storeWebhook(env: CloudflareEnv, id: string | null, secret: string | null): Promise<void> {
+ const values = { resendWebhookId: id, resendWebhookSecret: secret, updatedAt: new Date() };
+ await getDb(env).insert(appSettings).values({ id: "default", ...values }).onConflictDoUpdate({ target: appSettings.id, set: values });
+}
+
+function inboundMx(records: { type: string; value: string; priority?: number }[] | undefined) {
+ return (records ?? []).find((record) => record.type === "MX" && isInboundSmtpMx(record.value)) ?? null;
+}
+
+function isPublicHttps(origin: string): boolean {
+ try {
+ const url = new URL(origin);
+ return url.protocol === "https:" && !/^(localhost|127\.|\[::1\]|.*\.localhost$|.*\.test$)/.test(url.hostname);
+ } catch { return false; }
+}
+
+/** One webhook serves every domain; creating it returns the signing secret exactly once, so keep it. */
+async function ensureWebhook(env: CloudflareEnv, apiKey: string, origin: string): Promise<void> {
+ const endpoint = resendWebhookUrl(origin);
+ const existing = (await listResendWebhooks(apiKey)).find((webhook) => webhook.endpoint === endpoint);
+ if (existing && await getResendWebhookSecret(env)) return;
+ // Resend only shows the secret at creation, so a hook we have no secret for is useless: replace it.
+ if (existing) await deleteResendWebhook(apiKey, existing.id);
+ const created = await createResendWebhook(apiKey, endpoint);
+ await storeWebhook(env, created.id, created.signing_secret);
+}
+
+/**
+ * Receiving through Resend: enable the receiving capability on the domain, point
+ * its MX at Resend, register the `email.received` webhook, and ask Resend to verify.
+ */
+export async function setupResendReceiving(
+ env: CloudflareEnv,
+ domain: DomainRow,
+ origin: string,
+ options: { replaceMx: boolean },
+): Promise<void> {
+ if (!isPublicHttps(origin)) {
+ throw new Error("Resend delivers mail by calling this app over public HTTPS. Set APP_URL to your public address (localhost will not work).");
+ }
+ const apiKey = await getResendApiKey(env);
+ let resend = await findResendDomain(apiKey, domain.hostname);
+ if (!resend) {
+ const created = await createResendDomain(apiKey, domain.hostname, { sending: domain.sendingProvider === "resend", receiving: true });
+ resend = await getResendDomain(apiKey, created.id);
+ } else if (resend.capabilities?.receiving !== "enabled") {
+ await updateResendCapabilities(apiKey, resend.id, { receiving: true });
+ resend = await getResendDomain(apiKey, resend.id);
+ }
+ const mx = inboundMx(resend.records);
+ if (!mx) throw new Error("Resend did not return a receiving MX record for this domain.");
+ await publishMx(env, domain, mx.value, { replace: options.replaceMx, priority: mx.priority });
+ await ensureWebhook(env, apiKey, origin);
+ await verifyResendDomain(apiKey, resend.id).catch(() => undefined);
+}
+
+export async function getResendReceivingView(env: CloudflareEnv, domain: DomainRow, origin: string): Promise<ResendReceivingView> {
+ const base = { dnsManaged: !isManualZone(domain.zoneId) };
+ const key = await getResendKeyStatus(env);
+ const steps: ReceivingStep[] = [{ key: "key", label: "Resend API key", ok: key.configured, detail: key.configured ? undefined : "Add a key under Sending or here" }];
+ if (!key.configured || !key.apiKey) return { ...base, steps, ready: false, mx: null, restrictedKey: false };
+ try {
+ const resend = await findResendDomain(key.apiKey, domain.hostname);
+ const enabled = resend?.capabilities?.receiving === "enabled";
+ steps.push({ key: "domain", label: "Receiving enabled for this domain", ok: enabled, detail: !resend ? "Domain is not in Resend yet" : undefined });
+ const mx = inboundMx(resend?.records);
+ const mxOk = mx ? await hasMx(env, domain, mx.value) : false;
+ steps.push({ key: "mx", label: "MX record points to Resend", ok: mxOk === true, detail: mx?.value ?? undefined });
+ steps.push({ key: "verified", label: "Domain verified", ok: resend?.status === "verified", detail: resend ? resend.status.replace(/_/g, " ") : undefined });
+ const hooks = await listResendWebhooks(key.apiKey);
+ const hookOk = hooks.some((webhook) => webhook.endpoint === resendWebhookUrl(origin)) && !!(await getResendWebhookSecret(env));
+ steps.push({ key: "webhook", label: "Webhook delivering mail to Mailflare", ok: hookOk });
+ return { ...base, steps, ready: steps.every((step) => step.ok), mx: mx?.value ?? null, restrictedKey: false };
+ } catch (error) {
+ if (error instanceof ResendRestrictedKeyError) return { ...base, steps, ready: false, mx: null, restrictedKey: true };
+ throw error;
+ }
+}
+
+export async function hasResendReceivingConfig(env: CloudflareEnv, domain: DomainRow): Promise<boolean | null> {
+ const { apiKey } = await getResendKeyStatus(env);
+ if (!apiKey) return null;
+ try { return (await findResendDomain(apiKey, domain.hostname))?.capabilities?.receiving === "enabled"; }
+ catch { return null; }
+}
+
+/** Switches receiving off for the domain and removes the MX. The shared webhook stays for other domains. */
+export async function removeResendReceiving(env: CloudflareEnv, domain: DomainRow): Promise<void> {
+ const apiKey = await getResendApiKey(env);
+ const resend = await findResendDomain(apiKey, domain.hostname);
+ await removeMx(env, domain, isInboundSmtpMx);
+ if (!resend) return;
+ if (domain.sendingProvider === "resend") await updateResendCapabilities(apiKey, resend.id, { receiving: false });
+ else await deleteResendDomain(apiKey, resend.id);
+}
diff --git a/src/lib/domains/service.ts b/src/lib/domains/service.ts
index 14c1325..9c87ea7 100644
--- a/src/lib/domains/service.ts
+++ b/src/lib/domains/service.ts
@@ -40,7 +40,7 @@ export async function addDomainForUser(
env: CloudflareEnv,
userId: string,
hostname: string,
- options?: { enableRouting?: boolean; enableSending?: boolean; replaceMxRecords?: boolean },
+ options?: { enableRouting?: boolean; enableSending?: boolean; replaceMxRecords?: boolean; receivingProvider?: "none" | "cloudflare" | "resend" | "ses" },
): Promise<{
domain: typeof domains.$inferSelect;
dns: DomainDnsView;
@@ -62,7 +62,14 @@ export async function addDomainForUser(
throw new Error("Cloudflare zone is already registered to another account");
}
}
- const provisioned = await provisionDomainOnCloudflare(env, hostname, options);
+ // Email Routing is Cloudflare's way of receiving; another provider brings its own MX,
+ // which its setup in the domain page creates once credentials exist.
+ const receivingProvider = options?.receivingProvider ?? "cloudflare";
+ const provisioned = await provisionDomainOnCloudflare(env, hostname, {
+ ...options,
+ enableRouting: receivingProvider === "cloudflare" ? (options?.enableRouting ?? true) : false,
+ replaceMxRecords: receivingProvider === "cloudflare" ? options?.replaceMxRecords : false,
+ });
let insertedDomainId: string | null = null;
let domain: typeof domains.$inferSelect;
@@ -78,10 +85,12 @@ export async function addDomainForUser(
userId,
hostname: provisioned.hostname,
zoneId: provisioned.zone.id,
- status: provisioned.routingEnabled || provisioned.sendingEnabled ? ("active" as const) : ("pending" as const),
+ status: provisioned.routingEnabled || provisioned.sendingEnabled || receivingProvider !== "cloudflare" ? ("active" as const) : ("pending" as const),
+ receivingProvider,
routingStatus: provisioned.routingStatus ?? null,
sendingSubdomainTag: provisioned.sendingSubdomainTag,
sendingRequested: provisioned.sendingRequested,
+ ...(existing && existing.sendingProvider !== "none" ? {} : { sendingProvider: provisioned.sendingRequested ? ("cloudflare" as const) : ("none" as const) }),
sendingEnabled: provisioned.sendingEnabled,
routingEnabled: provisioned.routingEnabled,
};
diff --git a/src/lib/email/outbound-provider-types.d.ts b/src/lib/email/outbound-provider-types.d.ts
new file mode 100644
index 0000000..2866aa1
--- /dev/null
+++ b/src/lib/email/outbound-provider-types.d.ts
@@ -0,0 +1,34 @@
+import type { AwsConfig } from "@/lib/aws/aws-types";
+
+export type SendingProvider = "none" | "cloudflare" | "resend" | "ses";
+
+export type OutboundProviderConfig =
+ | { provider: "cloudflare" }
+ | { provider: "resend"; apiKey: string }
+ | { provider: "ses"; config: AwsConfig };
+
+export type OutboundProviderAttachment = {
+ filename: string;
+ type: string;
+ content: ArrayBuffer;
+ disposition: "attachment" | "inline";
+ contentId?: string | null;
+};
+
+export type OutboundProviderMessage = {
+ from: string;
+ to: string[];
+ cc?: string[];
+ bcc?: string[];
+ subject: string;
+ html?: string;
+ text?: string;
+ headers?: Record<string, string>;
+ attachments?: OutboundProviderAttachment[];
+};
+
+export type ResendKeyStatus = {
+ configured: boolean;
+ /** Where the key in use comes from; the key itself never leaves the server. */
+ source: "settings" | "environment" | null;
+};
diff --git a/src/lib/email/outbound-provider.ts b/src/lib/email/outbound-provider.ts
new file mode 100644
index 0000000..1f8b90b
--- /dev/null
+++ b/src/lib/email/outbound-provider.ts
@@ -0,0 +1,128 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { appSettings, domains } from "@/db/schema";
+import { requireAwsConfig } from "@/lib/aws/config";
+import { sendSesEmail } from "@/lib/aws/ses";
+import { getEmailAddress } from "@/lib/email/address";
+import type { OutboundProviderConfig, OutboundProviderMessage, ResendKeyStatus } from "@/lib/email/outbound-provider-types";
+
+const RESEND_ENDPOINT = "https://api.resend.com/emails";
+
+/**
+ * Each domain picks its own sender: Cloudflare Email Sending, Resend, or none
+ * (receive-only). Receiving and storage always stay on Cloudflare. The Resend key
+ * is shared by every domain; it comes from the admin setting, falling back to a
+ * RESEND_API_KEY secret so it can be provisioned outside the database.
+ */
+export async function getResendKeyStatus(env: CloudflareEnv): Promise<ResendKeyStatus & { apiKey: string | null }> {
+ const [settings] = await getDb(env)
+ .select({ resendApiKey: appSettings.resendApiKey })
+ .from(appSettings)
+ .where(eq(appSettings.id, "default"))
+ .limit(1);
+ const saved = settings?.resendApiKey?.trim();
+ const fromEnv = (env as { RESEND_API_KEY?: string }).RESEND_API_KEY?.trim();
+ return {
+ configured: !!(saved || fromEnv),
+ source: saved ? "settings" : fromEnv ? "environment" : null,
+ apiKey: saved || fromEnv || null,
+ };
+}
+
+export async function getResendApiKey(env: CloudflareEnv): Promise<string> {
+ const { apiKey } = await getResendKeyStatus(env);
+ if (!apiKey) throw new Error("Resend is selected but no API key is configured");
+ return apiKey;
+}
+
+/** The provider for the domain a message is sent from. */
+export async function getOutboundProviderConfig(env: CloudflareEnv, fromAddress: string): Promise<OutboundProviderConfig> {
+ const hostname = getEmailAddress(fromAddress).split("@")[1]?.toLowerCase();
+ const [domain] = hostname
+ ? await getDb(env).select({ provider: domains.sendingProvider }).from(domains).where(eq(domains.hostname, hostname)).limit(1)
+ : [];
+ if (!domain || domain.provider === "none") {
+ throw new Error(`Sending is not set up for ${hostname ?? "this domain"}. Choose a sending provider on the Domains page.`);
+ }
+ if (domain.provider === "resend") return { provider: "resend", apiKey: await getResendApiKey(env) };
+ if (domain.provider === "ses") return { provider: "ses", config: await requireAwsConfig(env) };
+ return { provider: "cloudflare" };
+}
+
+function toBase64(buffer: ArrayBuffer): string {
+ const bytes = new Uint8Array(buffer);
+ let binary = "";
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ }
+ return btoa(binary);
+}
+
+/** Resend does not return the RFC 5322 Message-ID, so we mint one for replies to thread against. */
+function mintMessageId(from: string): string {
+ const domain = getEmailAddress(from).split("@")[1] || "mailflare.local";
+ return `<${crypto.randomUUID()}@${domain}>`;
+}
+
+async function sendWithResend(
+ apiKey: string,
+ message: OutboundProviderMessage,
+ idempotencyKey?: string,
+): Promise<{ messageId: string }> {
+ const messageId = message.headers?.["Message-ID"] ?? mintMessageId(message.from);
+ const response = await fetch(RESEND_ENDPOINT, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
+ },
+ body: JSON.stringify({
+ from: message.from,
+ to: message.to,
+ ...(message.cc?.length ? { cc: message.cc } : {}),
+ ...(message.bcc?.length ? { bcc: message.bcc } : {}),
+ subject: message.subject,
+ html: message.html,
+ text: message.text,
+ headers: { ...message.headers, "Message-ID": messageId },
+ attachments: message.attachments?.map((attachment) => ({
+ filename: attachment.filename,
+ content: toBase64(attachment.content),
+ content_type: attachment.type,
+ ...(attachment.disposition === "inline" && attachment.contentId ? { content_id: attachment.contentId } : {}),
+ })),
+ }),
+ });
+ if (!response.ok) {
+ const body = (await response.json().catch(() => null)) as { message?: string } | null;
+ throw new Error(`Resend: ${body?.message ?? `request failed (${response.status})`}`);
+ }
+ return { messageId };
+}
+
+export async function sendThroughProvider(
+ env: CloudflareEnv,
+ config: OutboundProviderConfig,
+ message: OutboundProviderMessage,
+ idempotencyKey?: string,
+): Promise<{ messageId: string }> {
+ if (config.provider === "resend") return sendWithResend(config.apiKey, message, idempotencyKey);
+ if (config.provider === "ses") return sendSesEmail(config.config, message);
+ const response = await env.EMAIL.send({
+ from: message.from,
+ to: message.to,
+ ...(message.cc?.length ? { cc: message.cc } : {}),
+ ...(message.bcc?.length ? { bcc: message.bcc } : {}),
+ subject: message.subject,
+ headers: message.headers && Object.keys(message.headers).length ? message.headers : undefined,
+ html: message.html,
+ text: message.text,
+ attachments: message.attachments?.map((attachment) =>
+ attachment.disposition === "inline" && attachment.contentId
+ ? { filename: attachment.filename, type: attachment.type, content: attachment.content, disposition: "inline" as const, contentId: attachment.contentId }
+ : { filename: attachment.filename, type: attachment.type, content: attachment.content, disposition: "attachment" as const },
+ ),
+ });
+ return { messageId: response.messageId };
+}
diff --git a/src/lib/email/provider-intake.ts b/src/lib/email/provider-intake.ts
new file mode 100644
index 0000000..b2073ca
--- /dev/null
+++ b/src/lib/email/provider-intake.ts
@@ -0,0 +1,39 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { domains } from "@/db/schema";
+import { normalizeEmailAddress } from "@/lib/email/address";
+import { inboundAttachmentLimitReasonFromRaw } from "@/lib/email/inbound-attachments";
+import { intakeIncomingMail } from "@/lib/email/intake";
+
+export const MAX_PROVIDER_MESSAGE_BYTES = 25 * 1024 * 1024;
+
+/**
+ * Hands a message a mail provider delivered (SES, Resend) to the normal intake,
+ * once per recipient on a domain Mailflare manages. Routing rules, account
+ * forwarding and storage then behave exactly as for Cloudflare mail. A provider
+ * cannot refuse the message after it has been accepted, so a reject or a size
+ * limit simply drops it. Throws on infrastructure failure so the provider retries.
+ */
+export async function intakeProviderMail(
+ env: CloudflareEnv,
+ input: { from: string; recipients: string[]; raw: ArrayBuffer; headers?: Record<string, string> },
+): Promise<{ delivered: number; dropped: string | null }> {
+ if (input.raw.byteLength > MAX_PROVIDER_MESSAGE_BYTES) return { delivered: 0, dropped: "Message exceeds the 25 MiB receiving limit" };
+ const limit = await inboundAttachmentLimitReasonFromRaw(input.raw);
+ if (limit) return { delivered: 0, dropped: limit };
+
+ const db = getDb(env);
+ let delivered = 0;
+ for (const recipient of [...new Set(input.recipients.map(normalizeEmailAddress).filter(Boolean))]) {
+ const hostname = recipient.slice(recipient.lastIndexOf("@") + 1);
+ const [domain] = await db.select({ id: domains.id }).from(domains).where(eq(domains.hostname, hostname)).limit(1);
+ if (!domain) continue;
+ const result = await intakeIncomingMail(
+ env,
+ { from: normalizeEmailAddress(input.from), to: recipient, raw: input.raw, headers: input.headers ?? {} },
+ { forward: async () => false },
+ );
+ if (result.action === "store") delivered += 1;
+ }
+ return { delivered, dropped: null };
+}
diff --git a/src/lib/email/resend-api-types.d.ts b/src/lib/email/resend-api-types.d.ts
new file mode 100644
index 0000000..63c5f18
--- /dev/null
+++ b/src/lib/email/resend-api-types.d.ts
@@ -0,0 +1,30 @@
+export type ResendDomainRecord = {
+ record: string;
+ name: string;
+ type: "MX" | "TXT" | "CNAME";
+ value: string;
+ ttl?: string | number;
+ status?: string;
+ priority?: number;
+};
+
+export type ResendDomain = {
+ id: string;
+ name: string;
+ status: string;
+ capabilities?: { sending?: string; receiving?: string };
+ records?: ResendDomainRecord[];
+};
+
+export type ResendWebhook = { id: string; endpoint: string; events?: string[] };
+
+export type ResendReceivedEmail = {
+ id: string;
+ from: string;
+ to: string[];
+ cc?: string[];
+ bcc?: string[];
+ subject?: string;
+ message_id?: string;
+ raw?: { download_url: string; expires_at?: string };
+};
diff --git a/src/lib/email/resend-api.ts b/src/lib/email/resend-api.ts
new file mode 100644
index 0000000..f7a51a5
--- /dev/null
+++ b/src/lib/email/resend-api.ts
@@ -0,0 +1,90 @@
+import type { ResendDomain, ResendReceivedEmail, ResendWebhook } from "@/lib/email/resend-api-types";
+
+const RESEND_API = "https://api.resend.com";
+
+export class ResendRestrictedKeyError extends Error {
+ constructor() {
+ super("This Resend key can only send mail, so Mailflare cannot add or check domains. Add the domain in the Resend dashboard, or use a full-access key.");
+ }
+}
+
+async function resendRequest<T>(apiKey: string, path: string, init?: RequestInit): Promise<T> {
+ const response = await fetch(`${RESEND_API}${path}`, {
+ ...init,
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", ...init?.headers },
+ });
+ const body = (await response.json().catch(() => null)) as { message?: string; name?: string } | null;
+ if (!response.ok) {
+ // A send-only key cannot manage domains; say so instead of a bare 401.
+ if (body?.name === "restricted_api_key") {
+ throw new ResendRestrictedKeyError();
+ }
+ throw new Error(`Resend: ${body?.message ?? `request failed (${response.status})`}`);
+ }
+ return body as T;
+}
+
+export async function findResendDomain(apiKey: string, hostname: string): Promise<ResendDomain | null> {
+ const list = await resendRequest<{ data: ResendDomain[] }>(apiKey, "/domains");
+ const match = list.data.find((domain) => domain.name.toLowerCase() === hostname.toLowerCase());
+ return match ? getResendDomain(apiKey, match.id) : null;
+}
+
+export function getResendDomain(apiKey: string, id: string): Promise<ResendDomain> {
+ return resendRequest<ResendDomain>(apiKey, `/domains/${encodeURIComponent(id)}`);
+}
+
+export type ResendCapabilities = { sending: boolean; receiving: boolean };
+
+const toCapabilities = (capabilities: ResendCapabilities) => ({
+ sending: capabilities.sending ? "enabled" : "disabled",
+ receiving: capabilities.receiving ? "enabled" : "disabled",
+});
+
+export function createResendDomain(apiKey: string, hostname: string, capabilities: ResendCapabilities = { sending: true, receiving: false }): Promise<ResendDomain> {
+ return resendRequest<ResendDomain>(apiKey, "/domains", { method: "POST", body: JSON.stringify({ name: hostname, capabilities: toCapabilities(capabilities) }) });
+}
+
+/** Turns a capability on without touching the other (omitted fields keep their value). */
+export async function updateResendCapabilities(apiKey: string, id: string, capabilities: Partial<ResendCapabilities>): Promise<void> {
+ const body: Record<string, string> = {};
+ if (capabilities.sending !== undefined) body.sending = capabilities.sending ? "enabled" : "disabled";
+ if (capabilities.receiving !== undefined) body.receiving = capabilities.receiving ? "enabled" : "disabled";
+ await resendRequest<unknown>(apiKey, `/domains/${encodeURIComponent(id)}`, { method: "PATCH", body: JSON.stringify({ capabilities: body }) });
+}
+
+export async function listResendWebhooks(apiKey: string): Promise<ResendWebhook[]> {
+ return (await resendRequest<{ data: ResendWebhook[] }>(apiKey, "/webhooks")).data;
+}
+
+export function createResendWebhook(apiKey: string, endpoint: string): Promise<{ id: string; signing_secret: string }> {
+ return resendRequest(apiKey, "/webhooks", { method: "POST", body: JSON.stringify({ endpoint, events: ["email.received"] }) });
+}
+
+export async function deleteResendWebhook(apiKey: string, id: string): Promise<void> {
+ await resendRequest<unknown>(apiKey, `/webhooks/${encodeURIComponent(id)}`, { method: "DELETE" });
+}
+
+export function getReceivedEmail(apiKey: string, id: string): Promise<ResendReceivedEmail> {
+ return resendRequest<ResendReceivedEmail>(apiKey, `/emails/receiving/${encodeURIComponent(id)}`);
+}
+
+export async function verifyResendDomain(apiKey: string, id: string): Promise<void> {
+ await resendRequest<unknown>(apiKey, `/domains/${encodeURIComponent(id)}/verify`, { method: "POST" });
+}
+
+/**
+ * A key is valid if Resend accepts it at all. Send-only keys are rejected by the
+ * domains endpoint with `restricted_api_key`, which still means the key works.
+ */
+export async function checkResendKey(apiKey: string): Promise<{ valid: boolean; canManageDomains: boolean }> {
+ const response = await fetch(`${RESEND_API}/domains`, { headers: { Authorization: `Bearer ${apiKey}` } });
+ if (response.ok) return { valid: true, canManageDomains: true };
+ const body = (await response.json().catch(() => null)) as { name?: string } | null;
+ if (response.status === 401 && body?.name === "restricted_api_key") return { valid: true, canManageDomains: false };
+ return { valid: false, canManageDomains: false };
+}
+
+export async function deleteResendDomain(apiKey: string, id: string): Promise<void> {
+ await resendRequest<unknown>(apiKey, `/domains/${encodeURIComponent(id)}`, { method: "DELETE" });
+}
diff --git a/src/lib/email/send.ts b/src/lib/email/send.ts
index 924b73a..066334c 100644
--- a/src/lib/email/send.ts
+++ b/src/lib/email/send.ts
@@ -12,6 +12,7 @@ import { createAuditLog } from "@/lib/mailboxes/audit";
import { loadMessageAttachmentContents, storeMessageAttachments, validateAttachments } from "@/lib/email/attachments";
import type { AttachmentContent } from "@/lib/email/attachment-types";
import { getOutboundAttachmentMaxMb } from "@/lib/email/attachment-policy";
+import { getOutboundProviderConfig, sendThroughProvider } from "@/lib/email/outbound-provider";
import { prepareCloudflareAttachments } from "@/lib/email/cloud-attachment-utils";
export type SendEmailInput = {
@@ -183,42 +184,43 @@ async function deliverEmail(env: CloudflareEnv, delivery: PreparedDelivery): Pro
const db = getDb(env);
const toAddr = joinEmailAddressList(to);
try {
- const prepared = await prepareCloudflareAttachments(env, attachments, {
- subject: input.subject,
- html: input.html,
- text: input.text,
- headers,
- publicOrigin: input.publicOrigin,
- });
+ const provider = await getOutboundProviderConfig(env, from);
+ // Cloudflare's 5 MiB cap forces big files into download links; Resend takes
+ // the attachments directly (the admin's outgoing limit still applies).
+ const prepared = provider.provider === "cloudflare"
+ ? await prepareCloudflareAttachments(env, attachments, {
+ subject: input.subject,
+ html: input.html,
+ text: input.text,
+ headers,
+ publicOrigin: input.publicOrigin,
+ })
+ : { attachments, html: input.html, text: input.text };
if (prepared.text !== input.text || prepared.html !== input.html) {
await db.update(messages).set({ textBody: prepared.text ?? null, htmlBody: prepared.html ?? null }).where(eq(messages.id, messageId));
}
- const response = await env.EMAIL.send({
- from,
- to,
- ...(cc.length ? { cc } : {}),
- ...(bcc.length ? { bcc } : {}),
- subject: input.subject,
- headers: Object.keys(headers).length ? headers : undefined,
- html: prepared.html,
- text: prepared.text,
- attachments: prepared.attachments.map((attachment) =>
- attachment.disposition === "inline" && attachment.contentId
- ? {
- filename: attachment.filename,
- type: attachment.type,
- content: attachment.content,
- disposition: "inline" as const,
- contentId: attachment.contentId,
- }
- : {
- filename: attachment.filename,
- type: attachment.type,
- content: attachment.content,
- disposition: "attachment" as const,
- },
- ),
- });
+ const response = await sendThroughProvider(
+ env,
+ provider,
+ {
+ from,
+ to,
+ cc,
+ bcc,
+ subject: input.subject,
+ headers,
+ html: prepared.html,
+ text: prepared.text,
+ attachments: prepared.attachments.map((attachment) => ({
+ filename: attachment.filename,
+ type: attachment.type,
+ content: attachment.content,
+ disposition: attachment.disposition === "inline" && attachment.contentId ? "inline" : "attachment",
+ contentId: attachment.contentId,
+ })),
+ },
+ jobId,
+ );
// A fresh message starts its own conversation; Cloudflare's Message-ID is what
// any reply will name in In-Reply-To, so key the thread by it.
diff --git a/src/lib/email/svix.ts b/src/lib/email/svix.ts
new file mode 100644
index 0000000..5add4d5
--- /dev/null
+++ b/src/lib/email/svix.ts
@@ -0,0 +1,32 @@
+/**
+ * Verifies a Svix-signed webhook (what Resend sends): HMAC-SHA256 over
+ * `${id}.${timestamp}.${body}` with the base64 secret after the `whsec_` prefix,
+ * compared against every `v1,<base64>` entry in the signature header.
+ */
+export async function verifySvixSignature(
+ secret: string,
+ headers: { id: string | null; timestamp: string | null; signature: string | null },
+ body: string,
+ toleranceSeconds = 5 * 60,
+ now = Date.now(),
+): Promise<boolean> {
+ const { id, timestamp, signature } = headers;
+ if (!id || !timestamp || !signature) return false;
+ const seconds = Number(timestamp);
+ if (!Number.isFinite(seconds) || Math.abs(now / 1000 - seconds) > toleranceSeconds) return false;
+
+ const raw = secret.startsWith("whsec_") ? secret.slice(6) : secret;
+ let keyBytes: Uint8Array;
+ try { keyBytes = Uint8Array.from(atob(raw), (char) => char.charCodeAt(0)); } catch { return false; }
+ const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const expected = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`)));
+ const expectedB64 = btoa(String.fromCharCode(...expected));
+
+ return signature.split(" ").some((entry) => {
+ const [version, value] = entry.split(",");
+ if (version !== "v1" || !value || value.length !== expectedB64.length) return false;
+ let diff = 0;
+ for (let index = 0; index < value.length; index += 1) diff |= value.charCodeAt(index) ^ expectedB64.charCodeAt(index);
+ return diff === 0;
+ });
+}
diff --git a/src/lib/email/system-mail-types.d.ts b/src/lib/email/system-mail-types.d.ts
index 4593143..68c2fcf 100644
--- a/src/lib/email/system-mail-types.d.ts
+++ b/src/lib/email/system-mail-types.d.ts
@@ -3,4 +3,6 @@ export type SystemMailInput = {
subject: string;
text: string;
html?: string;
+ /** Send from a mailbox on this domain instead of the first usable one. */
+ hostname?: string;
};
diff --git a/src/lib/email/system-mail.ts b/src/lib/email/system-mail.ts
index 0aa6ffa..6ac34b1 100644
--- a/src/lib/email/system-mail.ts
+++ b/src/lib/email/system-mail.ts
@@ -1,7 +1,8 @@
-import { and, asc, eq } from "drizzle-orm";
+import { and, asc, eq, ne } from "drizzle-orm";
import { getDb } from "@/db";
import { domains, mailboxes, users } from "@/db/schema";
import { formatEmailAddress } from "@/lib/email/address";
+import { getOutboundProviderConfig, sendThroughProvider } from "@/lib/email/outbound-provider";
import type { SystemMailInput } from "@/lib/email/system-mail-types";
/**
@@ -14,12 +15,13 @@ import type { SystemMailInput } from "@/lib/email/system-mail-types";
* send from, and the caller decides what to tell the user.
*/
export async function sendSystemEmail(env: CloudflareEnv, input: SystemMailInput): Promise<boolean> {
- const sender = await pickSystemSender(env);
+ const sender = await pickSystemSender(env, input.hostname);
if (!sender) return false;
- await env.EMAIL.send({
- from: formatEmailAddress(sender.address, sender.name),
- to: input.to,
+ const from = formatEmailAddress(sender.address, sender.name);
+ await sendThroughProvider(env, await getOutboundProviderConfig(env, from), {
+ from,
+ to: [input.to],
subject: input.subject,
text: input.text,
html: input.html,
@@ -31,7 +33,10 @@ export async function sendSystemEmail(env: CloudflareEnv, input: SystemMailInput
return true;
}
-export async function pickSystemSender(env: CloudflareEnv): Promise<{ address: string; name: string } | null> {
+export async function pickSystemSender(
+ env: CloudflareEnv,
+ hostname?: string,
+): Promise<{ address: string; name: string } | null> {
const db = getDb(env);
const rows = await db
.select({
@@ -39,14 +44,24 @@ export async function pickSystemSender(env: CloudflareEnv): Promise<{ address: s
displayName: mailboxes.displayName,
hostname: domains.hostname,
role: users.role,
+ provider: domains.sendingProvider,
+ cloudflareSending: domains.sendingEnabled,
})
.from(mailboxes)
.innerJoin(domains, eq(mailboxes.domainId, domains.id))
.innerJoin(users, eq(mailboxes.userId, users.id))
- .where(and(eq(domains.sendingEnabled, true), eq(mailboxes.disabled, false), eq(users.disabled, false)))
+ .where(and(
+ ne(domains.sendingProvider, "none"),
+ ...(hostname ? [eq(domains.hostname, hostname.toLowerCase())] : []),
+ eq(mailboxes.disabled, false),
+ eq(users.disabled, false),
+ ))
.orderBy(asc(mailboxes.createdAt))
.limit(50);
- const chosen = rows.find((row) => row.role === "admin") ?? rows[0];
+ // Cloudflare sending only works once the zone's sending subdomain is enabled;
+ // Resend is verified per domain in Resend itself.
+ const usable = rows.filter((row) => row.provider !== "cloudflare" || row.cloudflareSending);
+ const chosen = usable.find((row) => row.role === "admin") ?? usable[0];
if (!chosen) return null;
return { address: `${chosen.localPart}@${chosen.hostname}`, name: chosen.displayName ?? "Mailflare" };
}
diff --git a/src/lib/mailboxes/domain-addresses.ts b/src/lib/mailboxes/domain-addresses.ts
index 61f61c1..fa318f2 100644
--- a/src/lib/mailboxes/domain-addresses.ts
+++ b/src/lib/mailboxes/domain-addresses.ts
@@ -87,7 +87,7 @@ export async function ensureMailboxDomainRouting(
.limit(1);
if (!primaryDomain) return;
const availableDomains = await db
- .select({ hostname: domains.hostname, zoneId: domains.zoneId })
+ .select({ hostname: domains.hostname, zoneId: domains.zoneId, receivingProvider: domains.receivingProvider })
.from(domains)
.where(eq(domains.userId, primaryDomain.userId));
const domainsByHostname = new Map(availableDomains.map((domain) => [domain.hostname.toLowerCase(), domain]));
@@ -97,7 +97,8 @@ export async function ensureMailboxDomainRouting(
addresses.map(async (address) => {
const hostname = address.slice(address.lastIndexOf("@") + 1);
const domain = domainsByHostname.get(hostname);
- if (domain) await ensureEmailRoutingRuleToWorker(env, domain.zoneId, address, changes);
+ // Worker routes only matter when Cloudflare is what receives this domain's mail.
+ if (domain && domain.receivingProvider === "cloudflare") await ensureEmailRoutingRuleToWorker(env, domain.zoneId, address, changes);
}),
);
const failure = results.find((result) => result.status === "rejected");
diff --git a/src/lib/seed-utils.ts b/src/lib/seed-utils.ts
index c23f0a3..e150dc2 100644
--- a/src/lib/seed-utils.ts
+++ b/src/lib/seed-utils.ts
@@ -265,6 +265,7 @@ export async function ensureDemoDomain(env: CloudflareEnv, userId: string) {
status: "active",
routingEnabled: true,
sendingRequested: true,
+ sendingProvider: "cloudflare" as const,
sendingEnabled: true,
});
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index 2b2e173..9274bc9 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -72,6 +72,8 @@ export const addDomainSchema = z.object({
enableRouting: z.boolean().optional(),
enableSending: z.boolean().optional(),
replaceMxRecords: z.boolean().optional(),
+ /** Which service receives mail for the domain; Cloudflare Email Routing when omitted. */
+ receivingProvider: z.enum(["none", "cloudflare", "resend", "ses"]).optional(),
});
export const loginSchema = z.object({
diff --git a/tests/provider-aws-resend.test.mjs b/tests/provider-aws-resend.test.mjs
new file mode 100644
index 0000000..777481a
--- /dev/null
+++ b/tests/provider-aws-resend.test.mjs
@@ -0,0 +1,207 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const outDir = mkdtempSync(join(tmpdir(), "mailflare-providers-"));
+after(() => rmSync(outDir, { recursive: true, force: true }));
+
+async function bundle(entry, outfile) {
+ await build({
+ entryPoints: [join(root, entry)],
+ outfile: join(outDir, outfile),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node22",
+ logLevel: "silent",
+ alias: { "@": join(root, "src") },
+ });
+ return import(pathToFileURL(join(outDir, outfile)).href);
+}
+
+const sigv4 = await bundle("src/lib/aws/sigv4.ts", "sigv4.mjs");
+const xml = await bundle("src/lib/aws/xml.ts", "xml.mjs");
+const notification = await bundle("src/lib/aws/ses-notification.ts", "notification.mjs");
+const svix = await bundle("src/lib/email/svix.ts", "svix.mjs");
+const config = await bundle("src/lib/aws/config.ts", "config.mjs").catch(() => null);
+const validate = await bundle("src/lib/aws/validate.ts", "validate.mjs");
+const sesLib = await bundle("src/lib/aws/ses.ts", "ses.mjs");
+
+test("SigV4 matches the AWS get-vanilla test vector", async () => {
+ const headers = await sigv4.signAwsRequest({
+ method: "GET",
+ url: new URL("https://example.amazonaws.com/"),
+ headers: {},
+ body: "",
+ region: "us-east-1",
+ service: "service",
+ credentials: { accessKeyId: "AKIDEXAMPLE", secretAccessKey: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" },
+ now: new Date("2015-08-30T12:36:00Z"),
+ });
+ assert.equal(
+ headers.Authorization,
+ "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-date, Signature=5fa00fa31553b73ebf1942676e86291e8372ff2a2260956d9b8aae1d763fbf31",
+ );
+});
+
+test("SigV4 matches the AWS post-x-www-form-urlencoded test vector", async () => {
+ const headers = await sigv4.signAwsRequest({
+ method: "POST",
+ url: new URL("https://example.amazonaws.com/"),
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: "Param1=value1",
+ region: "us-east-1",
+ service: "service",
+ credentials: { accessKeyId: "AKIDEXAMPLE", secretAccessKey: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" },
+ now: new Date("2015-08-30T12:36:00Z"),
+ });
+ assert.equal(
+ headers.Authorization,
+ "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=ff11897932ad3f4e8b18135d722051e5ac45fc38421b1da7b9d196a0fe09473a",
+ );
+});
+
+test("XML helpers read AWS responses", () => {
+ const doc = "<R><Account>1234</Account><Rules><member><Name>a</Name></member><member><Name>b&amp;c</Name></member></Rules></R>";
+ assert.equal(xml.xmlTag(doc, "Account"), "1234");
+ assert.deepEqual(xml.xmlBlocks(xml.xmlBlocks(doc, "Rules")[0], "member").map((member) => xml.xmlTag(member, "Name")), ["a", "b&c"]);
+ assert.equal(xml.xmlTag(doc, "Missing"), null);
+});
+
+test("SES notifications parse S3 receipts and ignore everything else", () => {
+ const message = JSON.stringify({
+ notificationType: "Received",
+ mail: { source: "[email protected]", destination: ["[email protected]"], headers: [{ name: "Subject", value: "Hi" }] },
+ receipt: { recipients: ["[email protected]"], virusVerdict: { status: "PASS" }, action: { type: "S3", bucketName: "b", objectKey: "inbound/abc" } },
+ });
+ assert.deepEqual(notification.parseSesNotification(message), {
+ from: "[email protected]", recipients: ["[email protected]"], bucket: "b", key: "inbound/abc", virusFailed: false, headers: { subject: "Hi" },
+ });
+ assert.equal(notification.parseSesNotification(JSON.stringify({ notificationType: "Bounce" })), null);
+ assert.equal(notification.parseSesNotification("not json"), null);
+ assert.equal(notification.parseSesNotification(message.replace('"PASS"', '"FAIL"')).virusFailed, true);
+ assert.equal(notification.safeEqual("abc", "abc"), true);
+ assert.equal(notification.safeEqual("abc", "abd"), false);
+});
+
+test("Svix signatures verify, and reject tampering, stale timestamps and wrong secrets", async () => {
+ const secretBytes = Buffer.from("super-secret-key-material");
+ const secret = `whsec_${secretBytes.toString("base64")}`;
+ const id = "msg_1";
+ const timestamp = String(Math.floor(Date.now() / 1000));
+ const body = '{"type":"email.received"}';
+ const { createHmac } = await import("node:crypto");
+ const signature = `v1,${createHmac("sha256", secretBytes).update(`${id}.${timestamp}.${body}`).digest("base64")}`;
+ const headers = { id, timestamp, signature };
+
+ assert.equal(await svix.verifySvixSignature(secret, headers, body), true);
+ assert.equal(await svix.verifySvixSignature(secret, { ...headers, signature: `v1,bogus ${signature}` }, body), true, "any listed signature may match");
+ assert.equal(await svix.verifySvixSignature(secret, headers, body + " "), false);
+ assert.equal(await svix.verifySvixSignature(`whsec_${Buffer.from("other").toString("base64")}`, headers, body), false);
+ assert.equal(await svix.verifySvixSignature(secret, { ...headers, timestamp: String(Number(timestamp) - 3600) }, body), false);
+ assert.equal(await svix.verifySvixSignature(secret, { id: null, timestamp, signature }, body), false);
+});
+
+test("AWS region validation and SES receiving regions", () => {
+ assert.ok(config, "config module bundles");
+ assert.equal(config.isValidRegion("us-east-1"), true);
+ assert.equal(config.isValidRegion("eu-west-2"), true);
+ assert.equal(config.isValidRegion("us-gov-west-1"), true);
+ assert.equal(config.isValidRegion("nowhere"), false);
+ assert.equal(config.isValidRegion("us-east-1; rm"), false);
+ assert.ok(config.SES_RECEIVING_REGIONS.includes("us-east-1"));
+ assert.ok(!config.SES_RECEIVING_REGIONS.includes("af-south-1"));
+});
+
+
+function mockAws(handler) {
+ const original = globalThis.fetch;
+ const calls = [];
+ globalThis.fetch = async (input, init = {}) => {
+ const url = new URL(typeof input === "string" ? input : input.url ?? input.href);
+ const body = typeof init.body === "string" ? init.body : "";
+ const action = new URLSearchParams(body).get("Action") ?? "";
+ calls.push({ url, method: init.method ?? "GET", action, body, headers: init.headers });
+ const result = handler({ url, action, body });
+ return new Response(result.body, { status: result.status ?? 200 });
+ };
+ return { calls, restore: () => { globalThis.fetch = original; } };
+}
+
+const creds = { accessKeyId: "AKIAEXAMPLE000000000", secretAccessKey: "x".repeat(40), region: "us-east-1" };
+
+test("validation rejects credentials AWS refuses", async () => {
+ const mock = mockAws(() => ({ status: 403, body: "<ErrorResponse><Error><Code>InvalidClientTokenId</Code><Message>bad token</Message></Error></ErrorResponse>" }));
+ try {
+ await assert.rejects(() => validate.validateAwsConfig(creds), (error) => error instanceof validate.AwsCredentialsError && /rejected/.test(error.message));
+ await assert.rejects(() => validate.validateAwsConfig({ ...creds, region: "mars-1" }), /not a valid AWS region/);
+ } finally { mock.restore(); }
+});
+
+test("validation reports each missing permission instead of failing", async () => {
+ const mock = mockAws(({ url, action }) => {
+ if (action === "GetCallerIdentity") return { body: "<R><Account>111122223333</Account><Arn>arn:aws:iam::111122223333:user/x</Arn></R>" };
+ if (url.pathname === "/v2/email/account") return { body: JSON.stringify({ ProductionAccessEnabled: false, SendingEnabled: true }) };
+ if (action === "DescribeActiveReceiptRuleSet") return { status: 403, body: "<ErrorResponse><Error><Code>AccessDenied</Code><Message>no</Message></Error></ErrorResponse>" };
+ if (action === "ListTopics") return { body: "<ListTopicsResponse/>" };
+ return { status: 403, body: "<Error><Code>AccessDenied</Code><Message>no</Message></Error>" };
+ });
+ try {
+ const report = await validate.validateAwsConfig(creds);
+ assert.equal(report.accountId, "111122223333");
+ assert.equal(report.sending, true);
+ assert.equal(report.productionAccess, false);
+ assert.equal(report.receiving, false);
+ assert.equal(report.sns, true);
+ assert.equal(report.s3, false);
+ assert.ok(report.missing.includes("ses:CreateReceiptRule"));
+ assert.ok(report.missing.includes("s3:CreateBucket"));
+ assert.ok(!report.missing.includes("sns:CreateTopic"));
+ assert.equal(report.receivingRegion, true);
+ } finally { mock.restore(); }
+});
+
+test("SES calls are signed and shaped for the v1 receipt-rule API", async () => {
+ const mock = mockAws(() => ({ body: "<R/>" }));
+ try {
+ await sesLib.upsertReceiptRule(creds, { ruleSet: "rs", name: "mailflare-example-com", recipient: "example.com", bucket: "bkt", prefix: "inbound/", topicArn: "arn:aws:sns:us-east-1:1:t" });
+ const call = mock.calls[0];
+ assert.equal(call.url.host, "email.us-east-1.amazonaws.com");
+ assert.equal(call.action, "CreateReceiptRule");
+ const params = new URLSearchParams(call.body);
+ assert.equal(params.get("Version"), "2010-12-01");
+ assert.equal(params.get("Rule.Recipients.member.1"), "example.com");
+ assert.equal(params.get("Rule.Actions.member.1.S3Action.BucketName"), "bkt");
+ assert.equal(params.get("Rule.Actions.member.1.S3Action.TopicArn"), "arn:aws:sns:us-east-1:1:t");
+ assert.match(call.headers.Authorization, /Credential=AKIAEXAMPLE000000000\/\d{8}\/us-east-1\/ses\/aws4_request/);
+ } finally { mock.restore(); }
+});
+
+test("an existing receipt rule is updated, not duplicated", async () => {
+ const mock = mockAws(({ action }) => action === "CreateReceiptRule"
+ ? { status: 400, body: "<ErrorResponse><Error><Code>AlreadyExists</Code><Message>exists</Message></Error></ErrorResponse>" }
+ : { body: "<R/>" });
+ try {
+ await sesLib.upsertReceiptRule(creds, { ruleSet: "rs", name: "n", recipient: "example.com", bucket: "b", prefix: "inbound/", topicArn: "arn" });
+ assert.deepEqual(mock.calls.map((call) => call.action), ["CreateReceiptRule", "UpdateReceiptRule"]);
+ } finally { mock.restore(); }
+});
+
+test("SES send maps the message and returns the Message-ID SES will use", async () => {
+ const mock = mockAws(() => ({ body: JSON.stringify({ MessageId: "0100abc" }) }));
+ try {
+ const result = await sesLib.sendSesEmail(creds, { from: "[email protected]", to: ["[email protected]"], subject: "Hi", text: "t", html: "<p>t</p>", headers: { "Message-ID": "<mine>", "In-Reply-To": "<x>" }, attachments: [{ filename: "f.txt", type: "text/plain", content: new TextEncoder().encode("hello").buffer, disposition: "attachment" }] });
+ assert.equal(result.messageId, "<[email protected]>");
+ const sent = JSON.parse(mock.calls[0].body);
+ assert.equal(sent.FromEmailAddress, "[email protected]");
+ assert.deepEqual(sent.Content.Simple.Headers, [{ Name: "In-Reply-To", Value: "<x>" }]);
+ assert.equal(sent.Content.Simple.Attachments[0].RawContent, Buffer.from("hello").toString("base64"));
+ const eu = await sesLib.sendSesEmail({ ...creds, region: "eu-west-1" }, { from: "[email protected]", to: ["[email protected]"], subject: "s", text: "t" });
+ assert.equal(eu.messageId, "<[email protected]>");
+ } finally { mock.restore(); }
+});
diff --git a/tests/recipient-display.test.mjs b/tests/recipient-display.test.mjs
index 33d706a..c78da9e 100644
--- a/tests/recipient-display.test.mjs
+++ b/tests/recipient-display.test.mjs
@@ -106,6 +106,6 @@ test("migration adds the user column off by default and the journal lists it", (
assert.equal(db.prepare("SELECT show_full_recipient_addresses AS value FROM users").get().value, 0);
const journal = JSON.parse(readFileSync(join(root, "drizzle/migrations/meta/_journal.json"), "utf8"));
- assert.equal(journal.entries.at(-1).tag, "0050_add_show_full_recipient_addresses");
- assert.equal(journal.entries.at(-1).idx, 42);
+ const entry = journal.entries.find((item) => item.tag === "0050_add_show_full_recipient_addresses");
+ assert.equal(entry?.idx, 42);
});