Skip to content

Email for professionals and teams

feat(routing): catch-all, forwarding, and reject rules with priorities

Oday Bakkour32d019303c7e
diff --git a/src/app/(admin)/routing/page.tsx b/src/app/(admin)/routing/page.tsx
index 4a3d555..6883a65 100644
--- a/src/app/(admin)/routing/page.tsx
+++ b/src/app/(admin)/routing/page.tsx
@@ -1,5 +1,447 @@
-import { redirect } from "next/navigation";
+"use client";
+
+import { useMemo, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Ban, Forward, Inbox, Pencil, Plus, Trash2 } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { CardGridSkeleton } from "@/components/page-skeletons";
+import type { DomainRule, DomainRuleInput } from "./types";
+import {
+ ACTION_LABELS,
+ MATCH_FIELD_LABELS,
+ MATCH_OPERATOR_LABELS,
+ createDomainRule,
+ deleteDomainRule,
+ describeRule,
+ emptyRuleInput,
+ fetchDomainRules,
+ fetchRoutingDomains,
+ formatLastMatched,
+ ruleToInput,
+ updateDomainRule,
+} from "./utils";
+
+const ACTION_ICONS = {
+ store: Inbox,
+ forward: Forward,
+ reject: Ban,
+} as const;
export default function RoutingPage() {
- redirect("/settings");
+ const qc = useQueryClient();
+ const [selectedDomainId, setSelectedDomainId] = useState("");
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [editing, setEditing] = useState<DomainRule | null>(null);
+ const [form, setForm] = useState<DomainRuleInput>(emptyRuleInput(""));
+ const [error, setError] = useState<string | null>(null);
+
+ const domains = useQuery({ queryKey: ["routing-domains"], queryFn: fetchRoutingDomains });
+
+ // Derive the active domain rather than syncing it in an effect: until the operator picks one,
+ // it is simply the first domain that loaded.
+ const domainId = selectedDomainId || (domains.data?.[0]?.id ?? "");
+
+ const rules = useQuery({
+ queryKey: ["domain-rules", domainId],
+ enabled: !!domainId,
+ queryFn: () => fetchDomainRules(domainId),
+ });
+
+ const hostname = useMemo(
+ () => domains.data?.find((d) => d.id === domainId)?.hostname ?? "",
+ [domains.data, domainId],
+ );
+ const mailboxes = rules.data?.mailboxes ?? [];
+
+ const save = useMutation({
+ mutationFn: () => {
+ const payload: DomainRuleInput = { ...form, domainId };
+ return editing ? updateDomainRule(editing.id, payload) : createDomainRule(payload);
+ },
+ onSuccess: () => {
+ setDialogOpen(false);
+ setEditing(null);
+ setError(null);
+ qc.invalidateQueries({ queryKey: ["domain-rules", domainId] });
+ },
+ onError: (e: Error) => setError(e.message),
+ });
+
+ const remove = useMutation({
+ mutationFn: deleteDomainRule,
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["domain-rules", domainId] }),
+ });
+
+ const toggle = useMutation({
+ mutationFn: (rule: DomainRule) =>
+ updateDomainRule(rule.id, { ...ruleToInput(rule), enabled: !rule.enabled }),
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["domain-rules", domainId] }),
+ });
+
+ function openCreate() {
+ setEditing(null);
+ setError(null);
+ setForm(emptyRuleInput(domainId));
+ setDialogOpen(true);
+ }
+
+ function openEdit(rule: DomainRule) {
+ setEditing(rule);
+ setError(null);
+ setForm(ruleToInput(rule));
+ setDialogOpen(true);
+ }
+
+ const blockRules = (rules.data?.rules ?? []).filter((r) => r.action === "reject");
+ const fallbackRules = (rules.data?.rules ?? []).filter((r) => r.action !== "reject");
+
+ return (
+ <div className="space-y-6">
+ <div className="flex flex-wrap items-end justify-between gap-4">
+ <div>
+ <h1 className="text-2xl font-semibold">Routing</h1>
+ <p className="mt-1 text-sm text-neutral-500">
+ Catch-all, forwarding, and block rules applied to mail arriving on a domain.
+ </p>
+ </div>
+ <div className="flex items-end gap-2">
+ <div className="space-y-1">
+ <Label htmlFor="routing-domain">Domain</Label>
+ <Select
+ id="routing-domain"
+ value={domainId}
+ onChange={(e) => setSelectedDomainId(e.target.value)}
+ className="h-9"
+ >
+ {(domains.data ?? []).map((domain) => (
+ <option key={domain.id} value={domain.id}>
+ {domain.hostname}
+ </option>
+ ))}
+ </Select>
+ </div>
+ <Button onClick={openCreate} disabled={!domainId}>
+ <Plus className="h-4 w-4" /> Add rule
+ </Button>
+ </div>
+ </div>
+
+ <Card>
+ <CardContent className="pt-6 text-sm text-neutral-600">
+ <p className="font-medium text-neutral-900">How these rules are applied</p>
+ <ol className="mt-2 list-decimal space-y-1 pl-5">
+ <li>Block rules run first and can reject a message before any mailbox is matched.</li>
+ <li>A real mailbox on the domain always wins over a catch-all.</li>
+ <li>
+ Remaining catch-all and forwarding rules run only when no mailbox matched, highest
+ priority first.
+ </li>
+ </ol>
+ <p className="mt-2">
+ Forwarding destinations must be verified destination addresses in Cloudflare Email
+ Routing.
+ </p>
+ </CardContent>
+ </Card>
+
+ {domains.isLoading || rules.isLoading ? (
+ <CardGridSkeleton />
+ ) : !domains.data?.length ? (
+ <Card>
+ <CardContent className="pt-6 text-sm text-neutral-500">
+ Add a domain before creating routing rules.
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="space-y-6">
+ <RuleSection
+ title="Block rules"
+ description="Evaluated before delivery. Matching mail is rejected at the edge."
+ rules={blockRules}
+ hostname={hostname}
+ mailboxes={mailboxes}
+ onEdit={openEdit}
+ onDelete={(id) => remove.mutate(id)}
+ onToggle={(rule) => toggle.mutate(rule)}
+ />
+ <RuleSection
+ title="Catch-all and forwarding"
+ description="Evaluated only when no mailbox on the domain matched the recipient."
+ rules={fallbackRules}
+ hostname={hostname}
+ mailboxes={mailboxes}
+ onEdit={openEdit}
+ onDelete={(id) => remove.mutate(id)}
+ onToggle={(rule) => toggle.mutate(rule)}
+ />
+ </div>
+ )}
+
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ {/* The form grows when the action changes, so the dialog must scroll rather than overflow the viewport. */}
+ <DialogContent className="max-h-[calc(100vh-4rem)] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle>{editing ? "Edit rule" : "Add routing rule"}</DialogTitle>
+ <DialogDescription>
+ Rules run in descending priority order within their phase.
+ </DialogDescription>
+ </DialogHeader>
+
+ <form
+ className="space-y-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ save.mutate();
+ }}
+ >
+ <div className="space-y-2">
+ <Label htmlFor="rule-name">Name</Label>
+ <Input
+ id="rule-name"
+ value={form.name ?? ""}
+ placeholder="Optional label"
+ onChange={(e) => setForm({ ...form, name: e.target.value })}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="rule-action">Action</Label>
+ <Select
+ id="rule-action"
+ value={form.action}
+ onChange={(e) =>
+ setForm({ ...form, action: e.target.value as DomainRuleInput["action"] })
+ }
+ >
+ {Object.entries(ACTION_LABELS).map(([value, label]) => (
+ <option key={value} value={value}>
+ {label}
+ </option>
+ ))}
+ </Select>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-2">
+ <Label htmlFor="rule-field">Match on</Label>
+ <Select
+ id="rule-field"
+ value={form.matchField}
+ onChange={(e) =>
+ setForm({ ...form, matchField: e.target.value as DomainRuleInput["matchField"] })
+ }
+ >
+ {Object.entries(MATCH_FIELD_LABELS).map(([value, label]) => (
+ <option key={value} value={value}>
+ {label}
+ </option>
+ ))}
+ </Select>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="rule-operator">Condition</Label>
+ <Select
+ id="rule-operator"
+ value={form.matchOperator}
+ onChange={(e) =>
+ setForm({
+ ...form,
+ matchOperator: e.target.value as DomainRuleInput["matchOperator"],
+ })
+ }
+ >
+ {Object.entries(MATCH_OPERATOR_LABELS).map(([value, label]) => (
+ <option key={value} value={value}>
+ {label}
+ </option>
+ ))}
+ </Select>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="rule-value">Value</Label>
+ <Input
+ id="rule-value"
+ required
+ value={form.matchValue}
+ placeholder="* to match everything"
+ onChange={(e) => setForm({ ...form, matchValue: e.target.value })}
+ />
+ <p className="text-xs text-neutral-500">
+ Use <code>*</code> for a catch-all that matches every message.
+ </p>
+ </div>
+
+ {form.action !== "reject" && (
+ <div className="space-y-2">
+ <Label htmlFor="rule-mailbox">
+ {form.action === "forward" ? "Mailbox for the kept copy" : "Destination mailbox"}
+ </Label>
+ <Select
+ id="rule-mailbox"
+ value={form.mailboxId ?? ""}
+ onChange={(e) => setForm({ ...form, mailboxId: e.target.value || null })}
+ >
+ <option value="">Select a mailbox</option>
+ {mailboxes.map((mailbox) => (
+ <option key={mailbox.id} value={mailbox.id}>
+ {mailbox.localPart}@{hostname}
+ {mailbox.disabled ? " (disabled)" : ""}
+ </option>
+ ))}
+ </Select>
+ </div>
+ )}
+
+ {form.action === "forward" && (
+ <>
+ <div className="space-y-2">
+ <Label htmlFor="rule-forward">Forward to</Label>
+ <Input
+ id="rule-forward"
+ type="email"
+ required
+ value={form.forwardTo ?? ""}
+ onChange={(e) => setForm({ ...form, forwardTo: e.target.value })}
+ />
+ </div>
+ <div className="flex items-center justify-between rounded-lg border border-neutral-200 px-3 py-2">
+ <div>
+ <p className="text-sm font-medium">Keep a copy</p>
+ <p className="text-xs text-neutral-500">
+ Also store the message in the selected mailbox.
+ </p>
+ </div>
+ <Switch
+ checked={form.keepCopy}
+ onCheckedChange={(keepCopy) => setForm({ ...form, keepCopy })}
+ />
+ </div>
+ </>
+ )}
+
+ {form.action === "reject" && (
+ <div className="space-y-2">
+ <Label htmlFor="rule-reason">Rejection reason</Label>
+ <Input
+ id="rule-reason"
+ value={form.rejectReason ?? ""}
+ placeholder="Message rejected by routing rule"
+ onChange={(e) => setForm({ ...form, rejectReason: e.target.value })}
+ />
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Label htmlFor="rule-priority">Priority</Label>
+ <Input
+ id="rule-priority"
+ type="number"
+ min={0}
+ max={1000}
+ value={form.priority}
+ onChange={(e) => setForm({ ...form, priority: Number(e.target.value) })}
+ />
+ <p className="text-xs text-neutral-500">Higher numbers are evaluated first.</p>
+ </div>
+
+ {error && <p className="text-sm text-red-600">{error}</p>}
+
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={save.isPending}>
+ {editing ? "Save changes" : "Create rule"}
+ </Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+function RuleSection({
+ title,
+ description,
+ rules,
+ hostname,
+ mailboxes,
+ onEdit,
+ onDelete,
+ onToggle,
+}: {
+ title: string;
+ description: string;
+ rules: DomainRule[];
+ hostname: string;
+ mailboxes: { id: string; localPart: string; displayName: string | null; disabled: boolean }[];
+ onEdit: (rule: DomainRule) => void;
+ onDelete: (id: string) => void;
+ onToggle: (rule: DomainRule) => void;
+}) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ <p className="text-sm text-neutral-500">{description}</p>
+ </CardHeader>
+ <CardContent className="space-y-2">
+ {rules.length === 0 ? (
+ <p className="text-sm text-neutral-500">No rules yet.</p>
+ ) : (
+ rules.map((rule) => {
+ const Icon = ACTION_ICONS[rule.action];
+ return (
+ <div
+ key={rule.id}
+ className="flex flex-wrap items-center gap-3 rounded-xl border border-neutral-200 px-3 py-2"
+ >
+ <Icon className="h-4 w-4 shrink-0 text-neutral-500" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <p className="truncate text-sm font-medium">
+ {rule.name || describeRule(rule, mailboxes, hostname)}
+ </p>
+ {!rule.enabled && <Badge variant="secondary">Disabled</Badge>}
+ </div>
+ {rule.name && (
+ <p className="truncate text-xs text-neutral-500">
+ {describeRule(rule, mailboxes, hostname)}
+ </p>
+ )}
+ <p className="text-xs text-neutral-400">
+ Priority {rule.priority} · matched {rule.matchCount}× · last{" "}
+ {formatLastMatched(rule.lastMatchedAt)}
+ </p>
+ </div>
+ <Switch checked={rule.enabled} onCheckedChange={() => onToggle(rule)} />
+ <Button variant="ghost" size="sm" onClick={() => onEdit(rule)}>
+ <Pencil className="h-4 w-4" />
+ </Button>
+ <Button variant="ghost" size="sm" onClick={() => onDelete(rule.id)}>
+ <Trash2 className="h-4 w-4 text-red-600" />
+ </Button>
+ </div>
+ );
+ })
+ )}
+ </CardContent>
+ </Card>
+ );
}
diff --git a/src/app/(admin)/routing/types.d.ts b/src/app/(admin)/routing/types.d.ts
new file mode 100644
index 0000000..b5fca63
--- /dev/null
+++ b/src/app/(admin)/routing/types.d.ts
@@ -0,0 +1,49 @@
+export type DomainRuleAction = "store" | "forward" | "reject";
+export type DomainRuleField = "recipient" | "sender" | "title" | "content";
+export type DomainRuleOperator = "contains" | "exact" | "starts_with" | "ends_with" | "regex";
+
+export type DomainRule = {
+ id: string;
+ domainId: string;
+ name: string | null;
+ enabled: boolean;
+ matchField: DomainRuleField;
+ matchOperator: DomainRuleOperator;
+ matchValue: string;
+ action: DomainRuleAction;
+ mailboxId: string | null;
+ forwardTo: string | null;
+ keepCopy: boolean;
+ rejectReason: string | null;
+ priority: number;
+ matchCount: number;
+ lastMatchedAt: string | number | null;
+};
+
+export type DomainRuleMailbox = {
+ id: string;
+ localPart: string;
+ displayName: string | null;
+ disabled: boolean;
+};
+
+export type DomainRuleInput = {
+ domainId: string;
+ name?: string;
+ enabled: boolean;
+ matchField: DomainRuleField;
+ matchOperator: DomainRuleOperator;
+ matchValue: string;
+ action: DomainRuleAction;
+ mailboxId?: string | null;
+ forwardTo?: string | null;
+ keepCopy: boolean;
+ rejectReason?: string | null;
+ priority: number;
+};
+
+export type RoutingDomain = {
+ id: string;
+ hostname: string;
+ status: string;
+};
diff --git a/src/app/(admin)/routing/utils.ts b/src/app/(admin)/routing/utils.ts
new file mode 100644
index 0000000..edbc20b
--- /dev/null
+++ b/src/app/(admin)/routing/utils.ts
@@ -0,0 +1,135 @@
+import { authFetch } from "@/lib/auth/client";
+import type {
+ DomainRule,
+ DomainRuleField,
+ DomainRuleInput,
+ DomainRuleMailbox,
+ DomainRuleOperator,
+ RoutingDomain,
+} from "./types";
+
+export const MATCH_FIELD_LABELS: Record<DomainRuleField, string> = {
+ recipient: "Recipient address",
+ sender: "Sender address",
+ title: "Subject",
+ content: "Body",
+};
+
+export const MATCH_OPERATOR_LABELS: Record<DomainRuleOperator, string> = {
+ contains: "contains",
+ exact: "is exactly",
+ starts_with: "starts with",
+ ends_with: "ends with",
+ regex: "matches regex",
+};
+
+export const ACTION_LABELS = {
+ store: "Deliver to mailbox",
+ forward: "Forward to address",
+ reject: "Reject / block",
+} as const;
+
+async function readJson<T>(res: Response): Promise<T> {
+ const json = (await res.json()) as T & { error?: unknown };
+ if (!res.ok) {
+ throw new Error(typeof json.error === "string" ? json.error : "Request failed");
+ }
+ return json;
+}
+
+export async function fetchRoutingDomains(): Promise<RoutingDomain[]> {
+ const res = await authFetch("/api/domains");
+ const json = await readJson<{ domains: RoutingDomain[] }>(res);
+ return json.domains ?? [];
+}
+
+export async function fetchDomainRules(
+ domainId: string,
+): Promise<{ rules: DomainRule[]; mailboxes: DomainRuleMailbox[] }> {
+ const res = await authFetch(`/api/routing-rules/domain?domainId=${encodeURIComponent(domainId)}`);
+ const json = await readJson<{ rules: DomainRule[]; mailboxes: DomainRuleMailbox[] }>(res);
+ return { rules: json.rules ?? [], mailboxes: json.mailboxes ?? [] };
+}
+
+export async function createDomainRule(input: DomainRuleInput) {
+ return readJson(
+ await authFetch("/api/routing-rules/domain", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ }),
+ );
+}
+
+export async function updateDomainRule(id: string, input: DomainRuleInput) {
+ return readJson(
+ await authFetch(`/api/routing-rules/domain/${id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ }),
+ );
+}
+
+export async function deleteDomainRule(id: string) {
+ return readJson(await authFetch(`/api/routing-rules/domain/${id}`, { method: "DELETE" }));
+}
+
+export function describeRule(rule: DomainRule, mailboxes: DomainRuleMailbox[], hostname: string): string {
+ const condition =
+ rule.matchValue === "*"
+ ? "Any message"
+ : `${MATCH_FIELD_LABELS[rule.matchField]} ${MATCH_OPERATOR_LABELS[rule.matchOperator]} "${rule.matchValue}"`;
+
+ if (rule.action === "reject") return `${condition} → reject`;
+ if (rule.action === "forward") {
+ const copy = rule.keepCopy ? " and keep a copy" : "";
+ return `${condition} → forward to ${rule.forwardTo ?? "—"}${copy}`;
+ }
+ const mailbox = mailboxes.find((m) => m.id === rule.mailboxId);
+ const address = mailbox ? `${mailbox.localPart}@${hostname}` : "—";
+ return `${condition} → deliver to ${address}`;
+}
+
+export function formatLastMatched(value: DomainRule["lastMatchedAt"]): string {
+ if (value === null || value === undefined) return "Never";
+ const numeric = typeof value === "number" ? value : Date.parse(String(value));
+ if (!Number.isFinite(numeric)) return "Never";
+ // Drizzle timestamps serialise as seconds when they bypass the mapper.
+ const ms = numeric < 1e12 ? numeric * 1000 : numeric;
+ return new Date(ms).toLocaleString();
+}
+
+export function emptyRuleInput(domainId: string): DomainRuleInput {
+ return {
+ domainId,
+ name: "",
+ enabled: true,
+ matchField: "recipient",
+ matchOperator: "contains",
+ matchValue: "",
+ action: "store",
+ mailboxId: null,
+ forwardTo: "",
+ keepCopy: false,
+ rejectReason: "",
+ priority: 100,
+ };
+}
+
+export function ruleToInput(rule: DomainRule): DomainRuleInput {
+ return {
+ domainId: rule.domainId,
+ name: rule.name ?? "",
+ enabled: rule.enabled,
+ matchField: rule.matchField,
+ matchOperator: rule.matchOperator,
+ matchValue: rule.matchValue,
+ action: rule.action,
+ mailboxId: rule.mailboxId,
+ forwardTo: rule.forwardTo ?? "",
+ keepCopy: rule.keepCopy,
+ rejectReason: rule.rejectReason ?? "",
+ priority: rule.priority,
+ };
+}
diff --git a/src/app/api/routing-rules/domain/[id]/route.ts b/src/app/api/routing-rules/domain/[id]/route.ts
new file mode 100644
index 0000000..e6535d3
--- /dev/null
+++ b/src/app/api/routing-rules/domain/[id]/route.ts
@@ -0,0 +1,74 @@
+import { and, eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { routingRules } from "@/db/schema";
+import { assertAdmin } from "@/lib/auth/admin";
+import { requireSessionUser } from "@/lib/api/auth";
+import { getEnv } from "@/lib/cloudflare";
+import { domainRoutingRuleSchema } from "@/lib/validators";
+import {
+ assertRuleMailbox,
+ getDomainOwnerId,
+ getOwnedDomain,
+ toRuleColumns,
+} from "@/lib/domains/routing-rules";
+import type { DomainRoutingRuleRouteParams } from "./types";
+
+/** Loads a domain-scope rule the caller is allowed to administer. */
+async function loadRule(request: Request, id: string) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return { error: auth.error } as const;
+ const user = auth.user;
+ try {
+ assertAdmin(user);
+ } catch {
+ return { error: NextResponse.json({ error: "Forbidden" }, { status: 403 }) } as const;
+ }
+
+ const db = getDb(env);
+ const [rule] = await db
+ .select()
+ .from(routingRules)
+ .where(and(eq(routingRules.id, id), eq(routingRules.scope, "domain")))
+ .limit(1);
+ if (!rule) {
+ return { error: NextResponse.json({ error: "Rule not found" }, { status: 404 }) } as const;
+ }
+
+ const domain = await getOwnedDomain(db, getDomainOwnerId(user), rule.domainId);
+ if (!domain) {
+ return { error: NextResponse.json({ error: "Rule not found" }, { status: 404 }) } as const;
+ }
+
+ return { env, db, user, rule, domain, error: null } as const;
+}
+
+export async function PATCH(request: Request, { params }: DomainRoutingRuleRouteParams) {
+ const { id } = await params;
+ const loaded = await loadRule(request, id);
+ if (loaded.error) return loaded.error;
+
+ const body = (await request.json()) as Record<string, unknown>;
+ // The rule's own domain always wins, so a request cannot move a rule to another domain.
+ const parsed = domainRoutingRuleSchema.safeParse({ ...body, domainId: loaded.rule.domainId });
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
+ }
+
+ if (parsed.data.mailboxId && !(await assertRuleMailbox(loaded.db, parsed.data.mailboxId, loaded.domain.id))) {
+ return NextResponse.json({ error: "Mailbox not found on this domain" }, { status: 404 });
+ }
+
+ await loaded.db.update(routingRules).set(toRuleColumns(parsed.data)).where(eq(routingRules.id, id));
+ return NextResponse.json({ ok: true });
+}
+
+export async function DELETE(request: Request, { params }: DomainRoutingRuleRouteParams) {
+ const { id } = await params;
+ const loaded = await loadRule(request, id);
+ if (loaded.error) return loaded.error;
+
+ await loaded.db.delete(routingRules).where(eq(routingRules.id, id));
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/routing-rules/domain/[id]/types.d.ts b/src/app/api/routing-rules/domain/[id]/types.d.ts
new file mode 100644
index 0000000..e370ee4
--- /dev/null
+++ b/src/app/api/routing-rules/domain/[id]/types.d.ts
@@ -0,0 +1,3 @@
+export type DomainRoutingRuleRouteParams = {
+ params: Promise<{ id: string }>;
+};
diff --git a/src/app/api/routing-rules/domain/route.ts b/src/app/api/routing-rules/domain/route.ts
new file mode 100644
index 0000000..3bf2c7f
--- /dev/null
+++ b/src/app/api/routing-rules/domain/route.ts
@@ -0,0 +1,81 @@
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { routingRules } from "@/db/schema";
+import { requireSessionUser } from "@/lib/api/auth";
+import { assertAdmin } from "@/lib/auth/admin";
+import { getEnv } from "@/lib/cloudflare";
+import { newId } from "@/lib/ids";
+import { domainRoutingRuleSchema } from "@/lib/validators";
+import {
+ assertRuleMailbox,
+ getDomainOwnerId,
+ getOwnedDomain,
+ listDomainMailboxes,
+ listDomainRules,
+ toRuleColumns,
+} from "@/lib/domains/routing-rules";
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return auth.error;
+ const user = auth.user;
+ try {
+ assertAdmin(user);
+ } catch {
+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ }
+
+ const domainId = new URL(request.url).searchParams.get("domainId");
+ if (!domainId) {
+ return NextResponse.json({ error: "domainId is required" }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ const domain = await getOwnedDomain(db, getDomainOwnerId(user), domainId);
+ if (!domain) {
+ return NextResponse.json({ error: "Domain not found" }, { status: 404 });
+ }
+
+ return NextResponse.json({
+ rules: await listDomainRules(db, domainId),
+ mailboxes: await listDomainMailboxes(db, domainId),
+ });
+}
+
+export async function POST(request: Request) {
+ const env = getEnv();
+ const auth = await requireSessionUser(env, request);
+ if (auth.error) return auth.error;
+ const user = auth.user;
+ try {
+ assertAdmin(user);
+ } catch {
+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ }
+
+ const parsed = domainRoutingRuleSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ const domain = await getOwnedDomain(db, getDomainOwnerId(user), parsed.data.domainId);
+ if (!domain) {
+ return NextResponse.json({ error: "Domain not found" }, { status: 404 });
+ }
+
+ if (parsed.data.mailboxId && !(await assertRuleMailbox(db, parsed.data.mailboxId, domain.id))) {
+ return NextResponse.json({ error: "Mailbox not found on this domain" }, { status: 404 });
+ }
+
+ const id = newId("rule");
+ await db.insert(routingRules).values({
+ id,
+ userId: user.id,
+ domainId: domain.id,
+ ...toRuleColumns(parsed.data),
+ });
+
+ return NextResponse.json({ id });
+}
diff --git a/src/app/api/routing-rules/route.ts b/src/app/api/routing-rules/route.ts
index 50730a8..34dda66 100644
--- a/src/app/api/routing-rules/route.ts
+++ b/src/app/api/routing-rules/route.ts
@@ -26,7 +26,7 @@ export async function GET(request: Request) {
const rows = await db
.select()
.from(routingRules)
- .where(eq(routingRules.mailboxId, mailboxId));
+ .where(and(eq(routingRules.mailboxId, mailboxId), eq(routingRules.scope, "mailbox")));
return NextResponse.json({ rules: rows });
}
@@ -69,6 +69,7 @@ export async function POST(request: Request) {
id,
userId: user.id,
domainId: mailbox.domainId,
+ scope: "mailbox",
pattern: parsed.data.matchValue.trim(),
matchField: parsed.data.matchField,
matchOperator: parsed.data.matchOperator,
diff --git a/src/lib/domains/routing-rules.ts b/src/lib/domains/routing-rules.ts
new file mode 100644
index 0000000..49aa734
--- /dev/null
+++ b/src/lib/domains/routing-rules.ts
@@ -0,0 +1,90 @@
+import { and, asc, desc, eq } from "drizzle-orm";
+import type { AppDatabase } from "@/db";
+import { domains, mailboxes, routingRules } from "@/db/schema";
+import type { SessionUser } from "@/lib/auth/types";
+
+export type DomainRuleInput = {
+ domainId: string;
+ name?: string | null;
+ enabled: boolean;
+ matchField: "recipient" | "sender" | "title" | "content";
+ matchOperator: "contains" | "exact" | "starts_with" | "ends_with" | "regex";
+ matchValue: string;
+ action: "store" | "forward" | "reject";
+ mailboxId?: string | null;
+ forwardTo?: string | null;
+ keepCopy: boolean;
+ rejectReason?: string | null;
+ priority: number;
+};
+
+/**
+ * Domains are owned by the admin who added them; team members with mailbox management
+ * rights act on their creator's domains, mirroring the domains API.
+ */
+export function getDomainOwnerId(user: Pick<SessionUser, "id" | "canManageMailboxes" | "createdByUserId">) {
+ return user.canManageMailboxes && user.createdByUserId ? user.createdByUserId : user.id;
+}
+
+export async function getOwnedDomain(db: AppDatabase, ownerId: string, domainId: string) {
+ const [domain] = await db
+ .select()
+ .from(domains)
+ .where(and(eq(domains.id, domainId), eq(domains.userId, ownerId)))
+ .limit(1);
+ return domain ?? null;
+}
+
+export async function listDomainRules(db: AppDatabase, domainId: string) {
+ return db
+ .select()
+ .from(routingRules)
+ .where(and(eq(routingRules.domainId, domainId), eq(routingRules.scope, "domain")))
+ .orderBy(desc(routingRules.priority), asc(routingRules.createdAt));
+}
+
+export async function listDomainMailboxes(db: AppDatabase, domainId: string) {
+ return db
+ .select({
+ id: mailboxes.id,
+ localPart: mailboxes.localPart,
+ displayName: mailboxes.displayName,
+ disabled: mailboxes.disabled,
+ })
+ .from(mailboxes)
+ .where(eq(mailboxes.domainId, domainId))
+ .orderBy(asc(mailboxes.localPart));
+}
+
+/** A destination mailbox must belong to the same domain as the rule. */
+export async function assertRuleMailbox(
+ db: AppDatabase,
+ mailboxId: string,
+ domainId: string,
+): Promise<boolean> {
+ const [mailbox] = await db
+ .select({ id: mailboxes.id })
+ .from(mailboxes)
+ .where(and(eq(mailboxes.id, mailboxId), eq(mailboxes.domainId, domainId)))
+ .limit(1);
+ return !!mailbox;
+}
+
+export function toRuleColumns(input: DomainRuleInput) {
+ return {
+ scope: "domain" as const,
+ name: input.name?.trim() || null,
+ enabled: input.enabled,
+ pattern: input.matchValue,
+ matchField: input.matchField,
+ matchOperator: input.matchOperator,
+ matchValue: input.matchValue,
+ action: input.action,
+ mailboxId: input.action === "reject" ? null : (input.mailboxId ?? null),
+ folderId: null,
+ forwardTo: input.action === "forward" ? (input.forwardTo?.trim() ?? null) : null,
+ keepCopy: input.action === "forward" ? input.keepCopy : false,
+ rejectReason: input.action === "reject" ? (input.rejectReason?.trim() || null) : null,
+ priority: input.priority,
+ };
+}
diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.ts
index 90b7e77..34085a8 100644
--- a/src/lib/email/inbound.ts
+++ b/src/lib/email/inbound.ts
@@ -28,7 +28,9 @@ export async function processInboundMessage(
payload: InboundQueueMessage,
): Promise<void> {
const db = getDb(env);
- const decision = await resolveInboundAddress(db, payload.to);
+ // The sender is passed so that sender-based block rules resolve the same way here as they
+ // do in the Worker email handler.
+ const decision = await resolveInboundAddress(db, payload.to, payload.from);
if (!decision) {
console.warn(`No routing for inbound address: ${payload.to}`);
@@ -40,7 +42,9 @@ export async function processInboundMessage(
return;
}
- if (decision.action === "forward" && decision.forwardTo) {
+ // A forward decision only reaches the queue when the rule keeps a copy; without a
+ // destination mailbox there is nothing to store.
+ if (decision.action === "forward" && !decision.keepCopy) {
console.info(`Forward ${payload.to} -> ${decision.forwardTo}`);
return;
}
diff --git a/src/lib/email/incoming.ts b/src/lib/email/incoming.ts
new file mode 100644
index 0000000..a1b4743
--- /dev/null
+++ b/src/lib/email/incoming.ts
@@ -0,0 +1,48 @@
+import { getDb } from "@/db";
+import { recordRuleMatch, resolveInboundAddress, type RoutingDecision } from "@/lib/email/routing";
+import { MAILFLARE_FORWARDED_HEADER } from "@/lib/email/account-forwarding";
+
+/**
+ * Resolves the routing decision for a live inbound message. Used by the Worker `email`
+ * handler, where `forward()` and `setReject()` are still available on the message.
+ *
+ * Never throws: a routing failure must not stop mail from being stored.
+ */
+export async function resolveIncomingMail(
+ env: CloudflareEnv,
+ from: string,
+ to: string,
+): Promise<RoutingDecision | null> {
+ try {
+ const db = getDb(env);
+ const decision = await resolveInboundAddress(db, to, from);
+ if (decision?.ruleId) {
+ await recordRuleMatch(db, decision.ruleId).catch(() => undefined);
+ }
+ return decision;
+ } catch (error) {
+ console.error(`Routing resolution failed for ${to}`, error);
+ return null;
+ }
+}
+
+/**
+ * Forwards to a Cloudflare Email Routing destination address. Returns whether the forward
+ * succeeded so the caller can decide to still store the message.
+ *
+ * The destination must be a verified destination address in Cloudflare Email Routing.
+ */
+export async function forwardMessage(
+ message: ForwardableEmailMessage,
+ destination: string,
+): Promise<boolean> {
+ try {
+ const headers = new Headers();
+ headers.set(MAILFLARE_FORWARDED_HEADER, "1");
+ await message.forward(destination, headers);
+ return true;
+ } catch (error) {
+ console.error(`Forwarding failed for ${message.to} -> ${destination}`, error);
+ return false;
+ }
+}
diff --git a/src/lib/email/routing.ts b/src/lib/email/routing.ts
index e0e1378..e7c6535 100644
--- a/src/lib/email/routing.ts
+++ b/src/lib/email/routing.ts
@@ -1,4 +1,4 @@
-import { eq, and, desc } from "drizzle-orm";
+import { eq, and, asc, desc } from "drizzle-orm";
import type { AppDatabase } from "@/db";
import { domains, folders, mailboxes, routingRules } from "@/db/schema";
import { getEmailAddress } from "@/lib/email/address";
@@ -19,6 +19,11 @@ export type RoutingDecision = {
action: "store" | "forward" | "reject";
mailbox?: ResolvedMailbox;
forwardTo?: string;
+ /** Forward rules drop the message unless the rule also keeps a copy in the mailbox. */
+ keepCopy?: boolean;
+ rejectReason?: string;
+ /** Set when a domain-scope rule produced this decision, so the caller can record a match. */
+ ruleId?: string;
};
export type InboxRuleDestination = {
@@ -26,9 +31,29 @@ export type InboxRuleDestination = {
folderId: string | null;
};
+type RuleRow = typeof routingRules.$inferSelect;
+
+export type RuleMatchInput = {
+ toAddress: string;
+ fromAddress?: string | null;
+ subject?: string | null;
+ content?: string | null;
+};
+
+/**
+ * Resolves what should happen to an inbound message addressed to `toAddress`.
+ *
+ * Domain-scope rules are evaluated in three phases so that a broad catch-all can never
+ * shadow a real mailbox:
+ * 1. `reject` rules (block lists) — highest precedence, evaluated before delivery.
+ * 2. exact mailbox, then multi-domain mailbox aliases.
+ * 3. remaining `forward` / `store` rules — the catch-all fallback.
+ * Within each phase rules run by descending priority, then oldest first.
+ */
export async function resolveInboundAddress(
db: AppDatabase,
toAddress: string,
+ fromAddress?: string | null,
): Promise<RoutingDecision | null> {
const parsed = parseAddress(toAddress);
if (!parsed) return null;
@@ -41,29 +66,129 @@ export async function resolveInboundAddress(
if (!domain) return null;
+ const domainRules = await listDomainRules(db, domain.id);
+ const matchInput: RuleMatchInput = { toAddress, fromAddress };
+
+ // Phase 1 — block rules run before any mailbox lookup so they can block a sender
+ // even when the recipient is a real mailbox.
+ for (const rule of domainRules) {
+ if (rule.action !== "reject") continue;
+ if (!matchesRule(rule, matchInput)) continue;
+ return {
+ action: "reject",
+ rejectReason: rule.rejectReason?.trim() || "Message rejected by routing rule",
+ ruleId: rule.id,
+ };
+ }
+
+ // Phase 2 — a real mailbox always wins over a catch-all.
const [exactMailbox] = await db
.select()
.from(mailboxes)
.where(and(eq(mailboxes.domainId, domain.id), eq(mailboxes.localPart, parsed.local)))
.limit(1);
- const mailbox = exactMailbox ?? await resolveMailboxDomainAlias(db, domain.hostname, parsed.local);
+ const mailbox = exactMailbox ?? (await resolveMailboxDomainAlias(db, domain.hostname, parsed.local));
+
+ if (mailbox) {
+ return {
+ action: "store",
+ mailbox: toResolvedMailbox(mailbox, domain.id, domain.hostname),
+ };
+ }
+
+ // Phase 3 — catch-all and forwarding fallbacks.
+ for (const rule of domainRules) {
+ if (rule.action !== "forward" && rule.action !== "store") continue;
+ if (!matchesRule(rule, matchInput)) continue;
+
+ if (rule.action === "forward") {
+ const forwardTo = rule.forwardTo?.trim();
+ if (!forwardTo) continue;
+ const catchAll = rule.mailboxId ? await getRuleMailbox(db, rule.mailboxId, domain.id) : null;
+ return {
+ action: "forward",
+ forwardTo,
+ keepCopy: rule.keepCopy && !!catchAll,
+ mailbox: catchAll ?? undefined,
+ ruleId: rule.id,
+ };
+ }
+
+ if (!rule.mailboxId) continue;
+ const catchAll = await getRuleMailbox(db, rule.mailboxId, domain.id);
+ if (!catchAll) continue;
+ return { action: "store", mailbox: catchAll, ruleId: rule.id };
+ }
+
+ return null;
+}
+
+async function listDomainRules(db: AppDatabase, domainId: string): Promise<RuleRow[]> {
+ return db
+ .select()
+ .from(routingRules)
+ .where(
+ and(
+ eq(routingRules.domainId, domainId),
+ eq(routingRules.scope, "domain"),
+ eq(routingRules.enabled, true),
+ ),
+ )
+ .orderBy(desc(routingRules.priority), asc(routingRules.createdAt));
+}
+async function getRuleMailbox(
+ db: AppDatabase,
+ mailboxId: string,
+ domainId: string,
+): Promise<ResolvedMailbox | null> {
+ const [mailbox] = await db
+ .select()
+ .from(mailboxes)
+ .where(and(eq(mailboxes.id, mailboxId), eq(mailboxes.disabled, false)))
+ .limit(1);
if (!mailbox) return null;
+ const [domain] = await db
+ .select({ hostname: domains.hostname })
+ .from(domains)
+ .where(eq(domains.id, domainId))
+ .limit(1);
+ if (!domain) return null;
+
+ return toResolvedMailbox(mailbox, domainId, domain.hostname);
+}
+
+function toResolvedMailbox(
+ mailbox: typeof mailboxes.$inferSelect,
+ domainId: string,
+ hostname: string,
+): ResolvedMailbox {
return {
- action: "store",
- mailbox: {
- mailboxId: mailbox.id,
- folderId: null,
- userId: mailbox.userId,
- domainId: domain.id,
- localPart: mailbox.localPart,
- hostname: domain.hostname,
- displayName: mailbox.displayName,
- },
+ mailboxId: mailbox.id,
+ folderId: null,
+ userId: mailbox.userId,
+ domainId,
+ localPart: mailbox.localPart,
+ hostname,
+ displayName: mailbox.displayName,
};
}
+/** Records that a domain rule fired, for the "last matched" column in the routing UI. */
+export async function recordRuleMatch(db: AppDatabase, ruleId: string): Promise<void> {
+ const [rule] = await db
+ .select({ matchCount: routingRules.matchCount })
+ .from(routingRules)
+ .where(eq(routingRules.id, ruleId))
+ .limit(1);
+ if (!rule) return;
+ await db
+ .update(routingRules)
+ .set({ matchCount: rule.matchCount + 1, lastMatchedAt: new Date() })
+ .where(eq(routingRules.id, ruleId));
+}
+
async function resolveMailboxDomainAlias(db: AppDatabase, hostname: string, localPart: string) {
const candidates = await db
.select()
@@ -92,11 +217,17 @@ export async function resolveInboxRuleDestination(
const rules = await db
.select()
.from(routingRules)
- .where(eq(routingRules.mailboxId, input.mailboxId))
- .orderBy(desc(routingRules.priority));
+ .where(
+ and(
+ eq(routingRules.mailboxId, input.mailboxId),
+ eq(routingRules.scope, "mailbox"),
+ eq(routingRules.enabled, true),
+ ),
+ )
+ .orderBy(desc(routingRules.priority), asc(routingRules.createdAt));
for (const rule of rules) {
- if (!matchesInboxRule(rule, input)) continue;
+ if (!matchesRule(rule, input)) continue;
if (rule.action === "spam" || rule.action === "trash") {
return { status: rule.action, folderId: null };
@@ -111,50 +242,74 @@ export async function resolveInboxRuleDestination(
return { status: "received", folderId: null };
}
-function matchesInboxRule(
- rule: {
- pattern: string;
- matchField?: "email" | "content" | "title" | string;
- matchOperator?: "contains" | "exact" | string;
- matchValue?: string | null;
- },
- input: {
- toAddress: string;
- fromAddress?: string | null;
- subject?: string | null;
- content?: string | null;
- },
-): boolean {
+type MatchableRule = {
+ pattern: string;
+ matchField?: string | null;
+ matchOperator?: string | null;
+ matchValue?: string | null;
+};
+
+export function matchesRule(rule: MatchableRule, input: RuleMatchInput): boolean {
const rawValue = (rule.matchValue || rule.pattern).trim();
+ // "*" is the catch-all pattern used by catch-all and block-everything rules.
+ if (rawValue === "*") return true;
const normalizedRuleValue = normalizeRuleComparisonValue(rule.matchField, rawValue);
if (!normalizedRuleValue) return false;
- if (normalizedRuleValue === "*") return true;
const values = getRuleFieldValues(rule.matchField, input);
return values.some((value) => {
+ if (!value) return false;
const normalizedValue = normalizeRuleComparisonValue(rule.matchField, value);
- if (rule.matchOperator === "exact") return normalizedValue === normalizedRuleValue;
- return normalizedValue.includes(normalizedRuleValue);
+ if (!normalizedValue) return false;
+ return compareRuleValue(rule.matchOperator, normalizedValue, normalizedRuleValue, rawValue);
});
}
-function normalizeRuleComparisonValue(field: string | undefined, value: string | null | undefined): string {
+function compareRuleValue(
+ operator: string | null | undefined,
+ value: string,
+ ruleValue: string,
+ rawRuleValue: string,
+): boolean {
+ switch (operator) {
+ case "exact":
+ return value === ruleValue;
+ case "starts_with":
+ return value.startsWith(ruleValue);
+ case "ends_with":
+ return value.endsWith(ruleValue);
+ case "regex":
+ return matchesRegex(value, rawRuleValue);
+ default:
+ return value.includes(ruleValue);
+ }
+}
+
+/**
+ * Rule patterns are operator-authored but still untrusted enough to warrant guarding:
+ * an invalid pattern must not throw and take down inbound processing.
+ */
+function matchesRegex(value: string, pattern: string): boolean {
+ try {
+ return new RegExp(pattern, "i").test(value);
+ } catch {
+ return false;
+ }
+}
+
+function normalizeRuleComparisonValue(field: string | null | undefined, value: string | null | undefined): string {
if (!value) return "";
- if (field !== "email") return value.toLowerCase();
- return getEmailAddress(value).trim().toLowerCase();
+ if (field === "email" || field === "sender" || field === "recipient") {
+ return getEmailAddress(value).trim().toLowerCase();
+ }
+ return value.toLowerCase();
}
-function getRuleFieldValues(
- field: string | undefined,
- input: {
- toAddress: string;
- fromAddress?: string | null;
- subject?: string | null;
- content?: string | null;
- },
-) {
+function getRuleFieldValues(field: string | null | undefined, input: RuleMatchInput) {
if (field === "content") return [input.content];
if (field === "title") return [input.subject];
+ if (field === "sender") return [input.fromAddress];
+ if (field === "recipient") return [input.toAddress];
return [input.fromAddress, input.toAddress];
}
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index bb85ac5..ce61dd3 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -163,10 +163,74 @@ export const routingRuleSchema = z.object({
priority: z.number().int().default(0),
});
+export const domainRoutingRuleSchema = z
+ .object({
+ domainId: z.string().min(1),
+ name: z.string().trim().max(120).optional(),
+ enabled: z.boolean().default(true),
+ matchField: z.enum(["recipient", "sender", "title", "content"]).default("recipient"),
+ matchOperator: z.enum(["contains", "exact", "starts_with", "ends_with", "regex"]).default("contains"),
+ matchValue: z.string().trim().min(1).max(500),
+ action: z.enum(["store", "forward", "reject"]),
+ mailboxId: z.string().min(1).nullish(),
+ forwardTo: z.string().trim().email().nullish(),
+ keepCopy: z.boolean().default(false),
+ rejectReason: z.string().trim().max(200).nullish(),
+ priority: z.number().int().min(0).max(1000).default(0),
+ })
+ .superRefine((value, ctx) => {
+ if (value.action === "store" && !value.mailboxId) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["mailboxId"],
+ message: "Choose the mailbox that should receive matching mail",
+ });
+ }
+ if (value.action === "forward" && !value.forwardTo) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["forwardTo"],
+ message: "A forwarding destination is required",
+ });
+ }
+ if (value.action === "forward" && value.keepCopy && !value.mailboxId) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["mailboxId"],
+ message: "Keeping a copy requires a destination mailbox",
+ });
+ }
+ if (value.matchOperator === "regex") {
+ try {
+ new RegExp(value.matchValue);
+ } catch {
+ ctx.addIssue({
+ code: "custom",
+ path: ["matchValue"],
+ message: "Enter a valid regular expression",
+ });
+ }
+ }
+ });
+
export const webhookSchema = z.object({
url: z.string().url().max(2048),
+ description: z.string().trim().max(200).optional(),
events: z
.array(z.enum(["message.inbound", "message.outbound", "message.failed"]))
.min(1)
.max(3),
+ maxAttempts: z.number().int().min(1).max(10).default(5),
+});
+
+export const webhookUpdateSchema = z.object({
+ url: z.string().url().max(2048).optional(),
+ description: z.string().trim().max(200).nullish(),
+ events: z
+ .array(z.enum(["message.inbound", "message.outbound", "message.failed"]))
+ .min(1)
+ .max(3)
+ .optional(),
+ enabled: z.boolean().optional(),
+ maxAttempts: z.number().int().min(1).max(10).optional(),
});
diff --git a/worker.ts b/worker.ts
index 8bcdf0a..f7bbc8e 100644
--- a/worker.ts
+++ b/worker.ts
@@ -6,7 +6,9 @@ import {
type InboundQueueMessage,
} from "./src/lib/email/inbound";
import { processOutboundQueue, type OutboundQueueMessage } from "./src/lib/email/send";
-import { isInboundQueueMessage } from "./worker-utils";
+import { isInboundQueueMessage, isWebhookRetryMessage } from "./worker-utils";
+import { processWebhookRetry, type WebhookRetryMessage } from "./src/lib/email/webhooks";
+import { resolveIncomingMail, forwardMessage } from "./src/lib/email/incoming";
import { getUserFromSession } from "./src/lib/auth/session";
import { getSessionTokenFromRequest } from "./src/lib/realtime/utils";
import {
@@ -38,16 +40,26 @@ export default {
async email(message: ForwardableEmailMessage, env: CloudflareEnv, ctx: ExecutionContext) {
try {
+ // Domain routing rules are resolved here rather than in the queue because reject and
+ // forward can only be actioned on the live ForwardableEmailMessage.
+ const decision = await resolveIncomingMail(env, message.from, message.to);
+
+ if (decision?.action === "reject") {
+ message.setReject(decision.rejectReason ?? "Message rejected by routing rule");
+ return;
+ }
+
+ if (decision?.action === "forward" && decision.forwardTo) {
+ const forwarded = await forwardMessage(message, decision.forwardTo);
+ // A forward rule drops the message unless it was explicitly asked to keep a copy.
+ // If the forward itself failed we still store it, so mail is never silently lost.
+ if (forwarded && !decision.keepCopy) return;
+ }
+
if (message.headers.get(MAILFLARE_FORWARDED_HEADER) !== "1") {
const forwardingDestination = await getAccountForwardingDestination(env, message.to);
if (forwardingDestination) {
- try {
- const forwardingHeaders = new Headers();
- forwardingHeaders.set(MAILFLARE_FORWARDED_HEADER, "1");
- await message.forward(forwardingDestination, forwardingHeaders);
- } catch (error) {
- console.error(`Account forwarding failed for ${message.to}`, error);
- }
+ await forwardMessage(message, forwardingDestination);
}
}
const rawR2Key = await storeRawToR2(env, message.from, message.to, message.raw);
@@ -69,6 +81,8 @@ export default {
try {
if (isInboundQueueMessage(msg.body)) {
await processInboundMessage(env, msg.body);
+ } else if (isWebhookRetryMessage(msg.body)) {
+ await processWebhookRetry(env, msg.body as WebhookRetryMessage);
} else {
await processOutboundQueue(env, msg.body as OutboundQueueMessage);
}