Skip to content

Email for professionals and teams

improve domain setup / record checking

Hieu Nguyen (Jack)214fb2a54fee
diff --git a/docs/api.md b/docs/api.md
index dd33093..3c425eb 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -16,6 +16,21 @@ Adding or removing a domain from Mailflare also updates Cloudflare Email Routing
The hostname must be the apex of a zone available to the configured Cloudflare credentials, or a subdomain of that zone. Creating a mailbox also creates the Cloudflare Email Routing rule that delivers its address to the `mailflare` Worker.
+### Domain management over the API
+
+The same operations are available to scripts through API keys with the `domains` scope, using `Authorization: Bearer <key>`:
+
+| Mailflare route | Purpose |
+| --- | --- |
+| `GET /api/v1/domains` | List connected domains with their DNS status |
+| `POST /api/v1/domains` | Connect a domain and configure Cloudflare (`{ hostname, enableRouting?, enableSending?, replaceMxRecords? }`) |
+| `GET /api/v1/domains/[id]` | Get a connected domain |
+| `DELETE /api/v1/domains/[id]` | Remove a domain and clean up its Cloudflare resources |
+| `GET /api/v1/domains/[id]/dns` | View its routing, sending and authentication DNS status |
+| `POST /api/v1/domains/[id]/dns/setup` | Create a missing record (`{ record: "mx" \| "spf" \| "dkim" \| "dmarc" }`) |
+
+`GET /api/v1/domains` returns `{ domains, dns }`, where `dns[id].auth` reports `ok` / `missing` / `unknown` for MX, SPF, DKIM and DMARC. `GET /api/v1/domains/[id]/dns` returns the full audit, including the names queried and the values found. The `setup` route provisions MX/SPF through Email Routing, DKIM through the sending subdomain, and a `v=DMARC1; p=none` TXT for DMARC; on a self-hosted install where DNS is managed manually it returns an error, since Mailflare cannot write the zone.
+
## Sending email
Send email through `POST /api/v1/send`. `to`, `cc` and `bcc` accept either a comma-separated header string or an array of addresses; each entry may carry a display name (`"Maya Chen" <[email protected]>`). A message can reach up to 50 recipients across the three fields. Attachments are optional and use Base64-encoded content:
diff --git a/src/app/(admin)/accounts/page.tsx b/src/app/(admin)/accounts/page.tsx
index 4565e9c..c832d9f 100644
--- a/src/app/(admin)/accounts/page.tsx
+++ b/src/app/(admin)/accounts/page.tsx
@@ -10,6 +10,7 @@ import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
import { authFetch } from "@/lib/auth/client";
import { LicenseRequiredOverlay } from "@/components/license-required-overlay";
+import { List, ListRow } from "@/components/ui/list";
import type { Account, AccountResponse, Domain } from "./types";
export default function AccountsPage() {
@@ -67,10 +68,10 @@ export default function AccountsPage() {
return <div className="space-y-6">
<div className="flex items-center justify-between gap-4"><div><h1 className="text-3xl font-medium text-neutral-900">Accounts</h1><p className="mt-2 text-sm text-neutral-500">Manage Team accounts and their inboxes.</p></div>{!teamRequired && <Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4" />New account</Button>}</div>
- <div className="relative">{teamRequired && <LicenseRequiredOverlay required="Team"><div className="min-h-48 rounded-3xl bg-white" /></LicenseRequiredOverlay>}<div className="grid gap-3">
+ <div className="relative">{teamRequired && <LicenseRequiredOverlay required="Team"><div className="min-h-48 rounded-3xl bg-white" /></LicenseRequiredOverlay>}<List>
{loading && <p className="text-sm text-neutral-500">Loading...</p>}
- {accounts.map((account) => <Link key={account.id} href={`/accounts/${account.id}`} className="flex items-center gap-4 rounded-3xl bg-white p-5 transition-colors hover:bg-blue-50/40"><span className="relative flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-full bg-blue-100 font-semibold text-blue-700">{account.name.charAt(0).toUpperCase()}{account.hasAvatar && <img src={`/api/accounts/${account.id}/avatar`} alt="" className="absolute inset-0 h-full w-full object-cover" />}</span><span className="min-w-0"><span className="flex items-center gap-2"><span className="truncate font-semibold text-neutral-900">{account.name}</span><span className="rounded-full bg-neutral-100 px-2 py-0.5 text-xs font-medium capitalize text-neutral-600">{account.role}</span></span><span className="block truncate text-sm text-neutral-500">{account.email}</span></span></Link>)}
- </div></div>
+ {accounts.map((account) => <ListRow key={account.id} asChild><Link href={`/accounts/${account.id}`}><span className="relative flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-full bg-blue-100 font-semibold text-blue-700 duration-200">{account.name.charAt(0).toUpperCase()}{account.hasAvatar && <img src={`/api/accounts/${account.id}/avatar`} alt="" className="absolute inset-0 h-full w-full object-cover" />}</span><span className="min-w-0"><span className="flex items-center gap-2"><span className="truncate font-semibold text-neutral-900">{account.name}</span><span className="rounded-full bg-neutral-100 px-2 py-0.5 text-xs font-medium capitalize text-neutral-600">{account.role}</span></span><span className="block truncate text-sm text-neutral-500">{account.email}</span></span></Link></ListRow>)}
+ </List></div>
<Dialog open={createOpen} onOpenChange={setCreateOpen}><DialogContent><DialogHeader><DialogTitle>Add user account</DialogTitle><DialogDescription>The user can sign in with this email and password.</DialogDescription></DialogHeader><form onSubmit={createAccount} className="space-y-4">
<div className="space-y-2"><Label htmlFor="account-username">Email</Label><div className="flex h-10 overflow-hidden rounded-md border border-neutral-200 bg-white"><Input id="account-username" value={username} onChange={(event) => setUsername(event.target.value)} placeholder="username" className="min-w-0 flex-1 rounded-none border-0 shadow-none" required /><span className="flex items-center text-sm text-neutral-400">@</span><Select aria-label="Domain" value={domainId} onChange={(event) => setDomainId(event.target.value)} className="max-w-[55%] bg-transparent px-3 text-sm" required><option value="">Select domain</option>{domains.map((domain) => <option key={domain.id} value={domain.id}>{domain.hostname}</option>)}</Select></div></div>
<div className="space-y-2"><Label htmlFor="account-password">Password</Label><Input id="account-password" type="password" minLength={8} value={password} onChange={(event) => setPassword(event.target.value)} required /></div>
diff --git a/src/app/(admin)/api-keys/page.tsx b/src/app/(admin)/api-keys/page.tsx
index 0379611..af5ad52 100644
--- a/src/app/(admin)/api-keys/page.tsx
+++ b/src/app/(admin)/api-keys/page.tsx
@@ -16,14 +16,17 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { Checkbox } from "@/components/ui/checkbox";
import { CardGridSkeleton } from "@/components/page-skeletons";
import { authFetch } from "@/lib/auth/client";
+import { API_KEY_SCOPES, type ApiKeyScope } from "@/lib/api/scopes";
import type { ApiKey } from "./types";
import { parseApiKeyScopes } from "./utils";
export default function ApiKeysPage() {
const qc = useQueryClient();
const [name, setName] = useState("");
+ const [scopes, setScopes] = useState<ApiKeyScope[]>(["send", "read"]);
const [newKey, setNewKey] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
@@ -40,7 +43,7 @@ export default function ApiKeysPage() {
const res = await authFetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name, scopes: ["send", "read"] }),
+ body: JSON.stringify({ name, scopes }),
});
const json = (await res.json()) as { key?: string };
if (!res.ok) throw new Error("Failed");
@@ -49,6 +52,7 @@ export default function ApiKeysPage() {
},
onSuccess: () => {
setCreateOpen(false);
+ setScopes(["send", "read"]);
qc.invalidateQueries({ queryKey: ["api-keys"] });
},
});
@@ -67,20 +71,43 @@ export default function ApiKeysPage() {
<DialogContent>
<DialogHeader>
<DialogTitle>Create API key</DialogTitle>
- <DialogDescription>Create a key with send and read permissions.</DialogDescription>
- </DialogHeader>
- <div className="space-y-4">
- <div className="space-y-2">
- <Label>Name</Label>
- <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Production app" />
+ <DialogDescription>Choose what this key is allowed to do.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Label>Name</Label>
+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Production app" />
+ </div>
+ <div className="space-y-2">
+ <Label>Scopes</Label>
+ <div className="flex flex-wrap gap-x-4 gap-y-2">
+ {API_KEY_SCOPES.map((scope) => (
+ <label key={scope} className="flex items-center gap-2 text-sm">
+ <Checkbox
+ checked={scopes.includes(scope)}
+ onChange={(event) =>
+ setScopes((current) =>
+ event.target.checked
+ ? [...current, scope]
+ : current.filter((item) => item !== scope),
+ )
+ }
+ />
+ {scope}
+ </label>
+ ))}
</div>
- {create.isError && (
- <p className="text-sm text-red-600">{(create.error as Error).message}</p>
- )}
- <Button onClick={() => create.mutate()} disabled={!name || create.isPending}>
- {create.isPending ? "Creating..." : "Create key"}
- </Button>
</div>
+ {create.isError && (
+ <p className="text-sm text-red-600">{(create.error as Error).message}</p>
+ )}
+ <Button
+ onClick={() => create.mutate()}
+ disabled={!name || scopes.length === 0 || create.isPending}
+ >
+ {create.isPending ? "Creating..." : "Create key"}
+ </Button>
+ </div>
</DialogContent>
</Dialog>
</div>
diff --git a/src/app/(admin)/domains/DomainDnsDetails.tsx b/src/app/(admin)/domains/DomainDnsDetails.tsx
index aa8f38f..acc329b 100644
--- a/src/app/(admin)/domains/DomainDnsDetails.tsx
+++ b/src/app/(admin)/domains/DomainDnsDetails.tsx
@@ -1,16 +1,83 @@
import { AlertTriangle, Check } from "lucide-react";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
import { getDnsRecordLabel } from "./domain-dns-details-utils";
+import { dnsAuthRecords, getDnsAuthItemClass, getDnsAuthStatusLabel } from "./utils";
import type { DomainDnsDetailsProps } from "./types";
-export default function DomainDnsDetails({ domain, dns }: DomainDnsDetailsProps) {
+export default function DomainDnsDetails({
+ domain,
+ dns,
+ onSetup,
+ setupRecord,
+ setupMessage,
+}: DomainDnsDetailsProps) {
+ const audit = dns.audit;
+ const manual = domain.zoneId === "manual";
return (
- <Card className="rounded-3xl border-0 bg-white p-6">
- <CardHeader className="py-0">
- <CardTitle>DNS — {domain.hostname}</CardTitle>
- </CardHeader>
- <CardContent className="gap-6 pt-5">
- <section className="space-y-3">
+ <div className="border-t border-neutral-100 pt-5">
+ {audit && (
+ <section className="space-y-3">
+ <h2 className="text-sm font-medium text-neutral-900">Authentication</h2>
+ <ul className="space-y-2">
+ {dnsAuthRecords.map((record) => {
+ const item = audit[record];
+ const ok = item.status === "ok";
+ const statusStr = getDnsAuthStatusLabel(item.status);
+
+ return (
+ <li
+ key={record}
+ className={`flex items-start gap-2 rounded-xl px-3 py-2 text-sm ${getDnsAuthItemClass(item.status)}`}
+ >
+ {ok ? (
+ <Check className="mt-0.5 h-4 w-4 shrink-0 text-green-600" />
+ ) : (
+ <AlertTriangle
+ className={`mt-0.5 h-4 w-4 shrink-0 ${item.status === "missing" ? "text-red-600" : "text-neutral-400"}`}
+ />
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="font-medium">{item.label}</span>{" "}
+ <span className="break-all">{item.name}</span>{" "}
+
+ {item.found.length > 0 ? (
+ <span className="block break-all text-xs opacity-80">
+ {item.found.join(", ")}
+ </span>
+ ) : !ok && <span className="block break-all text-xs opacity-80 capitalize">{statusStr}</span>}
+ </span>
+
+ {ok ? <span className="capitalize">{statusStr}</span> : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ disabled={manual || setupRecord === record}
+ title={
+ manual
+ ? "DNS for this domain is managed manually"
+ : `Create the ${item.label} record`
+ }
+ onClick={() => onSetup?.(record)}
+ >
+ {setupRecord === record ? "Setting up..." : "Setup"}
+ </Button>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ {manual && (
+ <p className="text-xs text-neutral-500">
+ DNS is managed manually for this domain, so records must be created
+ where the domain&apos;s nameservers are hosted.
+ </p>
+ )}
+ {setupMessage && <p className="text-xs text-red-600">{setupMessage}</p>}
+ </section>
+ )}
+
+ <section className={audit ? "space-y-3 mt-8" : "space-y-3"}>
<h2 className="text-sm font-medium text-neutral-900">Email Routing</h2>
<ul className="space-y-2">
{dns.routing.records.map((record, index) => (
@@ -67,8 +134,7 @@ export default function DomainDnsDetails({ domain, dns }: DomainDnsDetailsProps)
</li>
)}
</ul>
- </section>
- </CardContent>
- </Card>
+ </section>
+ </div>
);
}
diff --git a/src/app/(admin)/domains/DomainItemCard.tsx b/src/app/(admin)/domains/DomainItemCard.tsx
index 875a7e3..c87f914 100644
--- a/src/app/(admin)/domains/DomainItemCard.tsx
+++ b/src/app/(admin)/domains/DomainItemCard.tsx
@@ -1,91 +1,136 @@
+import { Fragment } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
+import { ListRow } from "@/components/ui/list";
+import { cn } from "@/lib/utils";
+import DomainDnsDetails from "./DomainDnsDetails";
+import { dnsAuthRecords, getDnsAuthStatusLabel } from "./utils";
import {
Check,
- X,
AlertTriangle,
- ArrowRight,
+ ChevronDown,
+ ChevronRight,
Globe2,
Trash2,
} from "lucide-react";
+import type { DomainItemCardProps } from "./types";
-export default function DomainItemCard({ item, dns, remove, loadDns }: any) {
+function StatusIcon({ ok, className }: { ok: boolean; className?: string }) {
+ if (ok) return <Check className={cn(className, "text-green-600")} />;
+ return <AlertTriangle className={cn(className, "text-amber-500")} />;
+}
+
+export default function DomainItemCard({
+ item,
+ dns,
+ dnsDetails,
+ expanded = false,
+ remove,
+ onToggleDns,
+ onSetup,
+ setupRecord,
+ setupMessage,
+}: DomainItemCardProps) {
+ const auth = dns?.auth;
return (
- <div
- key={item.id}
- className="flex flex-col gap-3 rounded-3xl bg-white p-5"
- >
- <div className="flex items-start gap-3">
- <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600">
+ <ListRow className="group relative flex-col items-stretch gap-3">
+ <div className="flex items-start gap-4">
+ <span className="relative flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-neutral-100 text-neutral-600">
<Globe2 className="h-5 w-5" />
+ <img
+ src={`https://${item.hostname}/favicon.ico`}
+ alt=""
+ className="absolute inset-0 h-full w-full object-contain p-1"
+ onError={(event) => event.currentTarget.remove()}
+ />
</span>
- <div className="min-w-0 flex-1">
- <span className="block truncate text-sm font-semibold text-neutral-900">
+
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
+ <span className="min-w-0 truncate pr-10 text-sm font-semibold text-neutral-900">
{item.hostname}
</span>
- <div className="mt-2 flex flex-wrap gap-2">
- <Badge variant={item.status === "active" ? "success" : "secondary"}>
+
+ <div className="flex flex-wrap gap-2">
+ <Badge
+ variant={item.status === "active" ? "success" : "secondary"}
+ className="gap-1"
+ >
+ <StatusIcon ok={item.status === "active"} className="h-3 w-3" />
{item.status}
</Badge>
- {item.routingEnabled && <Badge variant="outline">routing</Badge>}
- {item.sendingEnabled && <Badge variant="outline">sending</Badge>}
+ <Badge
+ variant={item.routingEnabled ? "outline" : "secondary"}
+ className={cn("gap-1", !item.routingEnabled && "opacity-50")}
+ >
+ <StatusIcon ok={item.routingEnabled} className="h-3 w-3" />
+ routing
+ </Badge>
+ <Badge
+ variant={item.sendingEnabled ? "outline" : "secondary"}
+ className={cn("gap-1", !item.sendingEnabled && "opacity-50")}
+ >
+ <StatusIcon ok={item.sendingEnabled} className="h-3 w-3" />
+ sending
+ </Badge>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
+ {auth &&
+ dnsAuthRecords.map((record, index) => (
+ <Fragment key={record}>
+ {index > 0 && <span className="text-neutral-300">|</span>}
+ <span
+ className="flex items-center gap-1 text-neutral-500"
+ title={`${record.toUpperCase()} · ${getDnsAuthStatusLabel(auth[record])}`}
+ >
+ <span className="uppercase">{record}</span>
+ <StatusIcon
+ ok={auth[record] === "ok"}
+ className="h-3.5 w-3.5"
+ />
+ </span>
+ </Fragment>
+ ))}
+ <span className="flex-1" />
+ <button
+ onClick={() => onToggleDns(item.id)}
+ className="flex cursor-pointer items-center gap-0.5 text-xs text-blue-600 hover:text-blue-800"
+ >
+ {expanded ? (
+ <>
+ Hide details <ChevronRight className="h-3 w-3" />
+ </>
+ ) : (
+ <>
+ Show details <ChevronDown className="h-3 w-3" />
+ </>
+ )}
+ </button>
</div>
- </div>
- <div className="flex gap-2">
- <Button variant="outline" size="sm" onClick={() => loadDns(item.id)}>
- DNS
- </Button>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => remove.mutate(item.id)}
- disabled={remove.isPending}
- aria-label={`Remove ${item.hostname}`}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
</div>
</div>
- {dns && (
- <div className="flex flex-wrap items-center gap-3 text-xs">
- <span className="flex items-center gap-1 text-neutral-500">
- Routing{" "}
- {dns.routing.configured ? (
- <Check className="h-3.5 w-3.5 text-green-600" />
- ) : (
- <AlertTriangle className="h-3.5 w-3.5 text-amber-500" />
- )}
- </span>
- {dns.routing.missing.length > 0 && (
- <span className="text-red-600 flex items-center gap-1">
- <X className="h-3 w-3" />
- Missing: {dns.routing.missing.join(", ")}
- </span>
- )}
- <span className="text-neutral-300">|</span>
- <span className="flex items-center gap-1 text-neutral-500">
- Sending{" "}
- {dns.sending.configured ? (
- <Check className="h-3.5 w-3.5 text-green-600" />
- ) : (
- <AlertTriangle className="h-3.5 w-3.5 text-amber-500" />
- )}
- </span>
- {dns.sending.records.length > 0 && (
- <span className="text-neutral-500">
- {dns.sending.records.join(", ")}
- </span>
- )}
- <button
- onClick={() => loadDns(item.id)}
- className="flex items-center gap-0.5 text-blue-600 hover:text-blue-800"
- >
- <ArrowRight className="h-3 w-3" />
- details
- </button>
- </div>
+
+ {expanded && dnsDetails && (
+ <DomainDnsDetails
+ domain={item}
+ dns={dnsDetails}
+ onSetup={onSetup}
+ setupRecord={setupRecord}
+ setupMessage={setupMessage}
+ />
)}
- </div>
+
+ <Button
+ variant="destructive"
+ size="sm"
+ className="absolute right-4 top-4 opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100"
+ onClick={() => remove.mutate(item.id)}
+ disabled={remove.isPending}
+ aria-label={`Remove ${item.hostname}`}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </ListRow>
);
}
diff --git a/src/app/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
index 121a5b3..e91cd42 100644
--- a/src/app/(admin)/domains/page.tsx
+++ b/src/app/(admin)/domains/page.tsx
@@ -14,11 +14,11 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
+import { List } from "@/components/ui/list";
import { CheckCircle2, LoaderCircle, Plus } from "lucide-react";
import { authFetch } from "@/lib/auth/client";
-import type { DnsStatusSummary, Domain, DomainDnsView, DomainPreflight } from "./types";
+import type { DnsAuthRecord, DnsStatusSummary, Domain, DomainDnsView, DomainPreflight } from "./types";
import DomainItemCard from "./DomainItemCard";
-import DomainDnsDetails from "./DomainDnsDetails";
import { SectionRowSkeleton } from "@/components/page-skeletons";
import { checkDomain } from "./utils";
@@ -36,6 +36,8 @@ export default function DomainsPage() {
const [enableSending, setEnableSending] = useState(false);
const [domainCheckError, setDomainCheckError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
+ const [setupRecord, setSetupRecord] = useState<DnsAuthRecord | null>(null);
+ const [setupMessage, setSetupMessage] = useState<string | null>(null);
const [dnsView, setDnsView] = useState<{
domain: Domain;
dns: DomainDnsView;
@@ -103,7 +105,45 @@ export default function DomainsPage() {
const loadDns = async (id: string) => {
const res = await authFetch(`/api/domains/${id}/dns`);
const json = (await res.json()) as { domain: Domain; dns: DomainDnsView };
- if (res.ok) setDnsView(json);
+ if (res.ok) {
+ setDnsView(json);
+ setSetupMessage(null);
+ }
+ };
+
+ const toggleDns = async (id: string) => {
+ if (dnsView?.domain.id === id) {
+ setDnsView(null);
+ setSetupMessage(null);
+ return;
+ }
+ await loadDns(id);
+ };
+
+ const setupDns = async (record: DnsAuthRecord) => {
+ if (!dnsView) return;
+ 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;
+ };
+ if (!res.ok) throw new Error(json.error ?? "Failed to set up DNS record");
+ if (json.domain && json.dns) setDnsView({ domain: json.domain, dns: json.dns });
+ else await loadDns(dnsView.domain.id);
+ qc.invalidateQueries({ queryKey: ["domains"] });
+ } catch (error) {
+ setSetupMessage(error instanceof Error ? error.message : "Failed to set up DNS record");
+ } finally {
+ setSetupRecord(null);
+ }
};
const inspectDomain = async () => {
@@ -245,24 +285,26 @@ export default function DomainsPage() {
No domains yet
</p>
)}
- <div className="grid gap-3">
+ <List>
{(data?.domains ?? []).map((d) => {
const dns = data?.dns?.[d.id];
return (
<DomainItemCard
key={d.id}
dns={dns}
- loadDns={loadDns}
+ dnsDetails={dnsView?.domain.id === d.id ? dnsView.dns : undefined}
+ expanded={dnsView?.domain.id === d.id}
+ onToggleDns={toggleDns}
+ onSetup={setupDns}
+ setupRecord={setupRecord}
+ setupMessage={setupMessage}
item={d}
remove={remove}
/>
);
})}
- </div>
+ </List>
</section>
- {dnsView && (
- <DomainDnsDetails domain={dnsView.domain} dns={dnsView.dns} />
- )}
</div>
);
}
diff --git a/src/app/(admin)/domains/types.d.ts b/src/app/(admin)/domains/types.d.ts
index 89fca8a..2952b31 100644
--- a/src/app/(admin)/domains/types.d.ts
+++ b/src/app/(admin)/domains/types.d.ts
@@ -26,9 +26,24 @@ export type DnsRecord = {
priority?: number;
};
+export type DnsAuthRecord = "mx" | "spf" | "dkim" | "dmarc";
+
+export type DnsAuthStatus = "ok" | "missing" | "unknown";
+
+export type DnsAuthCheck = {
+ record: DnsAuthRecord;
+ label: string;
+ name: string;
+ status: DnsAuthStatus;
+ found: string[];
+};
+
+export type DomainDnsAudit = Record<DnsAuthRecord, DnsAuthCheck>;
+
export type DnsStatusSummary = {
routing: { configured: boolean; missing: string[] };
sending: { configured: boolean; records: string[] };
+ auth?: Record<DnsAuthRecord, DnsAuthStatus>;
};
export type DomainDnsView = {
@@ -39,9 +54,25 @@ export type DomainDnsView = {
};
sending: DnsRecord[];
sendingEnabled: boolean;
+ audit?: DomainDnsAudit;
};
export type DomainDnsDetailsProps = {
domain: Domain;
dns: DomainDnsView;
+ onSetup?: (record: DnsAuthRecord) => void;
+ setupRecord?: DnsAuthRecord | null;
+ setupMessage?: string | null;
+};
+
+export type DomainItemCardProps = {
+ item: Domain;
+ dns?: DnsStatusSummary;
+ dnsDetails?: DomainDnsView;
+ expanded?: boolean;
+ remove: { mutate: (id: string) => void; isPending: boolean };
+ onToggleDns: (id: string) => void;
+ onSetup?: (record: DnsAuthRecord) => void;
+ setupRecord?: DnsAuthRecord | null;
+ setupMessage?: string | null;
};
diff --git a/src/app/(admin)/domains/utils.ts b/src/app/(admin)/domains/utils.ts
index 32ef4f7..123ec33 100644
--- a/src/app/(admin)/domains/utils.ts
+++ b/src/app/(admin)/domains/utils.ts
@@ -1,5 +1,29 @@
import { authFetch } from "@/lib/auth/client";
-import type { DomainPreflightResponse } from "./types";
+import type { DnsAuthRecord, DnsAuthStatus, DomainPreflightResponse } from "./types";
+
+export const dnsAuthRecords: DnsAuthRecord[] = ["mx", "spf", "dkim", "dmarc"];
+
+export function getDnsAuthStatusLabel(status: DnsAuthStatus): string {
+ switch (status) {
+ case "ok":
+ return "found";
+ case "missing":
+ return "missing";
+ default:
+ return "not verified";
+ }
+}
+
+export function getDnsAuthItemClass(status: DnsAuthStatus): string {
+ switch (status) {
+ case "ok":
+ return "bg-green-50 text-green-800";
+ case "missing":
+ return "bg-red-50 text-red-800";
+ default:
+ return "bg-neutral-100 text-neutral-600";
+ }
+}
export async function checkDomain(hostname: string): Promise<DomainPreflightResponse> {
const response = await authFetch("/api/domains/check", {
diff --git a/src/app/(admin)/mailboxes/page.tsx b/src/app/(admin)/mailboxes/page.tsx
index d962499..5250f07 100644
--- a/src/app/(admin)/mailboxes/page.tsx
+++ b/src/app/(admin)/mailboxes/page.tsx
@@ -17,6 +17,7 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
+import { List, ListRow } from "@/components/ui/list";
import { SectionRowSkeleton } from "@/components/page-skeletons";
import { clearMailboxesCache } from "@/components/mailbox-provider-utils";
import { authFetch } from "@/lib/auth/client";
@@ -234,7 +235,7 @@ export default function MailboxesPage() {
No mailboxes yet
</p>
)}
- <div className="divide-y divide-neutral-100 overflow-hidden rounded-3xl bg-white">
+ <List>
{(mailboxes.data?.mailboxes ?? []).map((mailbox) => {
const mailboxWithHostname = {
...mailbox,
@@ -242,42 +243,43 @@ export default function MailboxesPage() {
};
return (
- <Link
- key={mailbox.id}
- href={`/mailboxes/${mailbox.id}`}
- className="group flex items-center gap-4 px-5 py-4 transition-colors hover:bg-blue-50/40"
- >
- <span className="relative flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-blue-100 text-sm font-semibold text-blue-700">
- {getMailboxName(mailboxWithHostname).trim().charAt(0).toUpperCase() || "?"}
- {mailbox.hasAvatar && (
- <img
- src={`/api/mailboxes/${mailbox.id}/avatar`}
- alt={`${getMailboxName(mailboxWithHostname)} profile`}
- className="absolute inset-0 h-full w-full object-cover"
- onError={(event) => event.currentTarget.remove()}
- />
- )}
- </span>
- <span className="min-w-0">
- <span className="flex min-w-0 items-center gap-2">
- <span className="block truncate text-sm font-semibold text-neutral-900">
- {getMailboxName(mailboxWithHostname)}
- </span>
- {mailbox.type === "shared" && (
- <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">
- <UsersRound className="h-3 w-3" />
- Shared
- </span>
+ <ListRow key={mailbox.id} asChild>
+ <Link
+ href={`/mailboxes/${mailbox.id}`}
+ className="group px-5 py-4 transition-colors hover:bg-blue-50/40"
+ >
+ <span className="relative flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-blue-100 text-sm font-semibold text-blue-700">
+ {getMailboxName(mailboxWithHostname).trim().charAt(0).toUpperCase() || "?"}
+ {mailbox.hasAvatar && (
+ <img
+ src={`/api/mailboxes/${mailbox.id}/avatar`}
+ alt={`${getMailboxName(mailboxWithHostname)} profile`}
+ className="absolute inset-0 h-full w-full object-cover"
+ onError={(event) => event.currentTarget.remove()}
+ />
)}
</span>
- <span className="block truncate no-font-mono text-sm text-neutral-500">
- {getMailboxAddress(mailboxWithHostname)}
+ <span className="min-w-0">
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="block truncate text-sm font-semibold text-neutral-900">
+ {getMailboxName(mailboxWithHostname)}
+ </span>
+ {mailbox.type === "shared" && (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">
+ <UsersRound className="h-3 w-3" />
+ Shared
+ </span>
+ )}
+ </span>
+ <span className="block truncate no-font-mono text-sm text-neutral-500">
+ {getMailboxAddress(mailboxWithHostname)}
+ </span>
</span>
- </span>
- </Link>
+ </Link>
+ </ListRow>
);
})}
- </div>
+ </List>
</section>
</div>
);
diff --git a/src/app/api/api-keys/route.ts b/src/app/api/api-keys/route.ts
index 3645543..b689a88 100644
--- a/src/app/api/api-keys/route.ts
+++ b/src/app/api/api-keys/route.ts
@@ -6,11 +6,12 @@ import { getDb } from "@/db";
import { apiKeys } from "@/db/schema";
import { requireUser } from "@/lib/auth/cookies";
import { generateApiKey, scopesToJson } from "@/lib/api-keys";
+import { API_KEY_SCOPES } from "@/lib/api/scopes";
import { newId } from "@/lib/ids";
const createKeySchema = z.object({
name: z.string().min(1),
- scopes: z.array(z.enum(["send", "read", "jmap"])).min(1),
+ scopes: z.array(z.enum([...API_KEY_SCOPES])).min(1),
});
export async function GET(request: Request) {
diff --git a/src/app/api/domains/[id]/dns/route.ts b/src/app/api/domains/[id]/dns/route.ts
index 7eaa568..0a2e905 100644
--- a/src/app/api/domains/[id]/dns/route.ts
+++ b/src/app/api/domains/[id]/dns/route.ts
@@ -1,7 +1,8 @@
import { NextResponse } from "next/server";
import { getEnv } from "@/lib/cloudflare";
import { requireUser } from "@/lib/auth/cookies";
-import { getDomainDns, getDomainForUser } from "@/lib/domains/service";
+import { getDomainForUser } from "@/lib/domains/service";
+import { getDomainDnsView } from "@/lib/domains/dns-view";
type Params = { params: Promise<{ id: string }> };
@@ -13,7 +14,7 @@ export async function GET(request: Request, { params }: Params) {
if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
try {
- const dns = await getDomainDns(env, domain);
+ const dns = await getDomainDnsView(env, domain);
return NextResponse.json({
domain: { ...domain, sendingEnabled: dns.sendingEnabled },
dns,
diff --git a/src/app/api/domains/[id]/dns/setup/route.ts b/src/app/api/domains/[id]/dns/setup/route.ts
new file mode 100644
index 0000000..bead730
--- /dev/null
+++ b/src/app/api/domains/[id]/dns/setup/route.ts
@@ -0,0 +1,45 @@
+import { NextResponse } from "next/server";
+import { eq } from "drizzle-orm";
+import { getEnv } from "@/lib/cloudflare";
+import { getDb } from "@/db";
+import { domains } from "@/db/schema";
+import { requireUser } from "@/lib/auth/cookies";
+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";
+
+type Params = { params: Promise<{ id: string }> };
+
+const DNS_RECORDS: DnsAuthRecord[] = ["mx", "spf", "dkim", "dmarc"];
+
+export async function POST(request: Request, { params }: Params) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const domain = await getDomainForUser(env, user.id, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+
+ const body = (await request.json().catch(() => ({}))) as { record?: string };
+ 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);
+ const dns = await getDomainDnsView(env, domain);
+ const [updated] = await getDb(env)
+ .select()
+ .from(domains)
+ .where(eq(domains.id, domain.id))
+ .limit(1);
+ return NextResponse.json({
+ domain: { ...(updated ?? domain), sendingEnabled: dns.sendingEnabled },
+ dns,
+ });
+ } catch (err) {
+ 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/route.ts b/src/app/api/domains/route.ts
index d6becde..a24700b 100644
--- a/src/app/api/domains/route.ts
+++ b/src/app/api/domains/route.ts
@@ -2,8 +2,9 @@ import { NextRequest, NextResponse } from "next/server";
import { getEnv } from "@/lib/cloudflare";
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 { addDomainForUser, listUserDomains } from "@/lib/domains/service";
+import type { DnsStatusSummary } from "@/lib/dns-status";
+import { summariseDomainDns } from "@/lib/domains/dns-view";
import { getDomainProvisioningError } from "@/lib/domains/errors";
export async function GET(request: NextRequest) {
@@ -14,23 +15,13 @@ export async function GET(request: NextRequest) {
const includeDns = request.nextUrl.searchParams.get("includeDns") === "true";
- let dns: Record<string, DnsStatusSummary> = {};
+ const dns: Record<string, DnsStatusSummary> = {};
let domainViews = domains;
if (includeDns) {
const results = await Promise.allSettled(
domains.map(async (domain) => {
- const view = await getDomainDns(env, domain);
- return {
- id: domain.id,
- summary: summariseDns(
- view.routing.records,
- view.routing.missing,
- view.sending,
- domain.routingEnabled,
- view.sendingEnabled,
- ),
- sendingEnabled: view.sendingEnabled,
- };
+ const { summary, sendingEnabled } = await summariseDomainDns(env, domain);
+ return { id: domain.id, summary, sendingEnabled };
}),
);
const sendingEnabledByDomain = new Map<string, boolean>();
diff --git a/src/app/api/v1/domains/[id]/dns/route.ts b/src/app/api/v1/domains/[id]/dns/route.ts
new file mode 100644
index 0000000..75b1916
--- /dev/null
+++ b/src/app/api/v1/domains/[id]/dns/route.ts
@@ -0,0 +1,30 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { authenticateApiKey, requireScope } from "@/lib/api/auth";
+import { getDomainForUser } from "@/lib/domains/service";
+import { getDomainDnsView } from "@/lib/domains/dns-view";
+
+type Params = { params: Promise<{ id: string }> };
+
+export async function GET(request: Request, { params }: Params) {
+ const env = getEnv();
+ const auth = await authenticateApiKey(env, request.headers.get("authorization"));
+ if (!auth || !requireScope(auth.scopes, "domains")) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const { id } = await params;
+ const domain = await getDomainForUser(env, auth.userId, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+
+ try {
+ const dns = await getDomainDnsView(env, domain);
+ return NextResponse.json({
+ domain: { ...domain, sendingEnabled: dns.sendingEnabled },
+ dns,
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : "Failed to fetch DNS";
+ return NextResponse.json({ error: message }, { status: 500 });
+ }
+}
diff --git a/src/app/api/v1/domains/[id]/dns/setup/route.ts b/src/app/api/v1/domains/[id]/dns/setup/route.ts
new file mode 100644
index 0000000..7ce3b71
--- /dev/null
+++ b/src/app/api/v1/domains/[id]/dns/setup/route.ts
@@ -0,0 +1,49 @@
+import { NextResponse } from "next/server";
+import { eq } from "drizzle-orm";
+import { getEnv } from "@/lib/cloudflare";
+import { getDb } from "@/db";
+import { domains } from "@/db/schema";
+import { authenticateApiKey, requireScope } from "@/lib/api/auth";
+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";
+
+type Params = { params: Promise<{ id: string }> };
+
+const DNS_RECORDS: DnsAuthRecord[] = ["mx", "spf", "dkim", "dmarc"];
+
+export async function POST(request: Request, { params }: Params) {
+ const env = getEnv();
+ const auth = await authenticateApiKey(env, request.headers.get("authorization"));
+ if (!auth || !requireScope(auth.scopes, "domains")) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const { id } = await 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 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);
+ const dns = await getDomainDnsView(env, domain);
+ const [updated] = await getDb(env)
+ .select()
+ .from(domains)
+ .where(eq(domains.id, domain.id))
+ .limit(1);
+ return NextResponse.json({
+ domain: { ...(updated ?? domain), sendingEnabled: dns.sendingEnabled },
+ dns,
+ });
+ } catch (err) {
+ 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/v1/domains/[id]/route.ts b/src/app/api/v1/domains/[id]/route.ts
new file mode 100644
index 0000000..a8c4bd4
--- /dev/null
+++ b/src/app/api/v1/domains/[id]/route.ts
@@ -0,0 +1,37 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { authenticateApiKey, requireScope } from "@/lib/api/auth";
+import { getDomainForUser, removeDomainForUser } from "@/lib/domains/service";
+
+type Params = { params: Promise<{ id: string }> };
+
+async function authorize(request: Request) {
+ const env = getEnv();
+ const auth = await authenticateApiKey(env, request.headers.get("authorization"));
+ if (!auth || !requireScope(auth.scopes, "domains")) return null;
+ return auth;
+}
+
+export async function GET(request: Request, { params }: Params) {
+ const auth = await authorize(request);
+ if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const { id } = await params;
+ const domain = await getDomainForUser(getEnv(), auth.userId, id);
+ if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
+ return NextResponse.json({ domain });
+}
+
+export async function DELETE(request: Request, { params }: Params) {
+ const auth = await authorize(request);
+ if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const { id } = await params;
+ try {
+ await removeDomainForUser(getEnv(), auth.userId, id);
+ return NextResponse.json({ ok: true });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : "Failed to remove domain";
+ return NextResponse.json({ error: message }, { status: 400 });
+ }
+}
diff --git a/src/app/api/v1/domains/route.ts b/src/app/api/v1/domains/route.ts
new file mode 100644
index 0000000..7cd1d25
--- /dev/null
+++ b/src/app/api/v1/domains/route.ts
@@ -0,0 +1,69 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { authenticateApiKey, requireScope } from "@/lib/api/auth";
+import { addDomainSchema } from "@/lib/validators";
+import { addDomainForUser, listUserDomains } from "@/lib/domains/service";
+import { getDomainDnsView, summariseDomainDns } from "@/lib/domains/dns-view";
+import { getDomainProvisioningError } from "@/lib/domains/errors";
+import type { DnsStatusSummary } from "@/lib/dns-status";
+
+function ownerId(user: { id: string; canManageMailboxes: boolean; createdByUserId: string | null }) {
+ return user.canManageMailboxes && user.createdByUserId ? user.createdByUserId : user.id;
+}
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const auth = await authenticateApiKey(env, request.headers.get("authorization"));
+ if (!auth || !requireScope(auth.scopes, "domains")) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const domains = await listUserDomains(env, ownerId(auth.user));
+ const results = await Promise.allSettled(
+ domains.map((domain) => summariseDomainDns(env, domain)),
+ );
+
+ const dns: Record<string, DnsStatusSummary> = {};
+ const domainViews = domains.map((domain, index) => {
+ const result = results[index];
+ if (result.status !== "fulfilled") return domain;
+ dns[domain.id] = result.value.summary;
+ return { ...domain, sendingEnabled: result.value.sendingEnabled };
+ });
+
+ return NextResponse.json({ domains: domainViews, dns });
+}
+
+export async function POST(request: Request) {
+ const env = getEnv();
+ const auth = await authenticateApiKey(env, request.headers.get("authorization"));
+ if (!auth || !requireScope(auth.scopes, "domains")) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const parsed = addDomainSchema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
+ }
+
+ try {
+ const result = await addDomainForUser(env, auth.userId, parsed.data.hostname, {
+ enableRouting: parsed.data.enableRouting,
+ enableSending: parsed.data.enableSending,
+ replaceMxRecords: parsed.data.replaceMxRecords,
+ });
+ let dns = result.dns;
+ try {
+ dns = await getDomainDnsView(env, result.domain);
+ } catch (error) {
+ console.warn("v1 addDomain: failed to read DNS after provisioning", error);
+ }
+ return NextResponse.json({ ...result, dns });
+ } catch (err) {
+ const failure = getDomainProvisioningError(err, "Failed to add domain");
+ return NextResponse.json(
+ { error: failure.message, code: failure.code },
+ { status: failure.status },
+ );
+ }
+}
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 62bb1ce..25212ab 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -28,14 +28,14 @@ const buttonVariants = cva(
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
- VariantProps<typeof buttonVariants> {
+ VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
- return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
+ return <Comp className={cn('cursor-pointer', buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
},
);
Button.displayName = "Button";
diff --git a/src/components/ui/list.tsx b/src/components/ui/list.tsx
new file mode 100644
index 0000000..d479d60
--- /dev/null
+++ b/src/components/ui/list.tsx
@@ -0,0 +1,29 @@
+import * as React from "react";
+import { Slot } from "@radix-ui/react-slot";
+import { cn } from "@/lib/utils";
+
+export function List({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
+ return (
+ <div
+ className={cn(
+ "grid gap-1 [&>*:first-child]:rounded-t-3xl [&>*:last-child]:rounded-b-3xl",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export interface ListRowProps extends React.HTMLAttributes<HTMLElement> {
+ asChild?: boolean;
+}
+
+export function ListRow({ className, asChild = false, ...props }: ListRowProps) {
+ const Comp: React.ElementType = asChild ? Slot : "div";
+ return (
+ <Comp
+ className={cn("flex items-center gap-4 rounded-lg bg-white p-5", className)}
+ {...props}
+ />
+ );
+}
diff --git a/src/lib/api/scopes.ts b/src/lib/api/scopes.ts
new file mode 100644
index 0000000..b09896d
--- /dev/null
+++ b/src/lib/api/scopes.ts
@@ -0,0 +1,8 @@
+/**
+ * Scopes an API key can be granted. Kept free of server-only imports so the
+ * dashboard's key-creation form can import it without pulling in bcrypt.
+ * `domains` covers the `/api/v1/domains` admin surface.
+ */
+export const API_KEY_SCOPES = ["send", "read", "jmap", "domains"] as const;
+
+export type ApiKeyScope = (typeof API_KEY_SCOPES)[number];
diff --git a/src/lib/cloudflare-api.ts b/src/lib/cloudflare-api.ts
index 4171855..2cdb610 100644
--- a/src/lib/cloudflare-api.ts
+++ b/src/lib/cloudflare-api.ts
@@ -42,6 +42,13 @@ export async function cfRequest<T>(
return json.result;
}
+export async function getZone(
+ env: CloudflareEnv,
+ zoneId: string,
+): Promise<{ id: string; name: string }> {
+ return cfRequest<{ id: string; name: string }>(env, `/zones/${zoneId}`);
+}
+
export async function findZoneByHostname(
env: CloudflareEnv,
hostname: string,
diff --git a/src/lib/cloudflare-dns.ts b/src/lib/cloudflare-dns.ts
index 320b6ac..312cd5e 100644
--- a/src/lib/cloudflare-dns.ts
+++ b/src/lib/cloudflare-dns.ts
@@ -13,6 +13,17 @@ export async function listMxRecords(
);
}
+export async function listDnsRecords(
+ env: CloudflareEnv,
+ zoneId: string,
+ params: { type: string; name: string },
+): Promise<CfDnsRecord[]> {
+ return cfRequest<CfDnsRecord[]>(
+ env,
+ `/zones/${zoneId}/dns_records?type=${encodeURIComponent(params.type)}&name=${encodeURIComponent(params.name)}&per_page=5000`,
+ );
+}
+
export async function deleteDnsRecord(
env: CloudflareEnv,
zoneId: string,
diff --git a/src/lib/cloudflare-dns.types.d.ts b/src/lib/cloudflare-dns.types.d.ts
index 192c3c8..124acac 100644
--- a/src/lib/cloudflare-dns.types.d.ts
+++ b/src/lib/cloudflare-dns.types.d.ts
@@ -1,10 +1,19 @@
-export type CloudflareDnsRecordCreate = {
- type: "MX";
- name: string;
- content: string;
- priority: number;
- ttl: number;
- proxied?: boolean;
- comment?: string;
- tags?: string[];
-};
+export type CloudflareDnsRecordCreate =
+ | {
+ type: "MX";
+ name: string;
+ content: string;
+ priority: number;
+ ttl: number;
+ proxied?: boolean;
+ comment?: string;
+ tags?: string[];
+ }
+ | {
+ type: "TXT";
+ name: string;
+ content: string;
+ ttl: number;
+ comment?: string;
+ tags?: string[];
+ };
diff --git a/src/lib/dns-query.ts b/src/lib/dns-query.ts
new file mode 100644
index 0000000..cb5314e
--- /dev/null
+++ b/src/lib/dns-query.ts
@@ -0,0 +1,54 @@
+export type DnsQueryType = "MX" | "TXT" | "A" | "AAAA" | "CNAME";
+
+type DohAnswer = {
+ name: string;
+ type: number;
+ TTL: number;
+ data: string;
+};
+
+type DohResponse = {
+ Status: number;
+ Answer?: DohAnswer[];
+};
+
+const DOH_ENDPOINT = "https://cloudflare-dns.com/dns-query";
+const DOH_TIMEOUT_MS = 5000;
+
+function decodeTxt(data: string): string {
+ const chunks = data.match(/"([^"]*)"/g);
+ if (!chunks) return data.trim();
+ return chunks.map((chunk) => chunk.slice(1, -1)).join("");
+}
+
+/**
+ * Resolves a name over DNS-over-HTTPS so the same code path works on Workers
+ * (no Node `dns` module) and in the self-hosted runtime. `NXDOMAIN` and an
+ * empty `NOERROR` answer both map to an empty list; any other failure throws so
+ * callers can tell "missing" apart from "could not check".
+ */
+export async function queryDns(name: string, type: DnsQueryType): Promise<string[]> {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), DOH_TIMEOUT_MS);
+ try {
+ const response = await fetch(
+ `${DOH_ENDPOINT}?name=${encodeURIComponent(name)}&type=${type}`,
+ {
+ headers: { accept: "application/dns-json" },
+ signal: controller.signal,
+ },
+ );
+ if (!response.ok) {
+ throw new Error(`DNS query for ${name} ${type} failed (${response.status})`);
+ }
+ const json = (await response.json()) as DohResponse;
+ if (json.Status !== 0 && json.Status !== 3) {
+ throw new Error(`DNS query for ${name} ${type} returned status ${json.Status}`);
+ }
+ return (json.Answer ?? []).map((answer) =>
+ type === "TXT" ? decodeTxt(answer.data) : answer.data,
+ );
+ } finally {
+ clearTimeout(timeout);
+ }
+}
diff --git a/src/lib/dns-status.ts b/src/lib/dns-status.ts
index 8756c37..e8a819a 100644
--- a/src/lib/dns-status.ts
+++ b/src/lib/dns-status.ts
@@ -1,4 +1,7 @@
import type { CfDnsRecord } from "@/lib/cloudflare-api";
+import type { DnsAuthRecord, DnsAuthStatus, DomainDnsAudit } from "@/lib/domains/dns-audit";
+
+export type DnsAuthSummary = Record<DnsAuthRecord, DnsAuthStatus>;
export type DnsStatusSummary = {
routing: {
@@ -9,6 +12,7 @@ export type DnsStatusSummary = {
configured: boolean;
records: string[];
};
+ auth?: DnsAuthSummary;
};
export function summariseDns(
@@ -17,6 +21,7 @@ export function summariseDns(
sendingRecords: CfDnsRecord[],
routingEnabled = false,
sendingEnabled?: boolean,
+ audit?: DomainDnsAudit,
): DnsStatusSummary {
const recordTypes = (
type: "routing-records" | "routing-missing" | "sending",
@@ -39,5 +44,13 @@ export function summariseDns(
configured: sendingEnabled ?? sendingRecords.length > 0,
records: recordTypes("sending"),
},
+ auth: audit
+ ? {
+ mx: audit.mx.status,
+ spf: audit.spf.status,
+ dkim: audit.dkim.status,
+ dmarc: audit.dmarc.status,
+ }
+ : undefined,
};
}
diff --git a/src/lib/domains/dns-audit.ts b/src/lib/domains/dns-audit.ts
new file mode 100644
index 0000000..b3fc640
--- /dev/null
+++ b/src/lib/domains/dns-audit.ts
@@ -0,0 +1,80 @@
+import type { CfDnsRecord } from "@/lib/cloudflare-api.types";
+import { queryDns, type DnsQueryType } from "@/lib/dns-query";
+
+export type DnsAuthRecord = "mx" | "spf" | "dkim" | "dmarc";
+export type DnsAuthStatus = "ok" | "missing" | "unknown";
+
+export type DnsAuthCheck = {
+ record: DnsAuthRecord;
+ label: string;
+ name: string;
+ status: DnsAuthStatus;
+ found: string[];
+};
+
+export type DomainDnsAudit = {
+ mx: DnsAuthCheck;
+ spf: DnsAuthCheck;
+ dkim: DnsAuthCheck;
+ dmarc: DnsAuthCheck;
+};
+
+type AuditInput = {
+ routing: { records: CfDnsRecord[]; missing: CfDnsRecord[] };
+ sending: CfDnsRecord[];
+};
+
+function isTxt(record: CfDnsRecord) {
+ return record.type?.toUpperCase() === "TXT";
+}
+
+async function check(
+ record: DnsAuthRecord,
+ label: string,
+ name: string,
+ type: DnsQueryType,
+ matches: (value: string) => boolean,
+): Promise<DnsAuthCheck> {
+ try {
+ const answers = await queryDns(name, type);
+ const found = answers.filter(matches);
+ return { record, label, name, status: found.length > 0 ? "ok" : "missing", found };
+ } catch {
+ return { record, label, name, status: "unknown", found: [] };
+ }
+}
+
+/**
+ * Independently verifies the public DNS a domain needs, rather than trusting
+ * the zone records the Cloudflare API reports. MX, SPF and DMARC are checked at
+ * their canonical names; DKIM uses the selector the sending subdomain was
+ * provisioned with. A name that resolves is "ok", one that answers NXDOMAIN is
+ * "missing", and a lookup that fails outright is "unknown".
+ */
+export async function auditDomainDns(
+ hostname: string,
+ view: AuditInput,
+): Promise<DomainDnsAudit> {
+ const expected = [...view.routing.records, ...view.routing.missing, ...view.sending];
+ const dkimName = expected.find(
+ (record) => isTxt(record) && /_domainkey/i.test(record.name ?? ""),
+ )?.name;
+
+ const [mx, spf, dmarc] = await Promise.all([
+ check("mx", "MX", hostname, "MX", (value) => !/^0\s*\.?$/.test(value.trim())),
+ check("spf", "SPF", hostname, "TXT", (value) => /v=spf1/i.test(value)),
+ check("dmarc", "DMARC", `_dmarc.${hostname}`, "TXT", (value) => /v=DMARC1/i.test(value)),
+ ]);
+
+ const dkim: DnsAuthCheck = dkimName
+ ? await check("dkim", "DKIM", dkimName, "TXT", () => true)
+ : {
+ record: "dkim",
+ label: "DKIM",
+ name: `*._domainkey.${hostname}`,
+ status: "unknown",
+ found: [],
+ };
+
+ return { mx, spf, dkim, dmarc };
+}
diff --git a/src/lib/domains/dns-setup.ts b/src/lib/domains/dns-setup.ts
new file mode 100644
index 0000000..8a7fd0b
--- /dev/null
+++ b/src/lib/domains/dns-setup.ts
@@ -0,0 +1,79 @@
+import { eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { domains } from "@/db/schema";
+import {
+ createSendingSubdomain,
+ 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";
+import {
+ isManualZone,
+ shouldBindEmailCatchAllToWorker,
+} from "@/lib/domains/provision";
+import type { DomainRow } from "@/lib/domains/types";
+import { isZoneApex } from "@/lib/domains/utils";
+
+/**
+ * Provisions the DNS a single authentication check is missing, reusing the same
+ * 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.
+ */
+export async function setupDomainDnsRecord(
+ env: CloudflareEnv,
+ domain: DomainRow,
+ record: DnsAuthRecord,
+): Promise<void> {
+ if (isManualZone(domain.zoneId)) {
+ throw new Error("DNS for this domain is managed manually");
+ }
+
+ switch (record) {
+ case "mx":
+ case "spf": {
+ const zone = await getZone(env, domain.zoneId);
+ const routingName = isZoneApex(domain.hostname, zone.name) ? undefined : domain.hostname;
+ const result = await enableEmailRouting(env, domain.zoneId, routingName);
+ if (shouldBindEmailCatchAllToWorker(env)) {
+ await ensureEmailRoutingCatchAllToWorker(env, domain.zoneId);
+ }
+ await getDb(env)
+ .update(domains)
+ .set({
+ routingEnabled: result.enabled ?? true,
+ routingStatus: result.status ?? domain.routingStatus,
+ })
+ .where(eq(domains.id, domain.id));
+ return;
+ }
+ case "dkim": {
+ if (domain.sendingSubdomainTag) return;
+ const created = await createSendingSubdomain(env, domain.zoneId, domain.hostname);
+ await getDb(env)
+ .update(domains)
+ .set({
+ sendingSubdomainTag: created.tag,
+ sendingEnabled: created.enabled,
+ sendingRequested: true,
+ })
+ .where(eq(domains.id, domain.id));
+ return;
+ }
+ case "dmarc": {
+ const name = `_dmarc.${domain.hostname}`;
+ const existing = await listDnsRecords(env, domain.zoneId, { type: "TXT", name });
+ if (existing.some((item) => /v=dmarc1/i.test(item.content ?? ""))) return;
+ await createDnsRecord(env, domain.zoneId, {
+ type: "TXT",
+ name,
+ content: "v=DMARC1; p=none",
+ ttl: 3600,
+ });
+ return;
+ }
+ }
+}
diff --git a/src/lib/domains/dns-view.ts b/src/lib/domains/dns-view.ts
new file mode 100644
index 0000000..3222e09
--- /dev/null
+++ b/src/lib/domains/dns-view.ts
@@ -0,0 +1,36 @@
+import { summariseDns, type DnsStatusSummary } from "@/lib/dns-status";
+import { auditDomainDns, type DomainDnsAudit } from "@/lib/domains/dns-audit";
+import { getDomainDns, type DomainDnsView } from "@/lib/domains/service";
+import type { DomainRow } from "@/lib/domains/types";
+
+export type DomainDnsViewWithAudit = DomainDnsView & { audit: DomainDnsAudit };
+
+/** The DNS page's view: zone records plus an independent public-DNS audit. */
+export async function getDomainDnsView(
+ env: CloudflareEnv,
+ domain: DomainRow,
+): Promise<DomainDnsViewWithAudit> {
+ const dns = await getDomainDns(env, domain);
+ const audit = await auditDomainDns(domain.hostname, dns);
+ return { ...dns, audit };
+}
+
+/** The compact per-domain status the list endpoint returns. */
+export async function summariseDomainDns(
+ env: CloudflareEnv,
+ domain: DomainRow,
+): Promise<{ summary: DnsStatusSummary; sendingEnabled: boolean }> {
+ const view = await getDomainDns(env, domain);
+ const audit = await auditDomainDns(domain.hostname, view);
+ return {
+ summary: summariseDns(
+ view.routing.records,
+ view.routing.missing,
+ view.sending,
+ domain.routingEnabled,
+ view.sendingEnabled,
+ audit,
+ ),
+ sendingEnabled: view.sendingEnabled,
+ };
+}