Skip to content

Email for professionals and teams

Add switch setting for sending

Hieu Nguyen (Jack)c170b8a1e03f
diff --git a/docs/deployment.md b/docs/deployment.md
index 7f9bbb7..f288bc5 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -8,9 +8,9 @@ Set up Mailflare in three steps:
1. **Deploy the app:** use the Deploy to Cloudflare button, set the app name to `mailflare`, and provide the required `CF_TOKEN`.
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 sending, then helps you create the first mailbox.
+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**, **Email Sending Edit**, and **Email Routing Rules Write** permissions for every domain you plan to connect.
+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.
## Step 1: Deploy mailflare
@@ -26,7 +26,7 @@ The Worker name must remain `mailflare`. Before starting, create the required `C
Mailflare requires this runtime value:
-- `CF_TOKEN` — a scoped Cloudflare API token with **Zone Read**, **Email Routing Edit**, **Email Sending Edit**, and **Email Routing Rules Write** access for the domains you will connect. This is separate from the token Cloudflare uses to deploy the app.
+- `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.
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/drizzle/migrations/0025_add_domain_sending_intent.sql b/drizzle/migrations/0025_add_domain_sending_intent.sql
new file mode 100644
index 0000000..a7baa65
--- /dev/null
+++ b/drizzle/migrations/0025_add_domain_sending_intent.sql
@@ -0,0 +1,4 @@
+ALTER TABLE `domains` ADD `sending_requested` integer DEFAULT false NOT NULL;--> statement-breakpoint
+UPDATE `domains`
+SET `sending_requested` = true
+WHERE `sending_enabled` = true OR `sending_subdomain_tag` IS NOT NULL;
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index 683fc7e..402a416 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -176,6 +176,13 @@
"when": 1788604800001,
"tag": "0024_add_advanced_routing_and_webhook_retries",
"breakpoints": true
+ },
+ {
+ "idx": 25,
+ "version": "6",
+ "when": 1788796800000,
+ "tag": "0025_add_domain_sending_intent",
+ "breakpoints": true
}
]
}
diff --git a/package.json b/package.json
index 5e14ff1..e70ff4c 100644
--- a/package.json
+++ b/package.json
@@ -24,7 +24,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`, `Email Sending Edit`, and `Email Routing Rules Write` permissions for the zones you will connect. Paste only the token secret value, without `Bearer`."
+ "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`."
},
"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/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
index 4dcb44f..cc1ad74 100644
--- a/src/app/(admin)/domains/page.tsx
+++ b/src/app/(admin)/domains/page.tsx
@@ -13,16 +13,22 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import { Plus } from "lucide-react";
+import { Switch } from "@/components/ui/switch";
+import { CheckCircle2, LoaderCircle, Plus } from "lucide-react";
import { authFetch } from "@/lib/auth/client";
-import type { DnsStatusSummary, Domain, DomainDnsView } from "./types";
+import type { DnsStatusSummary, Domain, DomainDnsView, DomainPreflight } from "./types";
import DomainItemCard from "./DomainItemCard";
import DomainDnsDetails from "./DomainDnsDetails";
import { CardGridSkeleton } from "@/components/page-skeletons";
+import { checkDomain } from "./utils";
export default function DomainsPage() {
const qc = useQueryClient();
const [hostname, setHostname] = useState("");
+ const [domainCheck, setDomainCheck] = useState<DomainPreflight | null>(null);
+ const [domainChecking, setDomainChecking] = useState(false);
+ const [enableSending, setEnableSending] = useState(false);
+ const [domainCheckError, setDomainCheckError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [dnsView, setDnsView] = useState<{
domain: Domain;
@@ -42,13 +48,28 @@ export default function DomainsPage() {
const create = useMutation({
mutationFn: async () => {
+ const normalized = hostname.toLowerCase().trim();
+ let checkedDomain = domainCheck;
+ let sendingRequested = enableSending;
+ if (checkedDomain?.hostname !== normalized) {
+ const result = await checkDomain(normalized);
+ if (!result.ok || !result.domain) {
+ throw new Error(result.error ?? "Domain check failed");
+ }
+ checkedDomain = result.domain;
+ sendingRequested = true;
+ setDomainCheck(result.domain);
+ setEnableSending(sendingRequested);
+ }
+ if (!checkedDomain) throw new Error("Domain check failed");
+
const res = await authFetch("/api/domains", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- hostname,
+ hostname: checkedDomain.hostname,
enableRouting: true,
- enableSending: true,
+ enableSending: sendingRequested,
}),
});
const json = (await res.json()) as { error?: string };
@@ -57,6 +78,9 @@ export default function DomainsPage() {
},
onSuccess: () => {
setHostname("");
+ setDomainCheck(null);
+ setEnableSending(false);
+ setDomainCheckError(null);
setCreateOpen(false);
qc.invalidateQueries({ queryKey: ["domains"] });
},
@@ -76,14 +100,33 @@ export default function DomainsPage() {
if (res.ok) setDnsView(json);
};
+ const inspectDomain = async () => {
+ const normalized = hostname.toLowerCase().trim();
+ if (normalized.length < 3 || domainCheck?.hostname === normalized) return;
+
+ setDomainChecking(true);
+ setDomainCheckError(null);
+ const result = await checkDomain(normalized);
+ setDomainChecking(false);
+ if (!result.ok || !result.domain) {
+ setDomainCheck(null);
+ setEnableSending(false);
+ setDomainCheckError(result.error ?? "Domain check failed");
+ return;
+ }
+
+ setDomainCheck(result.domain);
+ setEnableSending(true);
+ };
+
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-4">
<div>
<h1 className="text-3xl font-medium">Domains</h1>
<p className="mt-1 text-sm text-neutral-500">
- Domains must be on your Cloudflare account. Adding a domain enables
- Email Routing and Email Sending DNS automatically.
+ Domains must be on your Cloudflare account. Email Routing is enabled
+ automatically, and Email Sending can be enabled when available.
</p>
</div>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
@@ -97,8 +140,8 @@ export default function DomainsPage() {
<DialogHeader>
<DialogTitle>Add domain</DialogTitle>
<DialogDescription>
- Provision Cloudflare routing and sending DNS for a zone in your
- account.
+ Connect a Cloudflare zone and choose whether Mailflare should
+ provision Email Sending.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
@@ -107,10 +150,52 @@ export default function DomainsPage() {
<Input
id="hostname"
value={hostname}
- onChange={(e) => setHostname(e.target.value)}
+ onChange={(e) => {
+ setHostname(e.target.value);
+ if (domainCheck?.hostname !== e.target.value.toLowerCase().trim()) {
+ setDomainCheck(null);
+ setEnableSending(false);
+ }
+ }}
+ onBlur={() => void inspectDomain()}
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="enable-sending">Enable sending</Label>
+ <p className="mt-1 text-xs leading-5 text-neutral-500">
+ {domainChecking
+ ? "Checking Cloudflare access..."
+ : domainCheck
+ ? enableSending
+ ? "Required to send email."
+ : "Receive-only mode."
+ : "Enter the domain and leave the field to verify it."}
+ </p>
+ </div>
+ {domainChecking ? (
+ <LoaderCircle className="h-4 w-4 animate-spin text-neutral-500" />
+ ) : (
+ <Switch
+ id="enable-sending"
+ checked={enableSending}
+ onCheckedChange={setEnableSending}
+ disabled={!domainCheck}
+ />
+ )}
+ </div>
+ {domainCheck && (
+ <div className="flex items-center gap-3 rounded-xl bg-green-50 px-4 py-3 text-sm text-green-700">
+ <CheckCircle2 className="h-4 w-4" />
+ Domain found in Cloudflare as {domainCheck.zone.name}
+ </div>
+ )}
+ {domainCheckError && (
+ <p className="rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">
+ {domainCheckError}
+ </p>
+ )}
{create.isError && (
<div className="space-y-3 rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">
<p>{(create.error as Error).message}</p>
@@ -120,8 +205,8 @@ export default function DomainsPage() {
</p>
<ul className="list-disc space-y-1 pl-5">
<li>
- All accounts — Email Sending:Edit, DNS Settings:Edit,
- Email Routing Addresses:Edit
+ All accounts — DNS Settings:Edit, Email Routing
+ Addresses:Edit; Email Sending:Edit for outbound mail
</li>
<li>
All zones — DNS Settings:Edit, Email Routing Rules:Edit,
@@ -133,7 +218,7 @@ export default function DomainsPage() {
)}
<Button
onClick={() => create.mutate()}
- disabled={!hostname || create.isPending}
+ disabled={!hostname || domainChecking || create.isPending}
>
{create.isPending ? "Adding..." : "Add domain"}
</Button>
diff --git a/src/app/(admin)/domains/types.d.ts b/src/app/(admin)/domains/types.d.ts
index dc75f5a..89fca8a 100644
--- a/src/app/(admin)/domains/types.d.ts
+++ b/src/app/(admin)/domains/types.d.ts
@@ -4,9 +4,21 @@ export type Domain = {
status: string;
routingEnabled: boolean;
sendingEnabled: boolean;
+ sendingRequested: boolean;
zoneId: string;
};
+export type DomainPreflight = {
+ hostname: string;
+ zone: { id: string; name: string };
+};
+
+export type DomainPreflightResponse = {
+ ok: boolean;
+ domain?: DomainPreflight;
+ error?: string;
+};
+
export type DnsRecord = {
type?: string;
name?: string;
diff --git a/src/app/(admin)/domains/utils.ts b/src/app/(admin)/domains/utils.ts
new file mode 100644
index 0000000..32ef4f7
--- /dev/null
+++ b/src/app/(admin)/domains/utils.ts
@@ -0,0 +1,12 @@
+import { authFetch } from "@/lib/auth/client";
+import type { DomainPreflightResponse } from "./types";
+
+export async function checkDomain(hostname: string): Promise<DomainPreflightResponse> {
+ const response = await authFetch("/api/domains/check", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ hostname }),
+ });
+ const data = (await response.json()) as Omit<DomainPreflightResponse, "ok">;
+ return { ok: response.ok, ...data };
+}
diff --git a/src/app/(auth)/onboarding/onboarding-client.tsx b/src/app/(auth)/onboarding/onboarding-client.tsx
index a3a3cf6..6b5d56e 100644
--- a/src/app/(auth)/onboarding/onboarding-client.tsx
+++ b/src/app/(auth)/onboarding/onboarding-client.tsx
@@ -2,17 +2,22 @@
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
-import { ArrowRight, MailPlus } from "lucide-react";
+import { 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";
import { Label } from "@/components/ui/label";
-import { createDomain, createMailbox, getDomains } from "./utils";
+import { Switch } from "@/components/ui/switch";
+import { checkDomain, createDomain, createMailbox, getDomains } from "./utils";
+import type { DomainPreflight } from "./types";
export function OnboardingClient() {
const router = useRouter();
const [step, setStep] = useState<1 | 2>(1);
const [hostname, setHostname] = useState("");
+ const [domainCheck, setDomainCheck] = useState<DomainPreflight | null>(null);
+ const [domainChecking, setDomainChecking] = useState(false);
+ const [enableSending, setEnableSending] = useState(false);
const [domainId, setDomainId] = useState("");
const [localPart, setLocalPart] = useState("me");
const [error, setError] = useState<string | null>(null);
@@ -34,7 +39,28 @@ export function OnboardingClient() {
setLoading(true);
setError(null);
- const { ok, data } = await createDomain(hostname);
+ const normalized = hostname.toLowerCase().trim();
+ let checkedDomain = domainCheck;
+ let sendingRequested = enableSending;
+ if (checkedDomain?.hostname !== normalized) {
+ const result = await checkDomain(normalized);
+ if (!result.ok || !result.domain) {
+ setLoading(false);
+ setError(result.error ?? "Domain check failed");
+ return;
+ }
+ checkedDomain = result.domain;
+ sendingRequested = true;
+ setDomainCheck(result.domain);
+ setEnableSending(sendingRequested);
+ }
+ if (!checkedDomain) {
+ setLoading(false);
+ setError("Domain check failed");
+ return;
+ }
+
+ const { ok, data } = await createDomain(checkedDomain.hostname, sendingRequested);
setLoading(false);
if (!ok || !data.domain) {
setError(data.error ?? "Failed to add domain");
@@ -44,6 +70,25 @@ export function OnboardingClient() {
setStep(2);
}
+ async function inspectDomain() {
+ const normalized = hostname.toLowerCase().trim();
+ if (normalized.length < 3 || domainCheck?.hostname === normalized) return;
+
+ setDomainChecking(true);
+ setError(null);
+ const result = await checkDomain(normalized);
+ setDomainChecking(false);
+ if (!result.ok || !result.domain) {
+ setDomainCheck(null);
+ setEnableSending(false);
+ setError(result.error ?? "Domain check failed");
+ return;
+ }
+
+ setDomainCheck(result.domain);
+ setEnableSending(true);
+ }
+
async function addMailbox() {
setLoading(true);
setError(null);
@@ -63,7 +108,7 @@ export function OnboardingClient() {
title={step === 1 ? "Connect mail routing" : "Create your first mailbox"}
description={
step === 1
- ? "Add the Cloudflare domain that will receive and send mail through this workspace."
+ ? "Add the Cloudflare domain that will receive mail and optionally send through this workspace."
: "Choose the mailbox address that should open directly into the inbox."
}
steps={[
@@ -89,13 +134,50 @@ export function OnboardingClient() {
<Input
id="domain"
value={hostname}
- onChange={(e) => setHostname(e.target.value)}
+ onChange={(e) => {
+ setHostname(e.target.value);
+ if (domainCheck?.hostname !== e.target.value.toLowerCase().trim()) {
+ setDomainCheck(null);
+ setEnableSending(false);
+ }
+ }}
+ onBlur={() => void inspectDomain()}
placeholder="example.com"
/>
</div>
+ <div className="flex items-center justify-between gap-4 rounded-2xl bg-neutral-50 px-4 py-3">
+ <div>
+ <Label htmlFor="onboarding-enable-sending">Enable sending</Label>
+ <p className="mt-1 text-xs leading-5 text-neutral-500">
+ {domainChecking
+ ? "Checking Cloudflare access..."
+ : domainCheck
+ ? enableSending
+ ? "Required to send email."
+ : "Receive-only mode."
+ : "Leave the domain field to verify it."}
+ </p>
+ </div>
+ {domainChecking ? (
+ <LoaderCircle className="h-4 w-4 animate-spin text-neutral-500" />
+ ) : (
+ <Switch
+ id="onboarding-enable-sending"
+ checked={enableSending}
+ onCheckedChange={setEnableSending}
+ disabled={!domainCheck}
+ />
+ )}
+ </div>
+ {domainCheck && (
+ <div className="flex items-center gap-3 rounded-2xl bg-green-50 px-4 py-3 text-sm text-green-700">
+ <CheckCircle2 className="h-4 w-4" />
+ Domain found in Cloudflare as {domainCheck.zone.name}
+ </div>
+ )}
<Button
onClick={addDomain}
- disabled={!hostname || loading}
+ disabled={!hostname || loading || domainChecking}
className="h-11 w-full rounded-full px-6 active:scale-[0.98]"
>
{loading ? "Adding..." : "Add domain"}
diff --git a/src/app/(auth)/onboarding/types.d.ts b/src/app/(auth)/onboarding/types.d.ts
index 098ae19..e94f750 100644
--- a/src/app/(auth)/onboarding/types.d.ts
+++ b/src/app/(auth)/onboarding/types.d.ts
@@ -7,6 +7,17 @@ export type DomainCreateResult = {
error?: string;
};
+export type DomainPreflight = {
+ hostname: string;
+ zone: { id: string; name: string };
+};
+
+export type DomainPreflightResponse = {
+ ok: boolean;
+ domain?: DomainPreflight;
+ error?: string;
+};
+
export type MailboxCreateResult = {
error?: string;
};
diff --git a/src/app/(auth)/onboarding/utils.ts b/src/app/(auth)/onboarding/utils.ts
index 520f57f..ed8bfd1 100644
--- a/src/app/(auth)/onboarding/utils.ts
+++ b/src/app/(auth)/onboarding/utils.ts
@@ -1,16 +1,34 @@
import { authFetch } from "@/lib/auth/client";
-import type { DomainCreateResult, DomainListResult, MailboxCreateResult } from "./types";
+import type {
+ DomainCreateResult,
+ DomainListResult,
+ DomainPreflightResponse,
+ MailboxCreateResult,
+} from "./types";
export async function getDomains(): Promise<DomainListResult> {
const res = await authFetch("/api/domains");
return (await res.json()) as DomainListResult;
}
-export async function createDomain(hostname: string): Promise<{ ok: boolean; data: DomainCreateResult }> {
+export async function checkDomain(hostname: string): Promise<DomainPreflightResponse> {
+ const res = await authFetch("/api/domains/check", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ hostname }),
+ });
+ const data = (await res.json()) as Omit<DomainPreflightResponse, "ok">;
+ return { ok: res.ok, ...data };
+}
+
+export async function createDomain(
+ hostname: string,
+ enableSending: boolean,
+): 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: true }),
+ body: JSON.stringify({ hostname, enableRouting: true, enableSending }),
});
return {
diff --git a/src/app/(auth)/register/register-client.tsx b/src/app/(auth)/register/register-client.tsx
index 99cf48e..706136f 100644
--- a/src/app/(auth)/register/register-client.tsx
+++ b/src/app/(auth)/register/register-client.tsx
@@ -8,6 +8,7 @@ import { AuthShell } from "@/components/auth/auth-shell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
import { TurnstileField } from "@/components/auth/turnstile";
import {
getSetupStatus,
@@ -15,7 +16,7 @@ import {
submitPrimaryDomain,
submitRegistration,
} from "./utils";
-import type { SetupRequirementCheck } from "./types";
+import type { DomainPreflight, DomainSetupResult, SetupRequirementCheck } from "./types";
export function RegisterClient() {
const router = useRouter();
@@ -24,7 +25,12 @@ export function RegisterClient() {
null,
);
const [primaryDomain, setPrimaryDomain] = useState<string | null>(null);
+ const [primaryDomainSendingRequested, setPrimaryDomainSendingRequested] = useState<boolean | null>(null);
const [setupDomain, setSetupDomain] = useState<string | null>(null);
+ const [domainCheck, setDomainCheck] = useState<DomainPreflight | null>(null);
+ const [domainChecking, setDomainChecking] = useState(false);
+ const [enableSending, setEnableSending] = useState(false);
+ const [setupEnableSending, setSetupEnableSending] = useState(false);
const [step, setStep] = useState<1 | 2 | 3>(1);
const [checks, setChecks] = useState<SetupRequirementCheck[]>([]);
const [databaseMigrated, setDatabaseMigrated] = useState(false);
@@ -55,6 +61,7 @@ export function RegisterClient() {
setHasAdminAccount(data.hasAdminAccount);
setHasPrimaryDomain(data.hasPrimaryDomain);
setPrimaryDomain(data.primaryDomain?.hostname ?? null);
+ setPrimaryDomainSendingRequested(data.primaryDomain?.sendingRequested ?? null);
setPreparationComplete(true);
} catch (error) {
setError(error instanceof Error ? error.message : "Installation preparation failed");
@@ -68,9 +75,12 @@ export function RegisterClient() {
setLoading(true);
setError(null);
- const { ok, data } = await submitPrimaryDomain(
- new FormData(e.currentTarget),
- );
+ const hostname = String(new FormData(e.currentTarget).get("domain") ?? "").toLowerCase().trim();
+ const usedCachedCheck = domainCheck?.hostname === hostname;
+ const result: { ok: boolean; data: DomainSetupResult } = usedCachedCheck
+ ? { ok: true, data: { domain: domainCheck } }
+ : await submitPrimaryDomain(hostname);
+ const { ok, data } = result;
setLoading(false);
if (!ok || !data.domain) {
setError(
@@ -79,9 +89,29 @@ export function RegisterClient() {
return;
}
setSetupDomain(data.domain.hostname);
+ setSetupEnableSending(usedCachedCheck ? enableSending : true);
setStep(3);
}
+ async function onDomainBlur(e: React.FocusEvent<HTMLInputElement>) {
+ const hostname = e.currentTarget.value.toLowerCase().trim();
+ if (hostname.length < 3 || domainCheck?.hostname === hostname) return;
+
+ setDomainChecking(true);
+ setError(null);
+ const { ok, data } = await submitPrimaryDomain(hostname);
+ setDomainChecking(false);
+ if (!ok || !data.domain) {
+ setDomainCheck(null);
+ setEnableSending(false);
+ setError(typeof data.error === "string" ? data.error : "Domain check failed");
+ return;
+ }
+
+ setDomainCheck(data.domain);
+ setEnableSending(true);
+ }
+
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
@@ -95,7 +125,13 @@ export function RegisterClient() {
return;
}
- const { ok, data } = await submitRegistration(form, { firstRun: true, domain });
+ const { ok, data } = await submitRegistration(form, {
+ firstRun: true,
+ domain,
+ enableSending: setupDomain
+ ? setupEnableSending
+ : primaryDomainSendingRequested ?? undefined,
+ });
setLoading(false);
if (!ok) {
setError(
@@ -225,11 +261,44 @@ export function RegisterClient() {
placeholder="example.com"
autoComplete="url"
required
+ onBlur={(event) => void onDomainBlur(event)}
+ onChange={(event) => {
+ if (domainCheck?.hostname !== event.currentTarget.value.toLowerCase().trim()) {
+ setDomainCheck(null);
+ setEnableSending(false);
+ }
+ }}
/>
<p className="text-xs leading-5 text-neutral-500">
The domain must already be a Cloudflare zone on this account.
</p>
</div>
+ <div className="flex items-center justify-between gap-4 rounded-2xl bg-neutral-50 px-4 py-3">
+ <div>
+ <Label htmlFor="setup-enable-sending">Enable sending</Label>
+ <p className="mt-1 text-xs leading-5 text-neutral-500">
+ {domainChecking
+ ? "Checking Cloudflare access..."
+ : domainCheck
+ ? enableSending
+ ? "Required to send email."
+ : "Receive-only mode."
+ : "Enter the domain and leave the field to verify it."}
+ </p>
+ </div>
+ <Switch
+ id="setup-enable-sending"
+ checked={enableSending}
+ onCheckedChange={setEnableSending}
+ disabled={domainChecking || !domainCheck}
+ />
+ </div>
+ {domainCheck && (
+ <div className="flex items-center gap-3 rounded-2xl bg-green-50 px-4 py-3 text-sm text-green-700">
+ <CheckCircle2 className="h-4 w-4" />
+ Domain found in Cloudflare as {domainCheck.zone.name}
+ </div>
+ )}
{error && (
<p className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">
{error}
@@ -238,7 +307,7 @@ export function RegisterClient() {
<Button
type="submit"
className="h-11 w-full rounded-full px-6 active:scale-[0.98]"
- disabled={loading}
+ disabled={loading || domainChecking}
>
{loading ? "Adding domain..." : "Continue"}
</Button>
diff --git a/src/app/(auth)/register/types.d.ts b/src/app/(auth)/register/types.d.ts
index 262fad3..6c45a4a 100644
--- a/src/app/(auth)/register/types.d.ts
+++ b/src/app/(auth)/register/types.d.ts
@@ -1,7 +1,7 @@
export type SetupStatus = {
hasAdminAccount: boolean;
hasPrimaryDomain: boolean;
- primaryDomain?: { hostname: string } | null;
+ primaryDomain?: { hostname: string; sendingRequested: boolean } | null;
error?: string;
};
@@ -17,8 +17,13 @@ export type SetupPreparationResult = {
error?: string;
};
+export type DomainPreflight = {
+ hostname: string;
+ zone: { id: string; name: string };
+};
+
export type DomainSetupResult = {
- domain?: { hostname: string };
+ domain?: DomainPreflight;
error?: string;
};
diff --git a/src/app/(auth)/register/utils.ts b/src/app/(auth)/register/utils.ts
index 3422368..5cf5ea8 100644
--- a/src/app/(auth)/register/utils.ts
+++ b/src/app/(auth)/register/utils.ts
@@ -21,11 +21,11 @@ export async function getSetupStatus(): Promise<SetupStatus> {
return data;
}
-export async function submitPrimaryDomain(form: FormData): Promise<{ ok: boolean; data: DomainSetupResult }> {
+export async function submitPrimaryDomain(hostname: string): Promise<{ ok: boolean; data: DomainSetupResult }> {
const res = await fetch("/api/setup/domain", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ hostname: form.get("domain") }),
+ body: JSON.stringify({ hostname }),
});
return {
@@ -36,7 +36,7 @@ export async function submitPrimaryDomain(form: FormData): Promise<{ ok: boolean
export async function submitRegistration(
form: FormData,
- payload: { firstRun: boolean; domain: string },
+ payload: { firstRun: boolean; domain: string; enableSending?: boolean },
): Promise<{ ok: boolean; data: RegisterResult }> {
const res = await fetch("/api/auth/register", {
method: "POST",
@@ -45,6 +45,7 @@ export async function submitRegistration(
payload.firstRun
? {
domain: payload.domain,
+ enableSending: payload.enableSending,
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.ts
index 83261f9..45a809a 100644
--- a/src/app/api/auth/register/route.ts
+++ b/src/app/api/auth/register/route.ts
@@ -69,7 +69,7 @@ export async function POST(request: Request) {
try {
const added = await addDomainForUser(env, userId, domainName, {
enableRouting: true,
- enableSending: true,
+ enableSending: firstRunParsed.data.enableSending ?? true,
});
const domain = added.domain;
changes = added.changes;
diff --git a/src/app/api/domains/check/route.ts b/src/app/api/domains/check/route.ts
new file mode 100644
index 0000000..b5d9e48
--- /dev/null
+++ b/src/app/api/domains/check/route.ts
@@ -0,0 +1,21 @@
+import { NextResponse } from "next/server";
+import { requireUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { preflightDomain } from "@/lib/domains/preflight";
+import { setupDomainSchema } from "@/lib/validators";
+
+export async function POST(request: Request) {
+ const env = getEnv();
+ await requireUser(env, request);
+ const parsed = setupDomainSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
+ }
+
+ try {
+ return NextResponse.json({ domain: await preflightDomain(env, parsed.data.hostname) });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Domain check failed";
+ return NextResponse.json({ error: message }, { status: 502 });
+ }
+}
diff --git a/src/app/api/setup/domain/route.ts b/src/app/api/setup/domain/route.ts
index a9cb494..a8f43b1 100644
--- a/src/app/api/setup/domain/route.ts
+++ b/src/app/api/setup/domain/route.ts
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { hasAdminAccount } from "@/lib/auth/setup";
import { getEnv } from "@/lib/cloudflare";
-import { provisionDomainOnCloudflare } from "@/lib/domains/provision";
+import { preflightDomain } from "@/lib/domains/preflight";
import { getPrimaryDomain } from "@/lib/user";
import { setupDomainSchema } from "@/lib/validators";
import { readJsonBody } from "@/lib/http/request";
@@ -31,20 +31,9 @@ export async function POST(request: Request) {
}
try {
- const provisioned = await provisionDomainOnCloudflare(env, parsed.data.hostname, {
- enableRouting: true,
- enableSending: true,
- });
- return NextResponse.json({
- domain: {
- hostname: provisioned.hostname,
- zoneId: provisioned.zone.id,
- routingEnabled: provisioned.routingEnabled,
- sendingEnabled: provisioned.sendingEnabled,
- },
- });
+ return NextResponse.json({ domain: await preflightDomain(env, parsed.data.hostname) });
} catch (err) {
- const message = err instanceof Error ? err.message : "Domain setup failed";
+ const message = err instanceof Error ? err.message : "Domain check failed";
return NextResponse.json({ error: message }, { status: 502 });
}
}
diff --git a/src/app/api/setup/status/route.ts b/src/app/api/setup/status/route.ts
index b9e658f..0050c37 100644
--- a/src/app/api/setup/status/route.ts
+++ b/src/app/api/setup/status/route.ts
@@ -13,7 +13,9 @@ export async function GET() {
return NextResponse.json({
hasAdminAccount: adminAccountExists,
hasPrimaryDomain: !!domain,
- primaryDomain: domain ? { hostname: domain.hostname } : null,
+ primaryDomain: domain
+ ? { hostname: domain.hostname, sendingRequested: domain.sendingRequested }
+ : null,
}, {
headers: { "Cache-Control": "no-store" },
});
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index db8656d..47542ff 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -32,6 +32,7 @@ export const domains = sqliteTable(
.default("pending"),
routingStatus: text("routing_status"),
sendingSubdomainTag: text("sending_subdomain_tag"),
+ 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),
createdAt: integer("created_at", { mode: "timestamp" })
diff --git a/src/lib/domains/preflight.ts b/src/lib/domains/preflight.ts
new file mode 100644
index 0000000..4ff4639
--- /dev/null
+++ b/src/lib/domains/preflight.ts
@@ -0,0 +1,17 @@
+import { findZoneByHostname } from "@/lib/cloudflare-api";
+import type { DomainPreflightResult } from "@/lib/domains/types";
+
+export async function preflightDomain(
+ env: CloudflareEnv,
+ hostname: string,
+): Promise<DomainPreflightResult> {
+ const normalized = hostname.toLowerCase().trim();
+ const zone = await findZoneByHostname(env, normalized);
+ if (!zone) {
+ throw new Error(
+ `Zone not found for "${normalized}". The domain must use Cloudflare DNS on this account.`,
+ );
+ }
+
+ return { hostname: normalized, zone };
+}
diff --git a/src/lib/domains/provision.ts b/src/lib/domains/provision.ts
index 7dc6430..8753fe9 100644
--- a/src/lib/domains/provision.ts
+++ b/src/lib/domains/provision.ts
@@ -64,20 +64,16 @@ export async function provisionDomainOnCloudflare(
}
if (enableSending) {
- if (isZoneApex(normalized, zone.name)) {
- sendingEnabled = false;
+ 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 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;
- }
+ const created = await createSendingSubdomain(env, zone.id, normalized);
+ sendingSubdomainTag = created.tag;
+ sendingEnabled = created.enabled;
+ changes.createdSendingSubdomainTag = created.tag;
}
}
@@ -85,6 +81,7 @@ export async function provisionDomainOnCloudflare(
hostname: normalized,
zone,
routingEnabled,
+ sendingRequested: enableSending,
sendingEnabled,
sendingSubdomainTag,
routingStatus,
diff --git a/src/lib/domains/service.ts b/src/lib/domains/service.ts
index 33cdcc3..93a787d 100644
--- a/src/lib/domains/service.ts
+++ b/src/lib/domains/service.ts
@@ -59,6 +59,7 @@ export async function addDomainForUser(
status: provisioned.routingEnabled || provisioned.sendingEnabled ? ("active" as const) : ("pending" as const),
routingStatus: provisioned.routingStatus ?? null,
sendingSubdomainTag: provisioned.sendingSubdomainTag,
+ sendingRequested: provisioned.sendingRequested,
sendingEnabled: provisioned.sendingEnabled,
routingEnabled: provisioned.routingEnabled,
};
@@ -109,7 +110,7 @@ export async function getDomainDns(
env: CloudflareEnv,
domain: typeof domains.$inferSelect,
): Promise<DomainDnsView> {
- const shouldInspectSending = domain.sendingEnabled || Boolean(domain.sendingSubdomainTag);
+ const shouldInspectSending = domain.sendingRequested;
const [routingDns, routingSettings, sendingSubdomains] = await Promise.all([
getEmailRoutingDns(env, domain.zoneId),
getEmailRoutingSettings(env, domain.zoneId),
diff --git a/src/lib/domains/types.d.ts b/src/lib/domains/types.d.ts
index 2679fdd..9e3daae 100644
--- a/src/lib/domains/types.d.ts
+++ b/src/lib/domains/types.d.ts
@@ -24,10 +24,16 @@ export type DomainProvisioningResult = {
hostname: string;
zone: { id: string; name: string };
routingEnabled: boolean;
+ sendingRequested: boolean;
sendingEnabled: boolean;
sendingSubdomainTag: string | null;
routingStatus?: string;
changes: DomainProvisioningChanges;
};
+export type DomainPreflightResult = {
+ hostname: string;
+ zone: { id: string; name: string };
+};
+
export type DomainRow = typeof domains.$inferSelect;
diff --git a/src/lib/seed-utils.ts b/src/lib/seed-utils.ts
index ca17e0b..ccdc8d1 100644
--- a/src/lib/seed-utils.ts
+++ b/src/lib/seed-utils.ts
@@ -262,6 +262,7 @@ export async function ensureDemoDomain(env: CloudflareEnv, userId: string) {
zoneId: "00000000000000000000000000000000",
status: "active",
routingEnabled: true,
+ sendingRequested: true,
sendingEnabled: true,
});
diff --git a/src/lib/setup/migration.ts b/src/lib/setup/migration.ts
index 9e6e136..fa4f5dc 100644
--- a/src/lib/setup/migration.ts
+++ b/src/lib/setup/migration.ts
@@ -24,12 +24,13 @@ const MIGRATION_NAMES = [
"0022_add_mailbox_auto_reply.sql",
"0023_add_mailbox_aliases.sql",
"0024_add_advanced_routing_and_webhook_retries.sql",
+ "0025_add_domain_sending_intent.sql",
];
const INITIAL_SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS users (id text PRIMARY KEY NOT NULL, email text NOT NULL UNIQUE, reset_email text, forwarding_email text, password_hash text NOT NULL, name text NOT NULL, avatar_key text, role text DEFAULT 'user' NOT NULL, disabled integer DEFAULT false NOT NULL, can_manage_mailboxes integer DEFAULT false NOT NULL, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);
CREATE INDEX IF NOT EXISTS users_created_by_idx ON users(created_by_user_id);
-CREATE TABLE IF NOT EXISTS domains (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, hostname text NOT NULL, zone_id text NOT NULL, status text DEFAULT 'pending' NOT NULL, routing_status text, sending_subdomain_tag text, sending_enabled integer DEFAULT false NOT NULL, routing_enabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);
+CREATE TABLE IF NOT EXISTS domains (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, hostname text NOT NULL, zone_id text NOT NULL, status text DEFAULT 'pending' NOT NULL, routing_status text, sending_subdomain_tag text, sending_requested integer DEFAULT false NOT NULL, sending_enabled integer DEFAULT false NOT NULL, routing_enabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);
CREATE UNIQUE INDEX IF NOT EXISTS domains_hostname_idx ON domains(hostname);
CREATE INDEX IF NOT EXISTS domains_user_idx ON domains(user_id);
CREATE TABLE IF NOT EXISTS mailboxes (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, domain_id text NOT NULL REFERENCES domains(id) ON DELETE cascade, local_part text NOT NULL, display_name text, signature text, auto_reply_enabled integer DEFAULT false NOT NULL, auto_reply_subject text DEFAULT 'Out of office' NOT NULL, auto_reply_body text DEFAULT '' NOT NULL, avatar_key text, type text DEFAULT 'personal' NOT NULL, use_all_domains integer DEFAULT true NOT NULL, disabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index d09ef99..fa4a708 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -28,6 +28,7 @@ export const registerSchema = z.object({
export const firstRunRegisterSchema = z.object({
domain: z.string().min(3),
+ enableSending: z.boolean().optional(),
username: z.string().min(1).max(64).regex(/^[a-zA-Z0-9._%+-]+$/),
password: z.string().min(8),
resetEmail: z.string().email(),
diff --git a/tests/setup-bootstrap-schema.test.mjs b/tests/setup-bootstrap-schema.test.mjs
index 109d10c..5a89db6 100644
--- a/tests/setup-bootstrap-schema.test.mjs
+++ b/tests/setup-bootstrap-schema.test.mjs
@@ -20,12 +20,13 @@ function initialSchemaSql() {
return match[1];
}
-test("bootstrap records migrations 0013, 0021, and 0022 so later deploys do not re-apply them", () => {
+test("bootstrap records migrations represented in the current schema so later deploys do not re-apply them", () => {
const names = migrationNames();
for (const name of [
"0013_add_license_settings.sql",
"0021_add_mailbox_signature.sql",
"0022_add_mailbox_auto_reply.sql",
+ "0025_add_domain_sending_intent.sql",
]) {
assert.ok(names.includes(name), `MIGRATION_NAMES is missing ${name}`);
}
@@ -41,6 +42,9 @@ test("fresh bootstrap schema accepts the current Drizzle mailbox and license ins
assert.match(mailboxCreate[1], /\bauto_reply_body\b/);
assert.match(sql, /CREATE TABLE IF NOT EXISTS license_settings \(/);
assert.match(sql, /CREATE TABLE IF NOT EXISTS auto_reply_deliveries \(/);
+ const domainCreate = sql.match(/CREATE TABLE IF NOT EXISTS domains \(([\s\S]*?)\);/);
+ assert.ok(domainCreate, "domains CREATE TABLE not found");
+ assert.match(domainCreate[1], /\bsending_requested\b/);
const py = `
import sqlite3, sys