Email for professionals and teams
Merge PR #13 with current routing and settings
Hieu Nguyen (Jack)9d5c1bc63aca
diff --cc drizzle/migrations/0024_add_advanced_routing_and_webhook_retries.sqlindex 267c074,0000000..267c074mode 100644,000000..100644--- a/drizzle/migrations/0024_add_advanced_routing_and_webhook_retries.sql+++ b/drizzle/migrations/0024_add_advanced_routing_and_webhook_retries.sqldiff --cc drizzle/migrations/meta/_journal.jsonindex 1fb56ca,02421fa..683fc7e--- a/drizzle/migrations/meta/_journal.json+++ b/drizzle/migrations/meta/_journal.json@@@ -148,6 -148,27 +148,34 @@@"when": 1788345600000,"tag": "0020_add_calendar_templates_schedule","breakpoints": true+ },+ {+ "idx": 21,+ "version": "6",+ "when": 1788432000000,+ "tag": "0021_add_mailbox_signature",+ "breakpoints": true+ },+ {+ "idx": 22,+ "version": "6",+ "when": 1788518400000,+ "tag": "0022_add_mailbox_auto_reply",+ "breakpoints": true+ },+ {+ "idx": 23,+ "version": "6",+ "when": 1788604800000,+ "tag": "0023_add_mailbox_aliases",+ "breakpoints": true++ },++ {++ "idx": 24,++ "version": "6",++ "when": 1788604800001,++ "tag": "0024_add_advanced_routing_and_webhook_retries",++ "breakpoints": true}]}diff --cc package.jsonindex 7645b5c,c5e95b5..de1cfa1--- a/package.json+++ b/package.json@@@ -5,11 -5,13 +5,13 @@@"scripts": {"dev": "next dev","build": "next build",+ "build:next": "next build","start": "next start",- "lint": "next lint",+ "lint": "eslint .",- "deploy": "opennextjs-cloudflare build && npm run deploy:worker",+ "deploy": "opennextjs-cloudflare build && npm run db:migrate:remote && npm run deploy:worker","deploy:worker": "OPEN_NEXT_DEPLOY=true wrangler deploy",- "deploy:with-migrations": "npm run db:migrate:remote && npm run deploy",+ "deploy:local": "npm run build && npm run deploy",+ "deploy:with-migrations": "npm run deploy:local","upload": "opennextjs-cloudflare build && OPEN_NEXT_DEPLOY=true wrangler versions upload","preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview","cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts",diff --cc src/app/(admin)/routing/page.tsxindex 6883a65,4a3d555..89d111d--- a/src/app/(admin)/routing/page.tsx+++ b/src/app/(admin)/routing/page.tsx@@@ -1,447 -1,5 +1,5 @@@- "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;+ import { redirect } from "next/navigation";export default function RoutingPage() {- 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>- );- redirect("/settings");++ redirect("/settings/rules");}diff --cc src/app/(settings)/settings/rules/page.tsxindex 5e2a89e,5e2a89e..4f205da--- a/src/app/(settings)/settings/rules/page.tsx+++ b/src/app/(settings)/settings/rules/page.tsx@@@ -1,4 -1,4 +1,5 @@@import { InboxRules } from "@/components/settings/inbox-rules";++import { DomainRouting } from "@/components/settings/domain-routing/domain-routing";export default function SettingsRulesPage() {return (@@@ -6,11 -6,11 +7,20 @@@<div><h1 className="text-3xl font-medium text-neutral-900">Rules</h1><p className="mt-1 text-sm text-neutral-500">-- Manage routing and filtering rules for the selected mailbox.++ Manage domain routing and mailbox filtering rules.</p></div><div className="rounded-3xl bg-white p-6">++ <DomainRouting />++ </div>++ <div className="rounded-3xl bg-white p-6">++ <h2 className="text-2xl font-semibold text-neutral-900">Mailbox rules</h2>++ <p className="mt-1 text-sm text-neutral-500">++ Filter mail after it reaches the selected mailbox.++ </p>++ <div className="mt-6"><InboxRules />++ </div></div></div>);diff --cc src/components/settings/domain-routing/domain-routing.tsxindex 0000000,0000000..1d953f9new file mode 100644--- /dev/null+++ b/src/components/settings/domain-routing/domain-routing.tsx@@@ -1,0 -1,0 +1,447 @@@++"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 function DomainRouting() {++ 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>++ <h2 className="text-2xl font-semibold">Domain routing</h2>++ <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 --cc src/components/settings/domain-routing/types.d.tsindex b5fca63,0000000..b5fca63mode 100644,000000..100644--- a/src/components/settings/domain-routing/types.d.ts+++ b/src/components/settings/domain-routing/types.d.tsdiff --cc src/components/settings/domain-routing/utils.tsindex edbc20b,0000000..edbc20bmode 100644,000000..100644--- a/src/components/settings/domain-routing/utils.ts+++ b/src/components/settings/domain-routing/utils.tsdiff --cc src/lib/email/routing.tsindex e7c6535,0315c89..e756274--- a/src/lib/email/routing.ts+++ b/src/lib/email/routing.ts@@@ -1,9 -1,9 +1,9 @@@-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 { domains, folders, mailboxAliases, mailboxes, routingRules } from "@/db/schema";import { getEmailAddress } from "@/lib/email/address";import { getMailboxDomainAddresses } from "@/lib/mailboxes/domain-addresses";- import { parseAddress } from "@/lib/utils";+ import { normalizeRecipientLocalPart, parseRecipientAddress } from "@/lib/email/recipient-address";export type ResolvedMailbox = {mailboxId: string;@@@ -53,9 -29,8 +53,9 @@@ export type RuleMatchInput =export async function resolveInboundAddress(db: AppDatabase,toAddress: string,+ fromAddress?: string | null,): Promise<RoutingDecision | null> {- const parsed = parseAddress(toAddress);+ const parsed = parseRecipientAddress(toAddress);if (!parsed) return null;const [domain] = await db@@@ -66,138 -41,69 +66,162 @@@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+ const exactMailboxes = 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));- .where(and(- eq(mailboxes.domainId, domain.id),- eq(mailboxes.disabled, false),- ));++ .where(and(eq(mailboxes.domainId, domain.id), eq(mailboxes.disabled, false)));+ const exactMailbox = exactMailboxes.find(+ (mailbox) => normalizeRecipientLocalPart(mailbox.localPart) === parsed.localPart,+ );+ const mailbox = exactMailbox+ ?? await resolveMailboxAlias(db, domain.id, parsed.localPart)+ ?? await resolveMailboxDomainAlias(db, parsed.localPart, parsed.normalizedAddress);+ 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) {+ async function resolveMailboxAlias(db: AppDatabase, domainId: string, localPart: string) {+ const rows = await db+ .select({ mailbox: mailboxes, aliasLocalPart: mailboxAliases.localPart })+ .from(mailboxAliases)+ .innerJoin(mailboxes, eq(mailboxAliases.mailboxId, mailboxes.id))+ .where(and(+ eq(mailboxAliases.domainId, domainId),+ eq(mailboxes.disabled, false),+ ));+ const row = rows.find(+ (item) => normalizeRecipientLocalPart(item.aliasLocalPart) === localPart,+ );+ return row?.mailbox ?? null;+ }++ async function resolveMailboxDomainAlias(+ db: AppDatabase,+ localPart: string,+ normalizedAddress: string,+ ) {const candidates = await db.select().from(mailboxes)- .where(and(eq(mailboxes.localPart, localPart), eq(mailboxes.useAllDomains, true), eq(mailboxes.disabled, false)));+ .where(and(eq(mailboxes.useAllDomains, true), eq(mailboxes.disabled, false)));for (const mailbox of candidates) {- if (normalizeRecipientLocalPart(mailbox.localPart) !== localPart) {- continue;- }++ if (normalizeRecipientLocalPart(mailbox.localPart) !== localPart) continue;const addresses = await getMailboxDomainAddresses(db, mailbox);- if (addresses.includes(`${localPart}@${hostname}`.toLowerCase())) {- if (addresses.some(- (address) => parseRecipientAddress(address)?.normalizedAddress === normalizedAddress,- )) {++ if (addresses.some((address) => parseRecipientAddress(address)?.normalizedAddress === normalizedAddress)) {return mailbox;}}diff --cc src/lib/setup/migration.tsindex 4170984,75f3cd4..9e6e136--- a/src/lib/setup/migration.ts+++ b/src/lib/setup/migration.ts@@@ -19,7 -20,9 +20,10 @@@ const MIGRATION_NAMES ="0018_add_mailbox_domain_aliases.sql","0019_merge_message_bodies.sql","0020_add_calendar_templates_schedule.sql",- "0021_add_advanced_routing_and_webhook_retries.sql",+ "0021_add_mailbox_signature.sql",+ "0022_add_mailbox_auto_reply.sql",+ "0023_add_mailbox_aliases.sql",++ "0024_add_advanced_routing_and_webhook_retries.sql",];const INITIAL_SCHEMA_SQL = `