Email for professionals and teams
fix(domains): roll back only the Cloudflare config a failed setup created (#20)
Oday Bakkourfe40039664b8
diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.tsindex 8457f4a..83261f9 100644--- a/src/app/api/auth/register/route.ts+++ b/src/app/api/auth/register/route.ts@@ -8,7 +8,9 @@ import { hasAdminAccount } from "@/lib/auth/setup";import { createSession, SESSION_COOKIE } from "@/lib/auth/session";import { newId } from "@/lib/ids";import { firstRunRegisterSchema } from "@/lib/validators";-import { addDomainForUser, listUserDomains, removeDomainForUser } from "@/lib/domains/service";+import { addDomainForUser } from "@/lib/domains/service";+import { rollbackDomainProvisioning } from "@/lib/domains/rollback";+import type { DomainProvisioningChanges } from "@/lib/domains/types";import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";import { readJsonBody } from "@/lib/http/request";@@ -58,12 +60,21 @@ export async function POST(request: Request) {role: "admin",});+ // Tracks what the attempt changed on the Cloudflare zone so a failure can undo+ // precisely that. The DB is not a reliable source for this: the same errors that+ // abort registration (an unmigrated schema, a dead D1 binding) also stop the+ // domain row from ever being written, which is exactly when the orphaned zone+ // config would go unnoticed.+ let changes: DomainProvisioningChanges | null = null;try {- const { domain } = await addDomainForUser(env, userId, domainName, {+ const added = await addDomainForUser(env, userId, domainName, {enableRouting: true,enableSending: true,});+ const domain = added.domain;+ changes = added.changes;await ensureEmailRoutingRuleToWorker(env, domain.zoneId, email);+ changes.createdAddressRules.push(email);const mailboxId = newId("mbx");await db.insert(mailboxes).values({id: mailboxId,@@ -74,13 +85,13 @@ export async function POST(request: Request) {});await ensureMailboxDomainRouting(env, db, { id: mailboxId, domainId: domain.id, localPart: username, useAllDomains: true });} catch (err) {+ if (changes) await rollbackDomainProvisioning(env, changes);try {- const [domain] = await listUserDomains(env, userId);- if (domain) await removeDomainForUser(env, userId, domain.id);+ // The domain row cascades with the user.+ await db.delete(users).where(eq(users.id, userId));} catch (cleanupError) {- console.warn("Failed to roll back domain after registration failure", cleanupError);+ console.warn("Failed to remove the partial user after registration failure", cleanupError);}- await db.delete(users).where(eq(users.id, userId));const message = err instanceof Error ? err.message : "Domain setup failed";return NextResponse.json({ error: message }, { status: 502 });}diff --git a/src/lib/domains/catch-all-routing.ts b/src/lib/domains/catch-all-routing.tsindex 7b166e9..1665c77 100644--- a/src/lib/domains/catch-all-routing.ts+++ b/src/lib/domains/catch-all-routing.ts@@ -2,6 +2,21 @@ import { cfRequest } from "@/lib/cloudflare-api";import type { CfEmailRoutingRule } from "@/lib/cloudflare-api.types";import { getEmailWorkerName } from "@/lib/cloudflare-api-utils";+export async function getEmailRoutingCatchAll(+ env: CloudflareEnv,+ zoneId: string,+): Promise<CfEmailRoutingRule | null> {+ try {+ return await cfRequest<CfEmailRoutingRule>(+ env,+ `/zones/${zoneId}/email/routing/rules/catch_all`,+ );+ } catch {+ // A zone without Email Routing has no catch-all to read; treat it as absent.+ return null;+ }+}+export async function ensureEmailRoutingCatchAllToWorker(env: CloudflareEnv,zoneId: string,@@ -21,3 +36,31 @@ export async function ensureEmailRoutingCatchAllToWorker(},);}++/**+ * Put back a catch-all captured before `ensureEmailRoutingCatchAllToWorker`+ * overwrote it. The catch-all is a singleton per zone, so it cannot be deleted —+ * restoring means writing the previous rule back, or falling back to+ * Cloudflare's own default (a disabled drop) when the zone never had one.+ */+export async function restoreEmailRoutingCatchAll(+ env: CloudflareEnv,+ zoneId: string,+ previous: CfEmailRoutingRule | null,+): Promise<void> {+ const actions = previous?.actions?.length ? previous.actions : [{ type: "drop" as const }];+ const matchers = previous?.matchers?.length ? previous.matchers : [{ type: "all" as const }];+ await cfRequest<CfEmailRoutingRule>(+ env,+ `/zones/${zoneId}/email/routing/rules/catch_all`,+ {+ method: "PUT",+ body: JSON.stringify({+ actions,+ enabled: previous?.enabled ?? false,+ matchers,+ ...(previous?.name ? { name: previous.name } : {}),+ }),+ },+ );+}diff --git a/src/lib/domains/provision.ts b/src/lib/domains/provision.tsindex 429bcb4..7dc6430 100644--- a/src/lib/domains/provision.ts+++ b/src/lib/domains/provision.ts@@ -2,11 +2,15 @@ import {createSendingSubdomain,enableEmailRouting,findZoneByHostname,+ getEmailRoutingSettings,listSendingSubdomains,} from "@/lib/cloudflare-api";-import { ensureEmailRoutingCatchAllToWorker } from "@/lib/domains/catch-all-routing";+import {+ ensureEmailRoutingCatchAllToWorker,+ getEmailRoutingCatchAll,+} from "@/lib/domains/catch-all-routing";import { isZoneApex } from "@/lib/domains/utils";-import type { DomainProvisioningResult } from "@/lib/domains/types";+import type { DomainProvisioningChanges, DomainProvisioningResult } from "@/lib/domains/types";export async function provisionDomainOnCloudflare(env: CloudflareEnv,@@ -28,10 +32,32 @@ export async function provisionDomainOnCloudflare(let sendingEnabled = false;let sendingSubdomainTag: string | null = null;let routingStatus: string | undefined;+ const changes: DomainProvisioningChanges = {+ zoneId: zone.id,+ enabledEmailRouting: false,+ createdSendingSubdomainTag: null,+ previousCatchAll: null,+ createdAddressRules: [],+ };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;await ensureEmailRoutingCatchAllToWorker(env, zone.id);@@ -50,6 +76,7 @@ export async function provisionDomainOnCloudflare(const created = await createSendingSubdomain(env, zone.id, normalized);sendingSubdomainTag = created.tag;sendingEnabled = created.enabled;+ changes.createdSendingSubdomainTag = created.tag;}}}@@ -61,5 +88,6 @@ export async function provisionDomainOnCloudflare(sendingEnabled,sendingSubdomainTag,routingStatus,+ changes,};}diff --git a/src/lib/domains/rollback.ts b/src/lib/domains/rollback.tsnew file mode 100644index 0000000..4554e18--- /dev/null+++ b/src/lib/domains/rollback.ts@@ -0,0 +1,56 @@+import {+ deleteEmailRoutingRuleForAddress,+ deleteSendingSubdomain,+ disableEmailRouting,+} from "@/lib/cloudflare-api";+import { restoreEmailRoutingCatchAll } from "@/lib/domains/catch-all-routing";+import type { DomainProvisioningChanges } from "@/lib/domains/types";++async function attempt(label: string, run: () => Promise<unknown>): Promise<void> {+ try {+ await run();+ } catch (err) {+ // A rollback runs while another error is already on its way to the caller,+ // so a failure here must be logged, never thrown — it would mask the cause.+ console.warn(`rollbackDomainProvisioning: ${label}`, err);+ }+}++/**+ * Undo exactly what a provisioning attempt changed on the zone, so a failed+ * signup or domain add leaves the Cloudflare account as it was rather than+ * stranding Email Routing and a sending subdomain with nothing referencing them.+ *+ * Anything the attempt merely reused is deliberately left alone.+ */+export async function rollbackDomainProvisioning(+ env: CloudflareEnv,+ changes: DomainProvisioningChanges,+): Promise<void> {+ const { zoneId } = changes;++ for (const address of changes.createdAddressRules) {+ await attempt(`deleteEmailRoutingRuleForAddress ${address}`, () =>+ deleteEmailRoutingRuleForAddress(env, zoneId, address),+ );+ }++ if (changes.createdSendingSubdomainTag) {+ await attempt("deleteSendingSubdomain", () =>+ deleteSendingSubdomain(env, zoneId, changes.createdSendingSubdomainTag!),+ );+ }++ // Restore before disabling: Cloudflare keeps the routing config around when+ // Email Routing is switched off, so leaving the Worker catch-all in place would+ // quietly resurrect it the next time someone re-enables routing on the zone.+ if (changes.previousCatchAll || changes.enabledEmailRouting) {+ await attempt("restoreEmailRoutingCatchAll", () =>+ restoreEmailRoutingCatchAll(env, zoneId, changes.previousCatchAll),+ );+ }++ if (changes.enabledEmailRouting) {+ await attempt("disableEmailRouting", () => disableEmailRouting(env, zoneId));+ }+}diff --git a/src/lib/domains/service.ts b/src/lib/domains/service.tsindex 026ac24..40497ba 100644--- a/src/lib/domains/service.ts+++ b/src/lib/domains/service.ts@@ -14,6 +14,8 @@ import {} from "@/lib/cloudflare-api";import { deleteEmailRoutingRulesForDomain } from "@/lib/domains/cloudflare-cleanup";import { provisionDomainOnCloudflare } from "@/lib/domains/provision";+import { rollbackDomainProvisioning } from "@/lib/domains/rollback";+import type { DomainProvisioningChanges } from "@/lib/domains/types";import { findSendingSubdomain } from "@/lib/domains/sending-status";export type DomainDnsView = {@@ -32,49 +34,75 @@ export async function addDomainForUser(userId: string,hostname: string,options?: { enableRouting?: boolean; enableSending?: boolean },-): Promise<{ domain: typeof domains.$inferSelect; dns: DomainDnsView }> {+): Promise<{+ domain: typeof domains.$inferSelect;+ dns: DomainDnsView;+ changes: DomainProvisioningChanges;+}> {const provisioned = await provisionDomainOnCloudflare(env, hostname, options);-const db = getDb(env);- const [existing] = await db.select().from(domains).where(eq(domains.hostname, provisioned.hostname)).limit(1);- if (existing && existing.userId !== userId) {- throw new Error("Domain is already registered");- }+ let insertedDomainId: string | null = null;+ let domain: typeof domains.$inferSelect;- const domainId = existing?.id ?? newId("dom");- const values = {- id: domainId,- userId,- hostname: provisioned.hostname,- zoneId: provisioned.zone.id,- status: provisioned.routingEnabled || provisioned.sendingEnabled ? ("active" as const) : ("pending" as const),- routingStatus: provisioned.routingStatus ?? null,- sendingSubdomainTag: provisioned.sendingSubdomainTag,- sendingEnabled: provisioned.sendingEnabled,- routingEnabled: provisioned.routingEnabled,- };+ try {+ const [existing] = await db.select().from(domains).where(eq(domains.hostname, provisioned.hostname)).limit(1);+ if (existing && existing.userId !== userId) {+ throw new Error("Domain is already registered");+ }- if (existing) {- await db.update(domains).set(values).where(eq(domains.id, domainId));- } else {- await db.insert(domains).values(values);- }+ const domainId = existing?.id ?? newId("dom");+ const values = {+ id: domainId,+ userId,+ hostname: provisioned.hostname,+ zoneId: provisioned.zone.id,+ status: provisioned.routingEnabled || provisioned.sendingEnabled ? ("active" as const) : ("pending" as const),+ routingStatus: provisioned.routingStatus ?? null,+ sendingSubdomainTag: provisioned.sendingSubdomainTag,+ sendingEnabled: provisioned.sendingEnabled,+ routingEnabled: provisioned.routingEnabled,+ };- const aliasMailboxes = 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, userId), eq(mailboxes.useAllDomains, true)));- const routingResults = await Promise.allSettled(- aliasMailboxes.map((mailbox) => ensureMailboxDomainRouting(env, db, mailbox)),- );- for (const result of routingResults) {- if (result.status === "rejected") console.warn("ensureMailboxDomainRouting", result.reason);+ if (existing) {+ await db.update(domains).set(values).where(eq(domains.id, domainId));+ } else {+ await db.insert(domains).values(values);+ insertedDomainId = domainId;+ }++ const aliasMailboxes = 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, userId), eq(mailboxes.useAllDomains, true)));+ const routingResults = await Promise.allSettled(+ aliasMailboxes.map((mailbox) => ensureMailboxDomainRouting(env, db, mailbox)),+ );+ for (const result of routingResults) {+ if (result.status === "rejected") console.warn("ensureMailboxDomainRouting", result.reason);+ }++ const [row] = await db.select().from(domains).where(eq(domains.id, domainId)).limit(1);+ domain = row!;+ } catch (err) {+ // The zone was already provisioned above. Anything that fails after that —+ // a hostname owned by another user, an unmigrated D1 schema — would otherwise+ // strand Email Routing and the sending subdomain with nothing referencing them.+ await rollbackDomainProvisioning(env, provisioned.changes);+ if (insertedDomainId) {+ try {+ await db.delete(domains).where(eq(domains.id, insertedDomainId));+ } catch (cleanupError) {+ console.warn("addDomainForUser: failed to remove partial domain row", cleanupError);+ }+ }+ throw err;}- const [domain] = await db.select().from(domains).where(eq(domains.id, domainId)).limit(1);- const dns = await getDomainDns(env, domain!);- return { domain: domain!, dns };+ // 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);+ return { domain, dns, changes: provisioned.changes };}export async function getDomainDns(diff --git a/src/lib/domains/types.d.ts b/src/lib/domains/types.d.tsindex 2145d4d..2679fdd 100644--- a/src/lib/domains/types.d.ts+++ b/src/lib/domains/types.d.ts@@ -1,4 +1,24 @@import type { domains } from "@/db/schema";+import type { CfEmailRoutingRule } from "@/lib/cloudflare-api.types";++/**+ * Exactly what one provisioning attempt changed on the Cloudflare zone, so a+ * failure further along can undo its own work and nothing else. Provisioning is+ * idempotent — it happily reuses Email Routing or a sending subdomain the zone+ * already had — and tearing those down would leave the account worse off than+ * the orphaned config the rollback exists to prevent.+ */+export type DomainProvisioningChanges = {+ zoneId: string;+ /** Email Routing was off before this attempt and this attempt turned it on. */+ enabledEmailRouting: boolean;+ /** Tag of a sending subdomain this attempt created; null when one already existed. */+ createdSendingSubdomainTag: string | null;+ /** The zone's catch-all rule as it stood before this attempt overwrote it. */+ previousCatchAll: CfEmailRoutingRule | null;+ /** Addresses this attempt pointed at the Worker, filled in as they are created. */+ createdAddressRules: string[];+};export type DomainProvisioningResult = {hostname: string;@@ -7,6 +27,7 @@ export type DomainProvisioningResult = {sendingEnabled: boolean;sendingSubdomainTag: string | null;routingStatus?: string;+ changes: DomainProvisioningChanges;};export type DomainRow = typeof domains.$inferSelect;