Email for professionals and teams
[setup] delete MX if already exist
Hieu Nguyen (Jack)76adbc8ebdc7
diff --git a/docs/deployment.md b/docs/deployment.mdindex 02aa027..cae8d9d 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -10,7 +10,7 @@ Set up Mailflare in three steps:2. **Complete setup:** open the deployed app and follow `/setup` to check the installation and create the first admin account.3. **Connect your domain:** add a domain managed by the same Cloudflare account. Mailflare configures email routing and, when available and selected, email sending before helping you create the first mailbox.-The Worker name must remain `mailflare`. Before starting, create the required `CF_TOKEN` with **Zone Read**, **Email Routing Edit**, and **Email Routing Rules Write** permissions for every domain you plan to connect. Add **Email Sending Edit** when Mailflare should send email; it is optional for receive-only domains.+The Worker name must remain `mailflare`. Before starting, create the required `CF_TOKEN` with **Zone Read**, **DNS Edit**, **Email Routing Edit**, and **Email Routing Rules Write** permissions for every domain you plan to connect. DNS Edit lets the confirmed setup flow replace conflicting MX records. Add **Email Sending Edit** when Mailflare should send email; it is optional for receive-only domains.## Step 1: Deploy mailflare@@ -26,7 +26,7 @@ The Worker name must remain `mailflare`. Before starting, create the required `CMailflare requires this runtime value:-- `CF_TOKEN` — a scoped Cloudflare API token with **Zone Read**, **Email Routing Edit**, and **Email Routing Rules Write** access for the domains you will connect. Add **Email Sending Edit** to enable outbound mail. This is separate from the token Cloudflare uses to deploy the app.+- `CF_TOKEN` — a scoped Cloudflare API token with **Zone Read**, **DNS Edit**, **Email Routing Edit**, and **Email Routing Rules Write** access for the domains you will connect. Add **Email Sending Edit** to enable outbound mail. This is separate from the token Cloudflare uses to deploy the app.Paste only the token secret into `CF_TOKEN`. Do not include the word `Bearer` and do not use the token ID. The token must belong to the same Cloudflare account as the domains you connect.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex cfeeef4..a1372a7 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -24,6 +24,10 @@ If you use a legacy Global API Key, set `CF_EMAIL` and `CF_API_KEY` instead of pUpdate the token so it can read the zone and manage its DNS, Email Routing settings, and Email Routing rules. The recommended scoped permissions are listed in the [deployment guide](deployment.md#required-configuration).+## Cloudflare error 2008 for existing MX records++Cloudflare Email Routing cannot be enabled while another mail provider's MX records are present. Mailflare shows a confirmation before replacing them. Continuing deletes the existing MX records and points incoming mail to Cloudflare Email Routing, so the previous provider will stop receiving mail. The `CF_TOKEN` needs **DNS Edit** permission for this action.+## D1 error 7404: Database could not be foundD1 database IDs belong to a specific Cloudflare account. This error commonly means `wrangler.jsonc` contains an ID copied from another account.diff --git a/package.json b/package.jsonindex bb940a3..141de40 100644--- a/package.json+++ b/package.json@@ -27,7 +27,7 @@"cloudflare": {"bindings": {"CF_TOKEN": {- "description": "Runtime Cloudflare API token used by Mailflare onboarding to call the Zones and Email Routing APIs. Cloudflare's deploy/build token is not passed to the app, so create this separately at https://dash.cloudflare.com/profile/api-tokens with `Zone Read`, `Email Routing Edit`, and `Email Routing Rules Write` permissions for the zones you will connect. Add `Email Sending Edit` to enable outbound mail. Paste only the token secret value, without `Bearer`."+ "description": "Runtime Cloudflare API token used by Mailflare onboarding to call the Zones, DNS, and Email Routing APIs. Cloudflare's deploy/build token is not passed to the app, so create this separately at https://dash.cloudflare.com/profile/api-tokens with `Zone Read`, `DNS Edit`, `Email Routing Edit`, and `Email Routing Rules Write` permissions for the zones you will connect. Add `Email Sending Edit` to enable outbound mail. Paste only the token secret value, without `Bearer`."},"TURNSTILE_SECRET_KEY": {"description": "Cloudflare Turnstile secret key used to verify login and first-run registration challenges. Pair with NEXT_PUBLIC_TURNSTILE_SITE_KEY at build time."diff --git a/src/app/(auth)/onboarding/onboarding-client.tsx b/src/app/(auth)/onboarding/onboarding-client.tsxindex 6b5d56e..4253159 100644--- a/src/app/(auth)/onboarding/onboarding-client.tsx+++ b/src/app/(auth)/onboarding/onboarding-client.tsx@@ -2,7 +2,7 @@import { useRouter } from "next/navigation";import { useEffect, useState } from "react";-import { ArrowRight, CheckCircle2, LoaderCircle, MailPlus } from "lucide-react";+import { AlertTriangle, ArrowRight, CheckCircle2, LoaderCircle, MailPlus } from "lucide-react";import { AuthShell } from "@/components/auth/auth-shell";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -21,6 +21,7 @@ export function OnboardingClient() {const [domainId, setDomainId] = useState("");const [localPart, setLocalPart] = useState("me");const [error, setError] = useState<string | null>(null);+ const [mxConflict, setMxConflict] = useState(false);const [loading, setLoading] = useState(false);useEffect(() => {@@ -35,7 +36,7 @@ export function OnboardingClient() {.catch(() => undefined);}, []);- async function addDomain() {+ async function addDomain(replaceMxRecords = false) {setLoading(true);setError(null);@@ -50,7 +51,7 @@ export function OnboardingClient() {return;}checkedDomain = result.domain;- sendingRequested = true;+ sendingRequested = false;setDomainCheck(result.domain);setEnableSending(sendingRequested);}@@ -60,12 +61,18 @@ export function OnboardingClient() {return;}- const { ok, data } = await createDomain(checkedDomain.hostname, sendingRequested);+ const { ok, data } = await createDomain(checkedDomain.hostname, sendingRequested, replaceMxRecords);setLoading(false);if (!ok || !data.domain) {+ if (data.code === "MX_RECORDS_CONFLICT") {+ setMxConflict(true);+ setError(null);+ return;+ }setError(data.error ?? "Failed to add domain");return;}+ setMxConflict(false);setDomainId(data.domain.id);setStep(2);}@@ -76,6 +83,7 @@ export function OnboardingClient() {setDomainChecking(true);setError(null);+ setMxConflict(false);const result = await checkDomain(normalized);setDomainChecking(false);if (!result.ok || !result.domain) {@@ -86,7 +94,7 @@ export function OnboardingClient() {}setDomainCheck(result.domain);- setEnableSending(true);+ setEnableSending(false);}async function addMailbox() {@@ -139,6 +147,7 @@ export function OnboardingClient() {if (domainCheck?.hostname !== e.target.value.toLowerCase().trim()) {setDomainCheck(null);setEnableSending(false);+ setMxConflict(false);}}}onBlur={() => void inspectDomain()}@@ -175,13 +184,32 @@ export function OnboardingClient() {Domain found in Cloudflare as {domainCheck.zone.name}</div>)}- <Button- onClick={addDomain}- disabled={!hostname || loading || domainChecking}- className="h-11 w-full rounded-full px-6 active:scale-[0.98]"- >- {loading ? "Adding..." : "Add domain"}- </Button>+ {mxConflict && (+ <div className="space-y-3 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-4 text-amber-900">+ <div className="flex items-start gap-3">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />+ <p className="text-sm leading-6">+ Existing MX records deliver mail to another provider. Continuing deletes those records and replaces them with Cloudflare Email Routing, so the previous provider will stop receiving mail.+ </p>+ </div>+ <Button+ onClick={() => void addDomain(true)}+ disabled={loading}+ className="h-11 w-full rounded-full px-6 active:scale-[0.98]"+ >+ {loading ? "Replacing MX records..." : "Delete MX records and continue"}+ </Button>+ </div>+ )}+ {!mxConflict && (+ <Button+ onClick={() => void addDomain()}+ disabled={!hostname || loading || domainChecking}+ className="h-11 w-full rounded-full px-6 active:scale-[0.98]"+ >+ {loading ? "Adding..." : "Add domain"}+ </Button>+ )}</>)}{step === 2 && (diff --git a/src/app/(auth)/onboarding/types.d.ts b/src/app/(auth)/onboarding/types.d.tsindex e94f750..17495f5 100644--- a/src/app/(auth)/onboarding/types.d.ts+++ b/src/app/(auth)/onboarding/types.d.ts@@ -5,6 +5,7 @@ export type DomainListResult = {export type DomainCreateResult = {domain?: { id: string };error?: string;+ code?: "MX_RECORDS_CONFLICT";};export type DomainPreflight = {diff --git a/src/app/(auth)/onboarding/utils.ts b/src/app/(auth)/onboarding/utils.tsindex ed8bfd1..839a2c4 100644--- a/src/app/(auth)/onboarding/utils.ts+++ b/src/app/(auth)/onboarding/utils.ts@@ -24,11 +24,12 @@ export async function checkDomain(hostname: string): Promise<DomainPreflightRespexport async function createDomain(hostname: string,enableSending: boolean,+ replaceMxRecords = false,): Promise<{ ok: boolean; data: DomainCreateResult }> {const res = await authFetch("/api/domains", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ hostname, enableRouting: true, enableSending }),+ body: JSON.stringify({ hostname, enableRouting: true, enableSending, replaceMxRecords }),});return {diff --git a/src/app/(auth)/register/register-client.tsx b/src/app/(auth)/register/register-client.tsxindex 706136f..b3d1813 100644--- a/src/app/(auth)/register/register-client.tsx+++ b/src/app/(auth)/register/register-client.tsx@@ -2,7 +2,7 @@import Link from "next/link";import { useRouter } from "next/navigation";-import { ArrowRight, CheckCircle2, LoaderCircle, MailPlus, XCircle } from "lucide-react";+import { AlertTriangle, ArrowRight, CheckCircle2, LoaderCircle, MailPlus, XCircle } from "lucide-react";import { useEffect, useState } from "react";import { AuthShell } from "@/components/auth/auth-shell";import { Button } from "@/components/ui/button";@@ -36,6 +36,7 @@ export function RegisterClient() {const [databaseMigrated, setDatabaseMigrated] = useState(false);const [preparationComplete, setPreparationComplete] = useState(false);const [error, setError] = useState<string | null>(null);+ const [mxConflict, setMxConflict] = useState(false);const [loading, setLoading] = useState(false);const [turnstileReset, setTurnstileReset] = useState(0);@@ -89,7 +90,7 @@ export function RegisterClient() {return;}setSetupDomain(data.domain.hostname);- setSetupEnableSending(usedCachedCheck ? enableSending : true);+ setSetupEnableSending(usedCachedCheck ? enableSending : false);setStep(3);}@@ -109,7 +110,7 @@ export function RegisterClient() {}setDomainCheck(data.domain);- setEnableSending(true);+ setEnableSending(false);}async function onSubmit(e: React.FormEvent<HTMLFormElement>) {@@ -118,6 +119,8 @@ export function RegisterClient() {setError(null);const form = new FormData(e.currentTarget);+ const submitter = (e.nativeEvent as SubmitEvent).submitter as HTMLButtonElement | null;+ const replaceMxRecords = submitter?.value === "true";const domain = setupDomain ?? primaryDomain;if (!domain) {setLoading(false);@@ -131,9 +134,16 @@ export function RegisterClient() {enableSending: setupDomain? setupEnableSending: primaryDomainSendingRequested ?? undefined,+ replaceMxRecords,});setLoading(false);if (!ok) {+ if (data.code === "MX_RECORDS_CONFLICT") {+ setMxConflict(true);+ setError(null);+ setTurnstileReset((value) => value + 1);+ return;+ }setError(typeof data.error === "string" ? data.error : "Registration failed",);@@ -359,14 +369,28 @@ export function RegisterClient() {{error}</p>)}+ {mxConflict && (+ <div className="space-y-3 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-4 text-amber-900">+ <div className="flex items-start gap-3">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />+ <p className="text-sm leading-6">+ Existing MX records deliver mail to another provider. Continuing deletes those records and replaces them with Cloudflare Email Routing, so the previous provider will stop receiving mail.+ </p>+ </div>+ </div>+ )}<TurnstileField resetSignal={turnstileReset} />- <Button- type="submit"- className="h-11 w-full rounded-full px-6 active:scale-[0.98] mt-8"- disabled={loading || hasAdminAccount === null || hasPrimaryDomain === null}- >- {loading ? "Creating..." : "Create account"}- </Button>+ <Button+ type="submit"+ name={mxConflict ? "replaceMxRecords" : undefined}+ value={mxConflict ? "true" : undefined}+ className="h-11 w-full rounded-full px-6 active:scale-[0.98] mt-8"+ disabled={loading || hasAdminAccount === null || hasPrimaryDomain === null}+ >+ {loading+ ? mxConflict ? "Replacing MX records..." : "Creating..."+ : mxConflict ? "Delete MX records and create account" : "Create account"}+ </Button></form>)}</AuthShell>diff --git a/src/app/(auth)/register/types.d.ts b/src/app/(auth)/register/types.d.tsindex 6c45a4a..1268c17 100644--- a/src/app/(auth)/register/types.d.ts+++ b/src/app/(auth)/register/types.d.ts@@ -31,4 +31,5 @@ export type RegisterResult = {token?: string;redirect?: string;error?: string;+ code?: "MX_RECORDS_CONFLICT";};diff --git a/src/app/(auth)/register/utils.ts b/src/app/(auth)/register/utils.tsindex 5cf5ea8..3be694f 100644--- a/src/app/(auth)/register/utils.ts+++ b/src/app/(auth)/register/utils.ts@@ -36,7 +36,7 @@ export async function submitPrimaryDomain(hostname: string): Promise<{ ok: booleexport async function submitRegistration(form: FormData,- payload: { firstRun: boolean; domain: string; enableSending?: boolean },+ payload: { firstRun: boolean; domain: string; enableSending?: boolean; replaceMxRecords?: boolean },): Promise<{ ok: boolean; data: RegisterResult }> {const res = await fetch("/api/auth/register", {method: "POST",@@ -46,6 +46,7 @@ export async function submitRegistration(? {domain: payload.domain,enableSending: payload.enableSending,+ replaceMxRecords: payload.replaceMxRecords,username: form.get("username"),password: form.get("password"),resetEmail: form.get("resetEmail"),diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.tsindex 45a809a..6573557 100644--- a/src/app/api/auth/register/route.ts+++ b/src/app/api/auth/register/route.ts@@ -16,6 +16,7 @@ import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";import { readJsonBody } from "@/lib/http/request";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { verifyTurnstileToken } from "@/lib/auth/turnstile";+import { getDomainProvisioningError } from "@/lib/domains/errors";export async function POST(request: Request) {const env = getEnv();@@ -70,6 +71,7 @@ export async function POST(request: Request) {const added = await addDomainForUser(env, userId, domainName, {enableRouting: true,enableSending: firstRunParsed.data.enableSending ?? true,+ replaceMxRecords: firstRunParsed.data.replaceMxRecords,});const domain = added.domain;changes = added.changes;@@ -92,8 +94,11 @@ export async function POST(request: Request) {} catch (cleanupError) {console.warn("Failed to remove the partial user after registration failure", cleanupError);}- const message = err instanceof Error ? err.message : "Domain setup failed";- return NextResponse.json({ error: message }, { status: 502 });+ const failure = getDomainProvisioningError(err, "Domain setup failed", 502);+ return NextResponse.json(+ { error: failure.message, code: failure.code },+ { status: failure.status },+ );}const token = await createSession(env, userId);diff --git a/src/app/api/domains/route.ts b/src/app/api/domains/route.tsindex a622682..d6becde 100644--- a/src/app/api/domains/route.ts+++ b/src/app/api/domains/route.ts@@ -4,6 +4,7 @@ import { requireUser } from "@/lib/auth/cookies";import { addDomainSchema } from "@/lib/validators";import { addDomainForUser, getDomainDns, listUserDomains } from "@/lib/domains/service";import { summariseDns, type DnsStatusSummary } from "@/lib/dns-status";+import { getDomainProvisioningError } from "@/lib/domains/errors";export async function GET(request: NextRequest) {const env = getEnv();@@ -60,10 +61,14 @@ export async function POST(request: Request) {const result = await addDomainForUser(env, user.id, parsed.data.hostname, {enableRouting: parsed.data.enableRouting,enableSending: parsed.data.enableSending,+ replaceMxRecords: parsed.data.replaceMxRecords,});return NextResponse.json(result);} catch (err) {- const message = err instanceof Error ? err.message : "Failed to add domain";- return NextResponse.json({ error: message }, { status: 400 });+ const failure = getDomainProvisioningError(err, "Failed to add domain");+ return NextResponse.json(+ { error: failure.message, code: failure.code },+ { status: failure.status },+ );}}diff --git a/src/lib/cloudflare-api-error.ts b/src/lib/cloudflare-api-error.tsnew file mode 100644index 0000000..124a352--- /dev/null+++ b/src/lib/cloudflare-api-error.ts@@ -0,0 +1,17 @@+import type { CfApiError } from "@/lib/cloudflare-api.types";++export class CloudflareApiError extends Error {+ constructor(+ message: string,+ readonly status: number,+ readonly path: string,+ readonly errors: CfApiError[],+ ) {+ super(message);+ this.name = "CloudflareApiError";+ }+}++export function isCloudflareApiErrorCode(error: unknown, code: number): boolean {+ return error instanceof CloudflareApiError && error.errors.some((item) => item.code === code);+}diff --git a/src/lib/cloudflare-api.ts b/src/lib/cloudflare-api.tsindex 03d1701..4171855 100644--- a/src/lib/cloudflare-api.ts+++ b/src/lib/cloudflare-api.ts@@ -11,6 +11,7 @@ import {getCloudflareAuthHint,getEmailWorkerName,} from "@/lib/cloudflare-api-utils";+import { CloudflareApiError } from "@/lib/cloudflare-api-error";import { getZoneLookupCandidates } from "@/lib/domains/utils";export type { CfDnsRecord } from "@/lib/cloudflare-api.types";@@ -31,8 +32,11 @@ export async function cfRequest<T>(const json = (await res.json()) as CfResponse<T>;if (!json.success) {- throw new Error(+ throw new CloudflareApiError(`${formatCloudflareError(path, res.status, res.statusText, json.errors ?? [])}${getCloudflareAuthHint(json.errors ?? [])}`,+ res.status,+ path,+ json.errors ?? [],);}return json.result;diff --git a/src/lib/cloudflare-api.types.d.ts b/src/lib/cloudflare-api.types.d.tsindex d3fae99..63f6b6f 100644--- a/src/lib/cloudflare-api.types.d.ts+++ b/src/lib/cloudflare-api.types.d.ts@@ -1,9 +1,13 @@export type CfDnsRecord = {+ id?: string;type?: string;name?: string;content?: string;priority?: number;ttl?: number;+ proxied?: boolean;+ comment?: string;+ tags?: string[];};export type CfApiError = {diff --git a/src/lib/cloudflare-dns.ts b/src/lib/cloudflare-dns.tsnew file mode 100644index 0000000..320b6ac--- /dev/null+++ b/src/lib/cloudflare-dns.ts@@ -0,0 +1,35 @@+import { cfRequest } from "@/lib/cloudflare-api";+import type { CfDnsRecord } from "@/lib/cloudflare-api.types";+import type { CloudflareDnsRecordCreate } from "@/lib/cloudflare-dns.types";++export async function listMxRecords(+ env: CloudflareEnv,+ zoneId: string,+ hostname: string,+): Promise<CfDnsRecord[]> {+ return cfRequest<CfDnsRecord[]>(+ env,+ `/zones/${zoneId}/dns_records?type=MX&name=${encodeURIComponent(hostname)}&per_page=5000`,+ );+}++export async function deleteDnsRecord(+ env: CloudflareEnv,+ zoneId: string,+ recordId: string,+): Promise<void> {+ await cfRequest<unknown>(env, `/zones/${zoneId}/dns_records/${recordId}`, {+ method: "DELETE",+ });+}++export async function createDnsRecord(+ env: CloudflareEnv,+ zoneId: string,+ record: CloudflareDnsRecordCreate,+): Promise<CfDnsRecord> {+ return cfRequest<CfDnsRecord>(env, `/zones/${zoneId}/dns_records`, {+ method: "POST",+ body: JSON.stringify(record),+ });+}diff --git a/src/lib/cloudflare-dns.types.d.ts b/src/lib/cloudflare-dns.types.d.tsnew file mode 100644index 0000000..192c3c8--- /dev/null+++ b/src/lib/cloudflare-dns.types.d.ts@@ -0,0 +1,10 @@+export type CloudflareDnsRecordCreate = {+ type: "MX";+ name: string;+ content: string;+ priority: number;+ ttl: number;+ proxied?: boolean;+ comment?: string;+ tags?: string[];+};diff --git a/src/lib/domains/errors.ts b/src/lib/domains/errors.tsnew file mode 100644index 0000000..092e7e3--- /dev/null+++ b/src/lib/domains/errors.ts@@ -0,0 +1,22 @@+import { isCloudflareApiErrorCode } from "@/lib/cloudflare-api-error";+import type { DomainProvisioningError } from "@/lib/domains/types";++export function getDomainProvisioningError(+ error: unknown,+ fallback: string,+ fallbackStatus = 400,+): DomainProvisioningError {+ if (isCloudflareApiErrorCode(error, 2008)) {+ return {+ code: "MX_RECORDS_CONFLICT",+ message:+ "Existing MX records currently deliver mail to another provider. Continue to delete them and replace them with Cloudflare Email Routing.",+ status: 409,+ };+ }++ return {+ message: error instanceof Error ? error.message : fallback,+ status: fallbackStatus,+ };+}diff --git a/src/lib/domains/mx-records.ts b/src/lib/domains/mx-records.tsnew file mode 100644index 0000000..9d5338c--- /dev/null+++ b/src/lib/domains/mx-records.ts@@ -0,0 +1,45 @@+import { createDnsRecord, deleteDnsRecord, listMxRecords } from "@/lib/cloudflare-dns";+import type { CfDnsRecord } from "@/lib/cloudflare-api.types";+import type { CloudflareDnsRecordCreate } from "@/lib/cloudflare-dns.types";++function toCreateInput(record: CfDnsRecord): CloudflareDnsRecordCreate {+ if (!record.name || !record.content || record.priority === undefined) {+ throw new Error("Cloudflare returned an incomplete MX record");+ }++ return {+ type: "MX",+ name: record.name,+ content: record.content,+ priority: record.priority,+ ttl: record.ttl ?? 1,+ ...(record.proxied === undefined ? {} : { proxied: record.proxied }),+ ...(record.comment === undefined ? {} : { comment: record.comment }),+ ...(record.tags === undefined ? {} : { tags: record.tags }),+ };+}++export async function removeMxRecords(+ env: CloudflareEnv,+ zoneId: string,+ hostname: string,+ deleted: CfDnsRecord[],+): Promise<void> {+ const records = await listMxRecords(env, zoneId, hostname);++ for (const record of records) {+ if (!record.id) throw new Error("Cloudflare returned an MX record without an id");+ await deleteDnsRecord(env, zoneId, record.id);+ deleted.push(record);+ }+}++export async function restoreMxRecords(+ env: CloudflareEnv,+ zoneId: string,+ records: CfDnsRecord[],+): Promise<void> {+ for (const record of records) {+ await createDnsRecord(env, zoneId, toCreateInput(record));+ }+}diff --git a/src/lib/domains/provision.ts b/src/lib/domains/provision.tsindex 515f932..411c656 100644--- a/src/lib/domains/provision.ts+++ b/src/lib/domains/provision.ts@@ -12,6 +12,8 @@ import {import { isZoneApex } from "@/lib/domains/utils";import { hasCloudflareCredentials, isNodeRuntime } from "@/lib/runtime";import type { DomainProvisioningChanges, DomainProvisioningResult } from "@/lib/domains/types";+import { removeMxRecords } from "@/lib/domains/mx-records";+import { rollbackDomainProvisioning } from "@/lib/domains/rollback";/** Node/Docker has no Email Worker; a catch-all PUT to one 404s (CF 2016). */export function shouldBindEmailCatchAllToWorker(@@ -34,7 +36,7 @@ export function isManualZone(zoneId: string | null | undefined): boolean {export async function provisionDomainOnCloudflare(env: CloudflareEnv,hostname: string,- options?: { enableRouting?: boolean; enableSending?: boolean },+ options?: { enableRouting?: boolean; enableSending?: boolean; replaceMxRecords?: boolean },): Promise<DomainProvisioningResult> {const normalized = hostname.toLowerCase().trim();if (!hasCloudflareCredentials(env)) {@@ -48,7 +50,7 @@ export async function provisionDomainOnCloudflare(sendingEnabled: false,sendingSubdomainTag: null,routingStatus: "manual",- changes: { zoneId: MANUAL_ZONE_ID, enabledEmailRouting: false, createdSendingSubdomainTag: null, previousCatchAll: null, createdAddressRules: [] },+ changes: { zoneId: MANUAL_ZONE_ID, enabledEmailRouting: false, createdSendingSubdomainTag: null, previousCatchAll: null, createdAddressRules: [], deletedMxRecords: [] },};}const zone = await findZoneByHostname(env, normalized);@@ -71,45 +73,54 @@ export async function provisionDomainOnCloudflare(createdSendingSubdomainTag: null,previousCatchAll: null,createdAddressRules: [],+ deletedMxRecords: [],};- if (enableRouting) {- // Record the zone's prior state before changing it: rolling back must only- // undo what this call did, never Email Routing the account already had.- // If the state cannot be read, assume it was already on — leaving an orphan- // behind is far cheaper than disabling a zone someone else's mail depends on.- let routingWasEnabled = true;- try {- const settings = await getEmailRoutingSettings(env, zone.id);- routingWasEnabled = settings.enabled === true;- } catch {- // Keep the fail-safe default.- }- // The catch-all is a singleton and the PUT below overwrites it, so keep a copy.- changes.previousCatchAll = routingWasEnabled ? await getEmailRoutingCatchAll(env, zone.id) : null;+ try {+ if (enableRouting) {+ // Record the zone's prior state before changing it: rolling back must only+ // undo what this call did, never Email Routing the account already had.+ // If the state cannot be read, assume it was already on — leaving an orphan+ // behind is far cheaper than disabling a zone someone else's mail depends on.+ let routingWasEnabled = true;+ try {+ const settings = await getEmailRoutingSettings(env, zone.id);+ routingWasEnabled = settings.enabled === true;+ } catch {+ // Keep the fail-safe default.+ }+ // The catch-all is a singleton and the PUT below overwrites it, so keep a copy.+ changes.previousCatchAll = routingWasEnabled ? await getEmailRoutingCatchAll(env, zone.id) : null;- const routingName = isZoneApex(normalized, zone.name) ? undefined : normalized;- const routing = await enableEmailRouting(env, zone.id, routingName);- changes.enabledEmailRouting = !routingWasEnabled;- routingEnabled = routing.enabled ?? true;- routingStatus = routing.status;- if (shouldBindEmailCatchAllToWorker(env)) {- await ensureEmailRoutingCatchAllToWorker(env, zone.id);+ const routingName = isZoneApex(normalized, zone.name) ? undefined : normalized;+ if (options?.replaceMxRecords) {+ await removeMxRecords(env, zone.id, routingName ?? zone.name, changes.deletedMxRecords);+ }+ const routing = await enableEmailRouting(env, zone.id, routingName);+ changes.enabledEmailRouting = !routingWasEnabled;+ routingEnabled = routing.enabled ?? true;+ routingStatus = routing.status;+ if (shouldBindEmailCatchAllToWorker(env)) {+ await ensureEmailRoutingCatchAllToWorker(env, zone.id);+ }}- }- if (enableSending) {- const subs = await listSendingSubdomains(env, zone.id);- const existingSub = subs.find((s) => s.name === normalized);- if (existingSub) {- sendingSubdomainTag = existingSub.tag;- sendingEnabled = existingSub.enabled;- } else {- const created = await createSendingSubdomain(env, zone.id, normalized);- sendingSubdomainTag = created.tag;- sendingEnabled = created.enabled;- changes.createdSendingSubdomainTag = created.tag;+ if (enableSending) {+ const subs = await listSendingSubdomains(env, zone.id);+ const existingSub = subs.find((s) => s.name === normalized);+ if (existingSub) {+ sendingSubdomainTag = existingSub.tag;+ sendingEnabled = existingSub.enabled;+ } else {+ const created = await createSendingSubdomain(env, zone.id, normalized);+ sendingSubdomainTag = created.tag;+ sendingEnabled = created.enabled;+ changes.createdSendingSubdomainTag = created.tag;+ }}+ } catch (error) {+ await rollbackDomainProvisioning(env, changes);+ throw error;}return {diff --git a/src/lib/domains/rollback.ts b/src/lib/domains/rollback.tsindex 4554e18..058be1e 100644--- a/src/lib/domains/rollback.ts+++ b/src/lib/domains/rollback.ts@@ -4,6 +4,7 @@ import {disableEmailRouting,} from "@/lib/cloudflare-api";import { restoreEmailRoutingCatchAll } from "@/lib/domains/catch-all-routing";+import { restoreMxRecords } from "@/lib/domains/mx-records";import type { DomainProvisioningChanges } from "@/lib/domains/types";async function attempt(label: string, run: () => Promise<unknown>): Promise<void> {@@ -53,4 +54,8 @@ export async function rollbackDomainProvisioning(if (changes.enabledEmailRouting) {await attempt("disableEmailRouting", () => disableEmailRouting(env, zoneId));}++ if (changes.deletedMxRecords.length > 0) {+ await attempt("restoreMxRecords", () => restoreMxRecords(env, zoneId, changes.deletedMxRecords));+ }}diff --git a/src/lib/domains/service.ts b/src/lib/domains/service.tsindex bae1006..9da955a 100644--- a/src/lib/domains/service.ts+++ b/src/lib/domains/service.ts@@ -34,7 +34,7 @@ export async function addDomainForUser(env: CloudflareEnv,userId: string,hostname: string,- options?: { enableRouting?: boolean; enableSending?: boolean },+ options?: { enableRouting?: boolean; enableSending?: boolean; replaceMxRecords?: boolean },): Promise<{domain: typeof domains.$inferSelect;dns: DomainDnsView;@@ -102,8 +102,19 @@ export async function addDomainForUser(}// Read the DNS view outside the rollback scope: the domain is fully set up by- // now, so a failed status read must not tear it back down.- const dns = await getDomainDns(env, domain);+ // now, so a failed status read must not tear it back down or make registration+ // delete the account that now owns the completed Cloudflare configuration.+ let dns: DomainDnsView;+ try {+ dns = await getDomainDns(env, domain);+ } catch (error) {+ console.warn("addDomainForUser: failed to read DNS status after provisioning", error);+ dns = {+ routing: { records: [], missing: [], status: provisioned.routingStatus },+ sending: [],+ sendingEnabled: provisioned.sendingEnabled,+ };+ }return { domain, dns, changes: provisioned.changes };}diff --git a/src/lib/domains/types.d.ts b/src/lib/domains/types.d.tsindex 9e3daae..a332c03 100644--- a/src/lib/domains/types.d.ts+++ b/src/lib/domains/types.d.ts@@ -1,5 +1,5 @@import type { domains } from "@/db/schema";-import type { CfEmailRoutingRule } from "@/lib/cloudflare-api.types";+import type { CfDnsRecord, CfEmailRoutingRule } from "@/lib/cloudflare-api.types";/*** Exactly what one provisioning attempt changed on the Cloudflare zone, so a@@ -18,6 +18,14 @@ export type DomainProvisioningChanges = {previousCatchAll: CfEmailRoutingRule | null;/** Addresses this attempt pointed at the Worker, filled in as they are created. */createdAddressRules: string[];+ /** MX records removed with the user's confirmation, retained so rollback can restore them. */+ deletedMxRecords: CfDnsRecord[];+};++export type DomainProvisioningError = {+ message: string;+ code?: "MX_RECORDS_CONFLICT";+ status: number;};export type DomainProvisioningResult = {diff --git a/src/lib/validators.ts b/src/lib/validators.tsindex 23da7c8..03d41c7 100644--- a/src/lib/validators.ts+++ b/src/lib/validators.ts@@ -51,6 +51,7 @@ export const registerSchema = z.object({export const firstRunRegisterSchema = z.object({domain: z.string().min(3),enableSending: z.boolean().optional(),+ replaceMxRecords: z.boolean().optional(),username: z.string().min(1).max(64).regex(/^[a-zA-Z0-9._%+-]+$/),password: z.string().min(8),resetEmail: z.string().email(),@@ -70,6 +71,7 @@ export const addDomainSchema = z.object({hostname: z.string().min(3),enableRouting: z.boolean().optional(),enableSending: z.boolean().optional(),+ replaceMxRecords: z.boolean().optional(),});export const loginSchema = z.object({