Skip to content

Email for professionals and teams

workaround for 401 cf error

Hieu Nguyen (Jack)a0efd37c1078
diff --git a/src/app/(admin)/domains/api.ts b/src/app/(admin)/domains/api.ts
index 85289c7..6e8305c 100644
--- a/src/app/(admin)/domains/api.ts
+++ b/src/app/(admin)/domains/api.ts
@@ -16,6 +16,13 @@ export const postJson = <T,>(url: string, method: string, body: unknown) => requ
type SetupResponse = { error?: string; code?: string; records?: { content: string; priority: number }[] };
+/** Whether a response is a 409 MX_CONFLICT the user agreed to resolve by replacing the listed MX records. */
+export function confirmMxReplacement(response: Response, data: SetupResponse): boolean {
+ if (response.status !== 409 || data.code !== "MX_CONFLICT") return false;
+ const list = (data.records ?? []).map((record) => ` ${record.priority} ${record.content}`).join("\n");
+ return window.confirm(`${data.error}\n\n${list}\n\nReplace them? Mail will stop going to the current service.`);
+}
+
/**
* 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.
@@ -32,8 +39,7 @@ export async function runReceivingSetup(domainId: string, provider: "cloudflare"
};
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;
+ if (!confirmMxReplacement(response, data)) return false;
({ response, data } = await call(true));
}
if (!response.ok) throw new Error(data.error ?? "Setup failed");
diff --git a/src/app/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
index dedcba3..92ebff5 100644
--- a/src/app/(admin)/domains/page.tsx
+++ b/src/app/(admin)/domains/page.tsx
@@ -21,6 +21,7 @@ import type { DnsAuthRecord, DnsStatusSummary, Domain, DomainDnsCache, DomainDns
import DomainItemCard from "./DomainItemCard";
import { SectionRowSkeleton } from "@/components/page-skeletons";
import { checkDomain } from "./utils";
+import { confirmMxReplacement } from "./api";
export default function DomainsPage() {
const qc = useQueryClient();
@@ -158,12 +159,17 @@ export default function DomainsPage() {
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 };
+ const put = async (replaceMx: boolean) => {
+ const res = await authFetch(`/api/domains/${id}/sending`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ provider, replaceMx }),
+ });
+ return { res, json: (await res.json()) as { warning?: string; error?: string; code?: string; records?: { content: string; priority: number }[] } };
+ };
+ let { res, json } = await put(false);
+ // Cloudflare sending refuses while another service's MX records exist.
+ if (confirmMxReplacement(res, json)) ({ res, json } = await put(true));
if (!res.ok) throw new Error(json.error ?? "Failed to change sending provider");
if (json.warning) setSendingMessage(json.warning);
await loadDns(id);
@@ -213,16 +219,25 @@ export default function DomainsPage() {
setSetupRecord(record);
setSetupMessage(null);
try {
- const res = await authFetch(`/api/domains/${dnsView.domain.id}/dns/setup`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ record }),
- });
- const json = (await res.json()) as {
- domain?: Domain;
- dns?: DomainDnsView;
- error?: string;
+ const post = async (replaceMx: boolean) => {
+ const res = await authFetch(`/api/domains/${dnsView.domain.id}/dns/setup`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ record, replaceMx }),
+ });
+ return {
+ res,
+ json: (await res.json()) as {
+ domain?: Domain;
+ dns?: DomainDnsView;
+ error?: string;
+ code?: string;
+ records?: { content: string; priority: number }[];
+ },
+ };
};
+ let { res, json } = await post(false);
+ if (confirmMxReplacement(res, json)) ({ res, json } = await post(true));
if (!res.ok) throw new Error(json.error ?? "Failed to set up DNS record");
if (json.domain && json.dns) {
const updatedView = { domain: json.domain, dns: json.dns };
diff --git a/src/app/api/domains/[id]/dns/setup/route.ts b/src/app/api/domains/[id]/dns/setup/route.ts
index 11c6fef..789a468 100644
--- a/src/app/api/domains/[id]/dns/setup/route.ts
+++ b/src/app/api/domains/[id]/dns/setup/route.ts
@@ -9,6 +9,7 @@ import { getDomainForUser } from "@/lib/domains/service";
import { getDomainDnsView } from "@/lib/domains/dns-view";
import type { DnsAuthRecord } from "@/lib/domains/dns-audit";
import { setupDomainDnsRecord } from "@/lib/domains/dns-setup";
+import { MxConflictError } from "@/lib/domains/receiving-dns";
import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
type Params = { params: Promise<{ id: string }> };
@@ -24,14 +25,14 @@ export async function POST(request: Request, { params }: Params) {
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 { record?: string };
+ const body = (await request.json().catch(() => ({}))) as { record?: string; replaceMx?: boolean };
const record = body.record as DnsAuthRecord | undefined;
if (!record || !DNS_RECORDS.includes(record)) {
return NextResponse.json({ error: "Unknown DNS record" }, { status: 400 });
}
try {
- await setupDomainDnsRecord(env, domain, record);
+ await setupDomainDnsRecord(env, domain, record, { replaceMx: body.replaceMx === true });
const dns = await getDomainDnsView(env, domain);
const [updated] = await getDb(env)
.select()
@@ -43,6 +44,8 @@ export async function POST(request: Request, { params }: Params) {
dns,
});
} catch (err) {
+ // 409 MX_CONFLICT asks the caller to confirm and retry with replaceMx.
+ if (err instanceof MxConflictError) return NextResponse.json({ error: err.message, code: err.code, records: err.records }, { status: 409 });
const message = err instanceof Error ? err.message : "Failed to set up DNS record";
return NextResponse.json({ error: message }, { status: 500 });
}
diff --git a/src/app/api/domains/[id]/sending/route.ts b/src/app/api/domains/[id]/sending/route.ts
index 18f9d38..8dff0ce 100644
--- a/src/app/api/domains/[id]/sending/route.ts
+++ b/src/app/api/domains/[id]/sending/route.ts
@@ -15,12 +15,17 @@ 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";
+import { MxConflictError } from "@/lib/domains/receiving-dns";
type Params = { params: Promise<{ id: string }> };
-const schema = z.object({ provider: z.enum(["none", "cloudflare", "resend", "ses"]) });
+const schema = z.object({ provider: z.enum(["none", "cloudflare", "resend", "ses"]), replaceMx: z.boolean().optional() });
-/** Chooses what sends mail for this domain. Receiving is unaffected. */
+/**
+ * Chooses what sends mail for this domain. Receiving is unaffected, except that
+ * Cloudflare sending refuses while another service's MX records exist: that is a
+ * 409 MX_CONFLICT (the choice is still saved) until the caller retries with replaceMx.
+ */
export async function PUT(request: Request, { params }: Params) {
const { id } = await params;
const env = getEnv();
@@ -31,7 +36,7 @@ export async function PUT(request: Request, { params }: Params) {
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;
+ const { provider, replaceMx } = parsed.data;
await getDb(env)
.update(domains)
@@ -42,8 +47,11 @@ export async function PUT(request: Request, { params }: Params) {
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"; }
+ try { await setupDomainDnsRecord(env, { ...domain, sendingProvider: provider }, "dkim", { replaceMx }); }
+ catch (error) {
+ if (error instanceof MxConflictError) return NextResponse.json({ error: error.message, code: error.code, records: error.records }, { status: 409 });
+ 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" } });
diff --git a/src/app/api/v1/domains/[id]/dns/setup/route.ts b/src/app/api/v1/domains/[id]/dns/setup/route.ts
index 4d2419b..9c0492e 100644
--- a/src/app/api/v1/domains/[id]/dns/setup/route.ts
+++ b/src/app/api/v1/domains/[id]/dns/setup/route.ts
@@ -8,6 +8,7 @@ import { getDomainForUser } from "@/lib/domains/service";
import { getDomainDnsView } from "@/lib/domains/dns-view";
import type { DnsAuthRecord } from "@/lib/domains/dns-audit";
import { setupDomainDnsRecord } from "@/lib/domains/dns-setup";
+import { MxConflictError } from "@/lib/domains/receiving-dns";
type Params = { params: Promise<{ id: string }> };
@@ -24,14 +25,14 @@ export async function POST(request: Request, { params }: Params) {
const domain = await getDomainForUser(env, auth.userId, id);
if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
- const body = (await request.json().catch(() => ({}))) as { record?: string };
+ const body = (await request.json().catch(() => ({}))) as { record?: string; replaceMx?: boolean };
const record = body.record as DnsAuthRecord | undefined;
if (!record || !DNS_RECORDS.includes(record)) {
return NextResponse.json({ error: "Unknown DNS record" }, { status: 400 });
}
try {
- await setupDomainDnsRecord(env, domain, record);
+ await setupDomainDnsRecord(env, domain, record, { replaceMx: body.replaceMx === true });
const dns = await getDomainDnsView(env, domain);
const [updated] = await getDb(env)
.select()
@@ -43,6 +44,8 @@ export async function POST(request: Request, { params }: Params) {
dns,
});
} catch (err) {
+ // 409 MX_CONFLICT asks the caller to confirm and retry with replaceMx.
+ if (err instanceof MxConflictError) return NextResponse.json({ error: err.message, code: err.code, records: err.records }, { status: 409 });
const message = err instanceof Error ? err.message : "Failed to set up DNS record";
return NextResponse.json({ error: message }, { status: 500 });
}
diff --git a/src/lib/cloudflare-api-utils.ts b/src/lib/cloudflare-api-utils.ts
index 7a570cd..fe454f1 100644
--- a/src/lib/cloudflare-api-utils.ts
+++ b/src/lib/cloudflare-api-utils.ts
@@ -45,7 +45,12 @@ export function formatCloudflareError(path: string, status: number, statusText:
return `Cloudflare API ${status} on ${path}: ${message}`;
}
-export function getCloudflareAuthHint(errors: CfApiError[]) {
+export function getCloudflareAuthHint(errors: CfApiError[], path = "") {
+ // Cloudflare answers a sending-subdomain create with 401/2036 when the hostname
+ // has another service's MX records, so a valid token is not the likely cause.
+ if (path.includes("/email/sending/") && errors.some((error) => error.code === 2036)) {
+ return " If the token has Email Sending permissions, check the domain for MX records pointing at another mail service; Cloudflare refuses sending setup until they are removed.";
+ }
const hasAuthError = errors.some(
(error) =>
error.code === 10000 ||
diff --git a/src/lib/cloudflare-api.ts b/src/lib/cloudflare-api.ts
index 892f148..a401672 100644
--- a/src/lib/cloudflare-api.ts
+++ b/src/lib/cloudflare-api.ts
@@ -34,7 +34,7 @@ export async function cfRequest<T>(
if (!json.success) {
throw new CloudflareApiError(
- `${formatCloudflareError(path, res.status, res.statusText, json.errors ?? [])}${getCloudflareAuthHint(json.errors ?? [])}`,
+ `${formatCloudflareError(path, res.status, res.statusText, json.errors ?? [])}${getCloudflareAuthHint(json.errors ?? [], path)}`,
res.status,
path,
json.errors ?? [],
diff --git a/src/lib/domains/dns-setup.ts b/src/lib/domains/dns-setup.ts
index 0a745dd..b966c58 100644
--- a/src/lib/domains/dns-setup.ts
+++ b/src/lib/domains/dns-setup.ts
@@ -1,12 +1,7 @@
import { eq } from "drizzle-orm";
import { getDb } from "@/db";
import { domains } from "@/db/schema";
-import {
- createSendingSubdomain,
- enableEmailRouting,
- getZone,
- listSendingSubdomains,
-} from "@/lib/cloudflare-api";
+import { enableEmailRouting, getZone } from "@/lib/cloudflare-api";
import { createDnsRecord, listDnsRecords } from "@/lib/cloudflare-dns";
import { ensureEmailRoutingCatchAllToWorker } from "@/lib/domains/catch-all-routing";
import type { DnsAuthRecord } from "@/lib/domains/dns-audit";
@@ -14,7 +9,7 @@ import {
isManualZone,
shouldBindEmailCatchAllToWorker,
} from "@/lib/domains/provision";
-import { findSendingSubdomain } from "@/lib/domains/sending-status";
+import { ensureSendingSubdomain } from "@/lib/domains/sending-subdomain";
import type { DomainRow } from "@/lib/domains/types";
import { isZoneApex } from "@/lib/domains/utils";
@@ -23,12 +18,14 @@ import { isZoneApex } from "@/lib/domains/utils";
* mechanisms domain creation uses: MX/SPF come from enabling Email Routing,
* DKIM from a sending subdomain, and DMARC is a hand-written TXT since
* Cloudflare does not create one for the domain. Idempotent, so a click on a
- * record that already exists is a no-op.
+ * record that already exists is a no-op. DKIM throws MxConflictError when another
+ * service's MX records block the sending subdomain, unless `replaceMx` is set.
*/
export async function setupDomainDnsRecord(
env: CloudflareEnv,
domain: DomainRow,
record: DnsAuthRecord,
+ options: { replaceMx?: boolean } = {},
): Promise<void> {
if (isManualZone(domain.zoneId)) {
throw new Error("DNS for this domain is managed manually");
@@ -56,10 +53,9 @@ export async function setupDomainDnsRecord(
// The stored tag can be stale or empty even though the subdomain exists
// on Cloudflare, so reuse what is there instead of creating a duplicate
// (which Cloudflare rejects with "Subdomain already exists").
- const subdomains = await listSendingSubdomains(env, domain.zoneId);
- const subdomain =
- findSendingSubdomain(domain.hostname, subdomains) ??
- (await createSendingSubdomain(env, domain.zoneId, domain.hostname));
+ const { subdomain } = await ensureSendingSubdomain(env, domain.zoneId, domain.hostname, {
+ replaceMx: options.replaceMx,
+ });
await getDb(env)
.update(domains)
.set({
diff --git a/src/lib/domains/errors.ts b/src/lib/domains/errors.ts
index 092e7e3..59a3fe1 100644
--- a/src/lib/domains/errors.ts
+++ b/src/lib/domains/errors.ts
@@ -1,4 +1,5 @@
import { isCloudflareApiErrorCode } from "@/lib/cloudflare-api-error";
+import { MxConflictError } from "@/lib/domains/receiving-dns";
import type { DomainProvisioningError } from "@/lib/domains/types";
export function getDomainProvisioningError(
@@ -15,6 +16,10 @@ export function getDomainProvisioningError(
};
}
+ if (error instanceof MxConflictError) {
+ return { code: "MX_RECORDS_CONFLICT", message: error.message, 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.ts
index 7a497fe..c34532a 100644
--- a/src/lib/domains/mx-records.ts
+++ b/src/lib/domains/mx-records.ts
@@ -40,6 +40,16 @@ export async function removeMxRecords(
}
}
+/** MX records on `hostname` that point somewhere other than Cloudflare Email Routing. */
+export async function listConflictingMxRecords(
+ env: CloudflareEnv,
+ zoneId: string,
+ hostname: string,
+): Promise<CfDnsRecord[]> {
+ const records = await listMxRecords(env, zoneId, hostname);
+ return records.filter((record) => !isCloudflareEmailRoutingMx(record));
+}
+
export async function hasConflictingMxRecords(
env: CloudflareEnv,
zoneId: string,
diff --git a/src/lib/domains/provision.ts b/src/lib/domains/provision.ts
index 411c656..bb91d09 100644
--- a/src/lib/domains/provision.ts
+++ b/src/lib/domains/provision.ts
@@ -1,9 +1,7 @@
import {
- createSendingSubdomain,
enableEmailRouting,
findZoneByHostname,
getEmailRoutingSettings,
- listSendingSubdomains,
} from "@/lib/cloudflare-api";
import {
ensureEmailRoutingCatchAllToWorker,
@@ -14,6 +12,7 @@ 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";
+import { ensureSendingSubdomain } from "@/lib/domains/sending-subdomain";
/** Node/Docker has no Email Worker; a catch-all PUT to one 404s (CF 2016). */
export function shouldBindEmailCatchAllToWorker(
@@ -106,17 +105,15 @@ export async function provisionDomainOnCloudflare(
}
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;
- }
+ // Cloudflare refuses (401, code 2036) while another service's MX records
+ // are on the hostname; replacing them follows the same consent as routing.
+ const { subdomain, created } = await ensureSendingSubdomain(env, zone.id, normalized, {
+ replaceMx: options?.replaceMxRecords,
+ deletedMx: changes.deletedMxRecords,
+ });
+ sendingSubdomainTag = subdomain.tag;
+ sendingEnabled = subdomain.enabled;
+ if (created) changes.createdSendingSubdomainTag = subdomain.tag;
}
} catch (error) {
await rollbackDomainProvisioning(env, changes);
diff --git a/src/lib/domains/receiving-dns.ts b/src/lib/domains/receiving-dns.ts
index b2f3399..397b9de 100644
--- a/src/lib/domains/receiving-dns.ts
+++ b/src/lib/domains/receiving-dns.ts
@@ -6,8 +6,11 @@ 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.");
+ constructor(
+ readonly records: { content: string; priority: number }[],
+ message = "This domain has MX records for another mail service. Replace them to receive mail here.",
+ ) {
+ super(message);
}
}
diff --git a/src/lib/domains/sending-subdomain.ts b/src/lib/domains/sending-subdomain.ts
new file mode 100644
index 0000000..e872234
--- /dev/null
+++ b/src/lib/domains/sending-subdomain.ts
@@ -0,0 +1,53 @@
+import { createSendingSubdomain, listSendingSubdomains } from "@/lib/cloudflare-api";
+import { CloudflareApiError, isCloudflareApiErrorCode } from "@/lib/cloudflare-api-error";
+import type { CfDnsRecord, CfSendingSubdomain } from "@/lib/cloudflare-api.types";
+import { listConflictingMxRecords, removeMxRecords } from "@/lib/domains/mx-records";
+import { MxConflictError } from "@/lib/domains/receiving-dns";
+import { findSendingSubdomain } from "@/lib/domains/sending-status";
+
+/**
+ * What Cloudflare answers when a sending subdomain is created on a hostname
+ * whose MX records point at another mail service: a 401 "Unauthorized", which
+ * reads like a bad token even when the token has every permission it needs.
+ */
+const SENDING_UNAUTHORIZED_CODE = 2036;
+
+export const SENDING_MX_CONFLICT_MESSAGE =
+ "Cloudflare Email Sending cannot be enabled while this domain has MX records for another mail service. Replace them to send with Cloudflare.";
+
+function isSendingUnauthorized(error: unknown): boolean {
+ return isCloudflareApiErrorCode(error, SENDING_UNAUTHORIZED_CODE) || (error instanceof CloudflareApiError && error.status === 401);
+}
+
+/**
+ * Returns the zone's sending subdomain for `hostname`, creating it when missing.
+ * When Cloudflare refuses because of another service's MX records, this throws
+ * MxConflictError unless `replaceMx` is set, in which case it deletes them (pushing
+ * them onto `deletedMx` so a rollback can restore them) and tries again.
+ */
+export async function ensureSendingSubdomain(
+ env: CloudflareEnv,
+ zoneId: string,
+ hostname: string,
+ options: { replaceMx?: boolean; deletedMx?: CfDnsRecord[] } = {},
+): Promise<{ subdomain: CfSendingSubdomain; created: boolean }> {
+ const existing = findSendingSubdomain(hostname, await listSendingSubdomains(env, zoneId));
+ if (existing) return { subdomain: existing, created: false };
+
+ try {
+ return { subdomain: await createSendingSubdomain(env, zoneId, hostname), created: true };
+ } catch (error) {
+ if (!isSendingUnauthorized(error)) throw error;
+ const conflicting = await listConflictingMxRecords(env, zoneId, hostname).catch(() => []);
+ // No foreign MX: the 401 really is about credentials, so keep Cloudflare's error.
+ if (conflicting.length === 0) throw error;
+ if (!options.replaceMx) {
+ throw new MxConflictError(
+ conflicting.map((record) => ({ content: record.content ?? "", priority: record.priority ?? 0 })),
+ SENDING_MX_CONFLICT_MESSAGE,
+ );
+ }
+ await removeMxRecords(env, zoneId, hostname, options.deletedMx ?? []);
+ return { subdomain: await createSendingSubdomain(env, zoneId, hostname), created: true };
+ }
+}