Skip to content

Email for professionals and teams

Allow choosing aliases when creating accounts

lewisf73b80fd93a4
diff --git a/docs/api.md b/docs/api.md
index 414fcfa..bf9592a 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -40,7 +40,7 @@ Admin API keys cannot read or send mail. Enable **Allow MCP access** when creati
| Scope | Mailflare route | Purpose |
| --- | --- | --- |
| `accounts` | `GET /api/v1/accounts` | List managed accounts |
-| `accounts` | `POST /api/v1/accounts` | Create an account and its mailbox (`{ username, domainId, password, role? }`) |
+| `accounts` | `POST /api/v1/accounts` | Create an account and its mailbox (`{ username, domainId, password, role?, useAllDomains?, aliases? }`) |
| `accounts` | `GET /api/v1/accounts/[id]` | Get a managed account |
| `accounts` | `PATCH /api/v1/accounts/[id]` | Update an account (`{ name, role, disabled, canManageMailboxes, forwardingEmail?, password? }`) |
| `mailboxes` | `GET /api/v1/mailboxes` | List managed mailboxes |
@@ -49,6 +49,46 @@ Admin API keys cannot read or send mail. Enable **Allow MCP access** when creati
| `mailboxes` | `PATCH /api/v1/mailboxes/[id]` | Update mailbox settings |
| `mailboxes` | `DELETE /api/v1/mailboxes/[id]` | Delete a mailbox and its routing rule |
+### Choose aliases when creating an account
+
+In **Admin > Accounts > New account**, the primary address is assigned by default.
+Add optional aliases by choosing each username and domain, or enable **Use all domains**
+to also receive and send as the primary username on every available active domain owned
+by the same admin, including domains added later.
+
+The dashboard, admin API, and MCP `manage_accounts` create action share the same
+creation handler. For example, this API body creates `[email protected]` with just
+`[email protected]` as an additional alias:
+
+```json
+{
+ "username": "sam",
+ "domainId": "dom_example_com",
+ "password": "REPLACE_WITH_A_STRONG_PASSWORD",
+ "useAllDomains": false,
+ "aliases": [
+ { "domainId": "dom_example_net", "localPart": "sales" }
+ ]
+}
+```
+
+Pass the same object as `data` to `manage_accounts` with `action: "create"`.
+`aliases` defaults to an empty list. Alias domains must
+be active and owned by the admin creating the account. Duplicate addresses and conflicts
+with existing mailboxes or aliases are rejected, including equivalent dot/plus variants.
+An alias shares its mailbox's delivery, message storage, and sending permissions.
+
+For backward compatibility, API/MCP requests that omit `useAllDomains` still default
+to `true`; pass `false` explicitly for primary-only or selected-alias accounts. The
+dashboard sends `false` unless the checkbox is enabled. This changes initial address
+assignment, not existing mailbox management permissions. Existing accounts are not
+modified and no database migration is required.
+
+Creation validates all selected addresses before provisioning. Account, mailbox, and
+alias records are inserted atomically. If Cloudflare routing fails, the new records
+are removed and routing changes from that attempt are rolled back, preserving existing
+rules. If cleanup itself fails, the response reports that manual checking is needed.
+
## 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/account-aliases.tsx b/src/app/(admin)/accounts/account-aliases.tsx
new file mode 100644
index 0000000..dfcb2e6
--- /dev/null
+++ b/src/app/(admin)/accounts/account-aliases.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { Plus, Trash2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { Select } from "@/components/ui/select";
+import type { AccountAliasesProps } from "./types";
+
+export function AccountAliases({ domains, domainId, username, useAllDomains, onUseAllDomainsChange, aliases, onAliasesChange }: AccountAliasesProps) {
+ const availableDomains = domains.filter((domain) => domain.status === "active");
+ return (
+ <div className="space-y-4 border-t border-neutral-100 pt-4">
+ <label className="flex items-start gap-3 rounded-xl bg-neutral-50 p-4">
+ <Checkbox checked={useAllDomains} onChange={(event) => onUseAllDomainsChange(event.target.checked)} />
+ <span>
+ <span className="block text-sm font-medium">Use all domains</span>
+ <span className="mt-1 block text-sm text-neutral-500">
+ Use this username on every available domain, including domains added later.
+ When off, only the primary address and the aliases below are assigned.
+ </span>
+ </span>
+ </label>
+ <div className="space-y-3">
+ <div>
+ <p className="text-sm font-medium">Additional aliases <span className="font-normal text-neutral-500">(optional)</span></p>
+ <p className="mt-1 text-sm text-neutral-500">These addresses share the new account’s inbox and can also be used to send mail.</p>
+ </div>
+ {aliases.map((alias, index) => (
+ <div key={alias.id} className="flex items-center gap-2">
+ <div className="flex min-w-0 flex-1 items-center gap-1 rounded-md border border-neutral-200 bg-white">
+ <Input
+ aria-label={`Alias ${index + 1} username`}
+ value={alias.localPart}
+ onChange={(event) => onAliasesChange(aliases.map((item) => item.id === alias.id ? { ...item, localPart: event.target.value } : item))}
+ placeholder="username"
+ className="min-w-0 flex-1 rounded-none border-0 shadow-none"
+ pattern="[a-zA-Z0-9._%+\-]+"
+ maxLength={64}
+ required
+ />
+ <span className="text-sm text-neutral-400">@</span>
+ <Select
+ aria-label={`Alias ${index + 1} domain`}
+ value={alias.domainId}
+ onChange={(event) => onAliasesChange(aliases.map((item) => item.id === alias.id ? { ...item, domainId: event.target.value } : item))}
+ containerClassName="min-w-0 flex-1 self-stretch rounded-none border-0 px-0"
+ className="min-w-0 bg-transparent px-2 text-sm"
+ required
+ >
+ {availableDomains.map((domain) => <option key={domain.id} value={domain.id}>{domain.hostname}</option>)}
+ </Select>
+ </div>
+ <Button type="button" variant="ghost" size="sm" className="h-10 w-10 shrink-0 p-0" aria-label={`Remove alias ${index + 1}`} onClick={() => onAliasesChange(aliases.filter((item) => item.id !== alias.id))}>
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+ <Button type="button" variant="outline" disabled={!availableDomains.length} onClick={() => onAliasesChange([
+ ...aliases,
+ { id: crypto.randomUUID(), localPart: username.trim(), domainId: (availableDomains.find((domain) => domain.id !== domainId) ?? availableDomains[0]).id },
+ ])}>
+ <Plus className="h-4 w-4" /> Add alias
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/(admin)/accounts/page.tsx b/src/app/(admin)/accounts/page.tsx
index 0cbe7a8..61bd84f 100644
--- a/src/app/(admin)/accounts/page.tsx
+++ b/src/app/(admin)/accounts/page.tsx
@@ -13,7 +13,15 @@ import { ProgressiveAvatarImage } from "@/components/progressive-avatar-image";
import { getAvatarColorStyle } from "@/lib/avatar-colors";
import { LicenseRequiredOverlay } from "@/components/license-required-overlay";
import { List, ListRow } from "@/components/ui/list";
-import type { Account, AccountResponse, Domain } from "./types";
+import { AccountAliases } from "./account-aliases";
+import type { Account, AccountAliasDraft, AccountResponse, Domain } from "./types";
+
+async function fetchAccounts(): Promise<Account[]> {
+ const response = await authFetch("/api/accounts");
+ const data = (await response.json()) as AccountResponse;
+ if (!response.ok) throw new Error(data.error ?? "Unable to load accounts");
+ return data.accounts ?? [];
+}
export default function AccountsPage() {
const [accounts, setAccounts] = useState<Account[]>([]);
@@ -22,6 +30,8 @@ export default function AccountsPage() {
const [domainId, setDomainId] = useState("");
const [role, setRole] = useState<"admin" | "user">("user");
const [password, setPassword] = useState("");
+ const [useAllDomains, setUseAllDomains] = useState(false);
+ const [aliases, setAliases] = useState<AccountAliasDraft[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
@@ -29,14 +39,12 @@ export default function AccountsPage() {
const [teamRequired, setTeamRequired] = useState(false);
async function loadAccounts() {
- const response = await authFetch("/api/accounts");
- const data = (await response.json()) as AccountResponse;
- if (!response.ok) throw new Error(data.error ?? "Unable to load accounts");
- setAccounts(data.accounts ?? []);
+ setAccounts(await fetchAccounts());
}
useEffect(() => {
- loadAccounts().then(async () => {
+ fetchAccounts().then(async (accounts) => {
+ setAccounts(accounts);
const response = await authFetch("/api/domains");
const data = (await response.json()) as { domains?: Domain[]; error?: string };
if (!response.ok) throw new Error(data.error ?? "Unable to load domains");
@@ -54,11 +62,17 @@ export default function AccountsPage() {
setSaving(true);
setMessage(null);
try {
- const response = await authFetch("/api/accounts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, domainId, password, role }) });
+ const response = await authFetch("/api/accounts", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ username, domainId, password, role, useAllDomains, aliases: aliases.map(({ domainId, localPart }) => ({ domainId, localPart })) }),
+ });
const data = (await response.json()) as AccountResponse;
- if (!response.ok) throw new Error(data.error ?? "Unable to create account");
+ if (!response.ok) throw new Error(typeof data.error === "string" ? data.error : "Check the account and alias details and try again");
setUsername("");
setPassword("");
+ setUseAllDomains(false);
+ setAliases([]);
setCreateOpen(false);
await loadAccounts();
} catch (error) {
@@ -74,11 +88,12 @@ export default function AccountsPage() {
{loading && <p className="text-sm text-neutral-500">Loading...</p>}
{accounts.map((account) => <ListRow key={account.id} asChild><Link href={`/accounts/${account.id}`}><span style={getAvatarColorStyle(account.email)} className="relative flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-full font-semibold duration-200">{account.name.charAt(0).toUpperCase()}{account.hasAvatar && <ProgressiveAvatarImage 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>
+ <Dialog open={createOpen} onOpenChange={setCreateOpen}><DialogContent className="max-h-[calc(100dvh-4rem)] w-[min(640px,calc(100vw-32px))] overflow-y-auto"><DialogHeader><DialogTitle>Add user account</DialogTitle><DialogDescription>The user can sign in with this email and password.</DialogDescription></DialogHeader><form onSubmit={createAccount}><fieldset disabled={saving} 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)} containerClassName="min-w-0 max-w-[55%] shrink-0 rounded-none border-0 px-0" className="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>
- <div className="space-y-2"><Label htmlFor="account-role">Role</Label><Select id="account-role" value={role} onChange={(event) => setRole(event.target.value as "admin" | "user")} className="h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm"><option value="user">User</option><option value="admin">Admin</option></Select></div>
+ <div className="space-y-2"><Label htmlFor="account-role">Role</Label><Select id="account-role" value={role} onChange={(event) => setRole(event.target.value as "admin" | "user")} containerClassName="h-10 w-full bg-white px-0" className="px-3 text-sm"><option value="user">User</option><option value="admin">Admin</option></Select></div>
+ <AccountAliases domains={domains} domainId={domainId} username={username} useAllDomains={useAllDomains} onUseAllDomainsChange={setUseAllDomains} aliases={aliases} onAliasesChange={setAliases} />
{message && <p className="text-sm text-red-600">{message}</p>}<Button type="submit" disabled={saving || !domainId}>{saving ? "Creating..." : "Create account"}</Button>
- </form></DialogContent></Dialog>
+ </fieldset></form></DialogContent></Dialog>
</div>;
}
diff --git a/src/app/(admin)/accounts/types.d.ts b/src/app/(admin)/accounts/types.d.ts
index b7840e3..645a4f5 100644
--- a/src/app/(admin)/accounts/types.d.ts
+++ b/src/app/(admin)/accounts/types.d.ts
@@ -1,6 +1,23 @@
export type Domain = {
id: string;
hostname: string;
+ status?: string;
+};
+
+export type AccountAliasDraft = {
+ id: string;
+ domainId: string;
+ localPart: string;
+};
+
+export type AccountAliasesProps = {
+ domains: Domain[];
+ domainId: string;
+ username: string;
+ useAllDomains: boolean;
+ onUseAllDomainsChange: (value: boolean) => void;
+ aliases: AccountAliasDraft[];
+ onAliasesChange: (aliases: AccountAliasDraft[]) => void;
};
export type Account = {
diff --git a/src/app/api/accounts/create.ts b/src/app/api/accounts/create.ts
new file mode 100644
index 0000000..91255fe
--- /dev/null
+++ b/src/app/api/accounts/create.ts
@@ -0,0 +1,86 @@
+import { eq, inArray } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { domains, mailboxAliases, mailboxes, users } from "@/db/schema";
+import { hashPassword } from "@/lib/auth/password";
+import { rollbackEmailRoutingRuleChanges } from "@/lib/cloudflare-api";
+import type { CfEmailRoutingRuleChange } from "@/lib/cloudflare-api.types";
+import { normalizeRecipientLocalPart } from "@/lib/email/recipient-address";
+import { newId } from "@/lib/ids";
+import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";
+import type { CreateUserAccountInput } from "./types";
+import { accountListItemFromUser, getDomainForAdmin } from "./utils";
+
+/** Shared by dashboard and admin API/MCP account creation. */
+export async function createAccountResponse(env: CloudflareEnv, adminUserId: string, input: CreateUserAccountInput) {
+ const db = getDb(env);
+ const primaryDomain = await getDomainForAdmin(db, adminUserId, input.domainId);
+ if (!primaryDomain) return NextResponse.json({ error: "Domain not found" }, { status: 404 });
+ const username = input.username.toLowerCase().trim();
+ const email = `${username}@${primaryDomain.hostname}`;
+ const requested = [{ domainId: primaryDomain.id, localPart: username }, ...input.aliases];
+ const ownedDomains = await db.select().from(domains).where(eq(domains.userId, adminUserId));
+ const byId = new Map(ownedDomains.map((domain) => [domain.id, domain]));
+ const seen = new Set<string>();
+ for (const [index, address] of requested.entries()) {
+ const domain = byId.get(address.domainId);
+ if (!domain || (index > 0 && domain.status !== "active")) {
+ return NextResponse.json({ error: "Choose an active alias domain owned by this admin account" }, { status: 400 });
+ }
+ const localPart = normalizeRecipientLocalPart(address.localPart);
+ if (!localPart) return NextResponse.json({ error: "Enter a valid address username" }, { status: 400 });
+ const key = `${localPart}@${domain.id}`;
+ if (seen.has(key)) {
+ return NextResponse.json({ error: "Each alias must be distinct from the primary address and other aliases" }, { status: 400 });
+ }
+ seen.add(key);
+ }
+ const [registered] = await db.select({ id: users.id }).from(users).where(eq(users.email, email)).limit(1);
+ if (registered) return NextResponse.json({ error: "Email already registered" }, { status: 409 });
+ // A subquery avoids one bound parameter per selected domain.
+ const ownedDomainIds = db.select({ id: domains.id }).from(domains).where(eq(domains.userId, adminUserId));
+ const [existingMailboxes, existingAliases] = await Promise.all([
+ db.select({ domainId: mailboxes.domainId, localPart: mailboxes.localPart }).from(mailboxes).where(inArray(mailboxes.domainId, ownedDomainIds)),
+ db.select({ domainId: mailboxAliases.domainId, localPart: mailboxAliases.localPart }).from(mailboxAliases).where(inArray(mailboxAliases.domainId, ownedDomainIds)),
+ ]);
+ if ([...existingMailboxes, ...existingAliases].some((address) => seen.has(`${normalizeRecipientLocalPart(address.localPart)}@${address.domainId}`))) {
+ return NextResponse.json({ error: "An email address is already assigned to a mailbox or alias" }, { status: 409 });
+ }
+
+ const userId = newId("usr");
+ const mailboxId = newId("mbx");
+ const mailbox = { id: mailboxId, userId, domainId: primaryDomain.id, localPart: username, displayName: username, useAllDomains: input.useAllDomains };
+ const changes: CfEmailRoutingRuleChange[] = [];
+ let inserted = false;
+ try {
+ const accountInsert = db.insert(users).values({
+ id: userId, email, passwordHash: hashPassword(input.password), name: username,
+ role: input.role, createdByUserId: adminUserId,
+ }).returning();
+ const mailboxInsert = db.insert(mailboxes).values(mailbox);
+ // Five bound columns per alias: 20 rows fit D1's 100-parameter limit.
+ const aliasInserts = Array.from({ length: Math.ceil(input.aliases.length / 20) }, (_, index) =>
+ db.insert(mailboxAliases).values(input.aliases.slice(index * 20, (index + 1) * 20).map((alias) => ({
+ id: newId("als"), mailboxId, domainId: alias.domainId, localPart: alias.localPart,
+ }))),
+ );
+ // D1 batches are atomic: aliases and their owner either all exist or none do.
+ const [accounts] = await db.batch([accountInsert, mailboxInsert, ...aliasInserts]);
+ inserted = true;
+ await ensureMailboxDomainRouting(env, db, mailbox, changes);
+ return NextResponse.json({ account: accountListItemFromUser(accounts[0]) }, { status: 201 });
+ } catch (error) {
+ const cleanup = await Promise.allSettled([
+ rollbackEmailRoutingRuleChanges(env, changes),
+ ...(inserted ? [db.delete(users).where(eq(users.id, userId))] : []),
+ ]);
+ if (cleanup.some((result) => result.status === "rejected")) {
+ return NextResponse.json({ error: "Account creation failed and cleanup could not finish. Check the account and Cloudflare routing before retrying." }, { status: 502 });
+ }
+ const cause = error instanceof Error ? error.cause : null;
+ if (/UNIQUE constraint failed/i.test(`${error} ${cause}`)) {
+ return NextResponse.json({ error: "An email address is already assigned" }, { status: 409 });
+ }
+ return NextResponse.json({ error: "Failed to create account mailbox routing. Please try again." }, { status: 502 });
+ }
+}
diff --git a/src/app/api/accounts/route.ts b/src/app/api/accounts/route.ts
index aa98029..b5d46e9 100644
--- a/src/app/api/accounts/route.ts
+++ b/src/app/api/accounts/route.ts
@@ -1,20 +1,8 @@
import { NextResponse } from "next/server";
-import { eq } from "drizzle-orm";
import { getDb } from "@/db";
-import { mailboxes, users } from "@/db/schema";
-import { hashPassword } from "@/lib/auth/password";
-import { newId } from "@/lib/ids";
import { createUserAccountSchema } from "@/lib/validators";
-import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";
-import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";
-import type { CreateUserAccountInput } from "./types";
-import {
- accountListItemFromUser,
- getDomainForAdmin,
- getExistingMailbox,
- listAccountsForAdmin,
- requireTeamAdmin,
-} from "./utils";
+import { createAccountResponse } from "./create";
+import { accountListItemFromUser, listAccountsForAdmin, requireTeamAdmin } from "./utils";
export async function GET(request: Request) {
const access = await requireTeamAdmin(request);
@@ -28,59 +16,9 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const access = await requireTeamAdmin(request);
if (access.error) return access.error;
-
- const parsed = createUserAccountSchema.safeParse(await request.json());
+ const parsed = createUserAccountSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
-
- const input: CreateUserAccountInput = parsed.data;
- const db = getDb(access.env);
- const domain = await getDomainForAdmin(db, access.user!.id, input.domainId);
- if (!domain) return NextResponse.json({ error: "Domain not found" }, { status: 404 });
- const username = input.username.toLowerCase().trim();
- const email = `${username}@${domain.hostname}`;
- const [existing] = await db.select({ id: users.id }).from(users).where(eq(users.email, email)).limit(1);
- if (existing) return NextResponse.json({ error: "Email already registered" }, { status: 409 });
- const mailbox = await getExistingMailbox(db, domain.id, username);
- if (mailbox) return NextResponse.json({ error: "Email address is already assigned" }, { status: 409 });
-
- const userId = newId("usr");
- try {
- await ensureEmailRoutingRuleToWorker(access.env, domain.zoneId, email);
- const [account] = await db
- .insert(users)
- .values({
- id: userId,
- email,
- passwordHash: hashPassword(input.password),
- name: username,
- role: input.role,
- createdByUserId: access.user!.id,
- })
- .returning({
- id: users.id,
- email: users.email,
- name: users.name,
- resetEmail: users.resetEmail,
- role: users.role,
- disabled: users.disabled,
- createdAt: users.createdAt,
- });
- const mailboxId = newId("mbx");
- await db.insert(mailboxes).values({
- id: mailboxId,
- userId,
- domainId: domain.id,
- localPart: username,
- displayName: username,
- });
- await ensureMailboxDomainRouting(access.env, db, { id: mailboxId, domainId: domain.id, localPart: username, useAllDomains: true });
-
- return NextResponse.json({ account: accountListItemFromUser(account) }, { status: 201 });
- } catch (error) {
- await db.delete(users).where(eq(users.id, userId));
- const message = error instanceof Error ? error.message : "Failed to create account mailbox";
- return NextResponse.json({ error: message }, { status: 502 });
- }
+ return createAccountResponse(access.env, access.user!.id, parsed.data);
}
diff --git a/src/app/api/accounts/types.d.ts b/src/app/api/accounts/types.d.ts
index d79d7df..77a2bd7 100644
--- a/src/app/api/accounts/types.d.ts
+++ b/src/app/api/accounts/types.d.ts
@@ -19,12 +19,7 @@ export type CreateAccountResult = {
error?: unknown;
};
-export type CreateUserAccountInput = {
- username: string;
- domainId: string;
- password: string;
- role: "admin" | "user";
-};
+export type CreateUserAccountInput = import("zod").output<typeof import("@/lib/validators").createUserAccountSchema>;
export type AccountListResponse = {
accounts?: AccountListItem[];
diff --git a/src/app/api/v1/accounts/utils.ts b/src/app/api/v1/accounts/utils.ts
index 99db8c7..540c624 100644
--- a/src/app/api/v1/accounts/utils.ts
+++ b/src/app/api/v1/accounts/utils.ts
@@ -2,14 +2,11 @@ import { NextResponse } from "next/server";
import { eq, or } from "drizzle-orm";
import { getEnv } from "@/lib/cloudflare";
import { getDb } from "@/db";
-import { mailboxes, users } from "@/db/schema";
+import { users } from "@/db/schema";
import { authenticateAdminApiKey, canManageAdminAccounts } from "@/lib/api/admin-auth";
-import { hashPassword } from "@/lib/auth/password";
-import { newId } from "@/lib/ids";
import { createUserAccountSchema } from "@/lib/validators";
-import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";
-import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";
-import { accountListItemFromUser, getDomainForAdmin, getExistingMailbox } from "@/app/api/accounts/utils";
+import { accountListItemFromUser } from "@/app/api/accounts/utils";
+import { createAccountResponse } from "@/app/api/accounts/create";
export async function GET(request: Request) {
const env = getEnv();
@@ -27,30 +24,5 @@ export async function POST(request: Request) {
if (!(await canManageAdminAccounts(env))) return NextResponse.json({ error: "A Team license is required to manage accounts" }, { status: 403 });
const parsed = createUserAccountSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
- const db = getDb(env);
- const domain = await getDomainForAdmin(db, auth.userId, parsed.data.domainId);
- if (!domain) return NextResponse.json({ error: "Domain not found" }, { status: 404 });
- const username = parsed.data.username.toLowerCase().trim();
- const email = `${username}@${domain.hostname}`;
- const [existing] = await db.select({ id: users.id }).from(users).where(eq(users.email, email)).limit(1);
- if (existing || await getExistingMailbox(db, domain.id, username)) return NextResponse.json({ error: "Email address is already assigned" }, { status: 409 });
- const userId = newId("usr");
- try {
- await ensureEmailRoutingRuleToWorker(env, domain.zoneId, email);
- const [account] = await db.insert(users).values({
- id: userId,
- email,
- passwordHash: hashPassword(parsed.data.password),
- name: username,
- role: parsed.data.role,
- createdByUserId: auth.userId,
- }).returning();
- const mailboxId = newId("mbx");
- await db.insert(mailboxes).values({ id: mailboxId, userId, domainId: domain.id, localPart: username, displayName: username });
- await ensureMailboxDomainRouting(env, db, { id: mailboxId, domainId: domain.id, localPart: username, useAllDomains: true });
- return NextResponse.json({ account: accountListItemFromUser(account) }, { status: 201 });
- } catch (error) {
- await db.delete(users).where(eq(users.id, userId));
- return NextResponse.json({ error: error instanceof Error ? error.message : "Failed to create account mailbox" }, { status: 502 });
- }
+ return createAccountResponse(env, auth.userId, parsed.data);
}
diff --git a/src/lib/cloudflare-api.ts b/src/lib/cloudflare-api.ts
index 2cdb610..892f148 100644
--- a/src/lib/cloudflare-api.ts
+++ b/src/lib/cloudflare-api.ts
@@ -1,6 +1,7 @@
import type {
CfDnsRecord,
CfEmailRoutingRule,
+ CfEmailRoutingRuleChange,
CfResponse,
CfSendingSubdomain,
} from "@/lib/cloudflare-api.types";
@@ -218,6 +219,7 @@ export async function ensureEmailRoutingRuleToWorker(
env: CloudflareEnv,
zoneId: string,
address: string,
+ changes?: CfEmailRoutingRuleChange[],
) {
if (zoneId === "manual") return;
const normalized = address.toLowerCase();
@@ -227,6 +229,7 @@ export async function ensureEmailRoutingRuleToWorker(
if (existing?.enabled) return existing;
if (existing?.id) {
+ changes?.push({ zoneId, ruleId: existing.id, previous: existing });
return cfRequest<CfEmailRoutingRule>(
env,
`/zones/${zoneId}/email/routing/rules/${existing.id}`,
@@ -243,7 +246,26 @@ export async function ensureEmailRoutingRuleToWorker(
);
}
- return createEmailRoutingRuleToWorker(env, zoneId, normalized);
+ const created = await createEmailRoutingRuleToWorker(env, zoneId, normalized);
+ if (created.id) changes?.push({ zoneId, ruleId: created.id });
+ return created;
+}
+
+/** Undo only the rules created or re-enabled by a failed provisioning attempt. */
+export async function rollbackEmailRoutingRuleChanges(env: CloudflareEnv, changes: CfEmailRoutingRuleChange[]) {
+ const results = await Promise.allSettled(changes.map(({ zoneId, ruleId, previous }) =>
+ previous
+ ? cfRequest(env, `/zones/${zoneId}/email/routing/rules/${ruleId}`, {
+ method: "PUT",
+ body: JSON.stringify({
+ actions: previous.actions, enabled: previous.enabled, matchers: previous.matchers,
+ name: previous.name, priority: previous.priority,
+ }),
+ })
+ : deleteEmailRoutingRule(env, zoneId, ruleId),
+ ));
+ const failures = results.filter((result) => result.status === "rejected");
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Unable to restore routing rules");
}
export async function deleteEmailRoutingRuleForAddress(
diff --git a/src/lib/cloudflare-api.types.d.ts b/src/lib/cloudflare-api.types.d.ts
index c821408..077c847 100644
--- a/src/lib/cloudflare-api.types.d.ts
+++ b/src/lib/cloudflare-api.types.d.ts
@@ -62,3 +62,9 @@ export type CfSendingSubdomain = {
created?: string;
modified?: string;
};
+
+export type CfEmailRoutingRuleChange = {
+ zoneId: string;
+ ruleId: string;
+ previous?: CfEmailRoutingRule;
+};
diff --git a/src/lib/mailboxes/domain-addresses.ts b/src/lib/mailboxes/domain-addresses.ts
index ce8575e..61f61c1 100644
--- a/src/lib/mailboxes/domain-addresses.ts
+++ b/src/lib/mailboxes/domain-addresses.ts
@@ -4,6 +4,7 @@ import { domains, mailboxAliases, mailboxes } from "@/db/schema";
import { deleteEmailRoutingRuleForAddress, ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";
import { normalizeRecipientLocalPart } from "@/lib/email/recipient-address";
import type { MailboxDomainAddressInput } from "./domain-addresses-types";
+import type { CfEmailRoutingRuleChange } from "@/lib/cloudflare-api.types";
export async function getMailboxAliasAddresses(
db: AppDatabase,
@@ -75,6 +76,7 @@ export async function ensureMailboxDomainRouting(
env: CloudflareEnv,
db: AppDatabase,
mailbox: MailboxDomainAddressInput,
+ changes?: CfEmailRoutingRuleChange[],
): Promise<void> {
const addresses = await getMailboxDomainAddresses(db, mailbox);
if (addresses.length === 0) return;
@@ -90,13 +92,16 @@ export async function ensureMailboxDomainRouting(
.where(eq(domains.userId, primaryDomain.userId));
const domainsByHostname = new Map(availableDomains.map((domain) => [domain.hostname.toLowerCase(), domain]));
- await Promise.all(
+ // Wait for every request before a caller rolls back a failed attempt.
+ const results = await Promise.allSettled(
addresses.map(async (address) => {
const hostname = address.slice(address.lastIndexOf("@") + 1);
const domain = domainsByHostname.get(hostname);
- if (domain) await ensureEmailRoutingRuleToWorker(env, domain.zoneId, address);
+ if (domain) await ensureEmailRoutingRuleToWorker(env, domain.zoneId, address, changes);
}),
);
+ const failure = results.find((result) => result.status === "rejected");
+ if (failure?.status === "rejected") throw failure.reason;
}
export async function removeMailboxDomainRouting(
diff --git a/src/lib/mcp/admin-tools.ts b/src/lib/mcp/admin-tools.ts
index 34e971f..40024b8 100644
--- a/src/lib/mcp/admin-tools.ts
+++ b/src/lib/mcp/admin-tools.ts
@@ -55,7 +55,7 @@ export function registerAdminMcpTools(server: McpServer, principal: McpPrincipal
});
if (principal.scopes.includes("accounts")) server.registerTool("manage_accounts", {
- description: "List, inspect, create, or update managed accounts. Actions: list, get, create, update. Pass id for get or update and data for create or update. Requires a Team license.",
+ description: "List, inspect, create, or update managed accounts. Actions: list, get, create, update. Pass id for get or update and data for create or update. For create, data accepts username, domainId, password, role?, useAllDomains? (defaults to true for compatibility), and aliases?: [{ domainId, localPart }]. Set useAllDomains to false to assign only the primary address and explicit aliases. Requires a Team license.",
inputSchema: adminInput,
}, async ({ action, id, data }) => {
if (!principal.scopes.includes("accounts")) return result({ error: "Permission denied" }, true);
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index be4e616..4dccafe 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -145,11 +145,20 @@ export const createAccountSchema = z.object({
),
});
+export const createMailboxAliasSchema = z.object({
+ domainId: z.string().min(1),
+ localPart: z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._%+-]+$/)
+ .transform((value) => value.toLowerCase()),
+});
+
export const createUserAccountSchema = z.object({
username: z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._%+-]+$/),
domainId: z.string().min(1),
password: z.string().min(8).max(128),
role: z.enum(["admin", "user"]).default("user"),
+ // Existing API/MCP clients retain the previous behavior when this is omitted.
+ useAllDomains: z.boolean().default(true),
+ aliases: z.array(createMailboxAliasSchema).default([]),
});
export const updateAccountSchema = z.object({
@@ -187,17 +196,6 @@ export const updateMailboxSchema = z.object({
useAllDomains: z.boolean().optional(),
});
-export const createMailboxAliasSchema = z.object({
- domainId: z.string().min(1),
- localPart: z
- .string()
- .trim()
- .min(1)
- .max(64)
- .regex(/^[a-zA-Z0-9._%+-]+$/)
- .transform((value) => value.toLowerCase()),
-});
-
export const folderSchema = z.object({
mailboxId: z.string().min(1),
name: z.string().trim().min(1).max(80),
diff --git a/tests/account-alias-selection.test.mjs b/tests/account-alias-selection.test.mjs
new file mode 100644
index 0000000..6b21b13
--- /dev/null
+++ b/tests/account-alias-selection.test.mjs
@@ -0,0 +1,273 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const directory = mkdtempSync(join(root, "node_modules", "mailflare-account-test-"));
+after(() => rmSync(directory, { recursive: true, force: true }));
+await build({
+ stdin: {
+ contents: `
+ export { SqliteDatabase } from "./server/runtime/sqlite-database.ts";
+ export { applyMigrations } from "./server/runtime/migrate.ts";
+ export { getDb } from "./src/db/index.ts";
+ export { createSession } from "./src/lib/auth/session.ts";
+ export { generateApiKey } from "./src/lib/api-keys.ts";
+ export { createUserAccountSchema } from "./src/lib/validators.ts";
+ export { POST as dashboardCreate } from "./src/app/api/accounts/route.ts";
+ export { POST as apiCreate } from "./src/app/api/v1/accounts/route.ts";
+ export { registerAdminMcpTools } from "./src/lib/mcp/admin-tools.ts";
+ export { getMailboxDomainAddresses } from "./src/lib/mailboxes/domain-addresses.ts";
+ export { resolveInboundAddress } from "./src/lib/email/routing.ts";
+ export { getAuthorizedSenderAddress } from "./src/lib/email/sender.ts";
+ `,
+ resolveDir: root,
+ sourcefile: "account-alias-test-entry.ts",
+ },
+ outfile: join(directory, "entry.mjs"),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node24",
+ tsconfig: join(root, "tsconfig.json"),
+ packages: "external",
+ alias: { "next/headers": "next/headers.js", "next/server": "next/server.js", "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" },
+ logLevel: "silent",
+});
+const {
+ SqliteDatabase, applyMigrations, getDb, createSession, generateApiKey, createUserAccountSchema,
+ dashboardCreate, apiCreate, registerAdminMcpTools, getMailboxDomainAddresses, resolveInboundAddress, getAuthorizedSenderAddress,
+} = await import(pathToFileURL(join(directory, "entry.mjs")).href);
+const key = generateApiKey();
+
+async function fixture(t, { rules = [], failAddress, slowAddress } = {}) {
+ const database = new SqliteDatabase(":memory:");
+ t.after(() => database.db.close());
+ await applyMigrations(database, join(root, "drizzle/migrations"));
+ database.db.exec(`
+ INSERT INTO users (id, email, password_hash, name, role, created_at) VALUES
+ ('admin', '[email protected]', 'hash', 'Owner', 'admin', 1),
+ ('other', '[email protected]', 'hash', 'Other', 'admin', 1);
+ INSERT INTO domains (id, user_id, hostname, zone_id, status, created_at) VALUES
+ ('one', 'admin', 'one.test', 'zone-one', 'active', 1),
+ ('two', 'admin', 'two.test', 'zone-two', 'active', 1),
+ ('pending', 'admin', 'pending.test', 'zone-pending', 'pending', 1),
+ ('foreign', 'other', 'foreign.test', 'zone-foreign', 'active', 1);
+ INSERT INTO license_settings (id, instance_id, plan, state, features, updated_at)
+ VALUES ('default', 'test-instance', 'team', 'active', '[]', 1);
+ `);
+ database.db.prepare("INSERT INTO api_keys (id, user_id, name, prefix, key_hash, scopes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
+ .run("key", "admin", "Test", key.prefix, key.hash, '["accounts"]', 1);
+ const env = { DB: database, CF_TOKEN: "test-only", MAILFLARE_RUNTIME: "node" };
+ globalThis.__mailflareNodeEnv = env;
+ t.after(() => { delete globalThis.__mailflareNodeEnv; });
+ const session = await createSession(env, "admin");
+ const currentRules = structuredClone(rules);
+ const calls = [];
+ let nextRule = 0;
+ t.mock.method(globalThis, "fetch", async (url, init = {}) => {
+ const parsed = new URL(url);
+ assert.equal(parsed.origin, "https://api.cloudflare.com", "tests must never contact a real service");
+ const match = parsed.pathname.match(/^\/client\/v4\/zones\/([^/]+)\/email\/routing\/rules(?:\/([^/]+))?$/);
+ assert.ok(match, parsed.pathname);
+ const [, zoneId, ruleId] = match;
+ const method = init.method ?? "GET";
+ const body = init.body ? JSON.parse(init.body) : null;
+ calls.push({ method, zoneId, ruleId, body });
+ if (method === "GET") return Response.json({ success: true, result: structuredClone(currentRules.filter((rule) => rule.zoneId === zoneId)) });
+ const address = body?.matchers?.[0]?.value;
+ if (slowAddress && address === slowAddress) await new Promise((resolve) => setTimeout(resolve, 20));
+ if (failAddress && address === failAddress) return Response.json({ success: false, errors: [{ message: "Simulated routing failure" }] }, { status: 502 });
+ if (method === "POST") {
+ const rule = { ...body, id: `new-${++nextRule}`, zoneId };
+ currentRules.push(rule);
+ return Response.json({ success: true, result: rule });
+ }
+ const index = currentRules.findIndex((rule) => rule.id === ruleId && rule.zoneId === zoneId);
+ assert.notEqual(index, -1);
+ if (method === "DELETE") currentRules.splice(index, 1);
+ if (method === "PUT") currentRules[index] = { ...body, id: ruleId, zoneId };
+ return Response.json({ success: true, result: currentRules[index] ?? null });
+ });
+ const post = (kind, overrides = {}, token) => {
+ const handler = kind === "dashboard" ? dashboardCreate : apiCreate;
+ return handler(new Request(`https://mailflare.test/api/${kind === "dashboard" ? "" : "v1/"}accounts`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${token ?? (kind === "dashboard" ? session : key.fullKey)}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ username: "sam", domainId: "one", password: "test-password", ...overrides }),
+ }));
+ };
+ const mailbox = () => {
+ const row = database.db.prepare("SELECT * FROM mailboxes WHERE local_part = 'sam'").get();
+ return row && { id: row.id, userId: row.user_id, domainId: row.domain_id, localPart: row.local_part, useAllDomains: !!row.use_all_domains };
+ };
+ return { database, env, db: getDb(env), post, mailbox, calls, currentRules };
+}
+
+for (const kind of ["dashboard", "api"]) {
+ test(`${kind}: primary-only creation does not grant addresses on other domains`, async (t) => {
+ const f = await fixture(t);
+ assert.equal((await f.post(kind, { useAllDomains: false })).status, 201);
+ const mailbox = f.mailbox();
+ assert.equal(mailbox.useAllDomains, false);
+ assert.deepEqual(await getMailboxDomainAddresses(f.db, mailbox), ["[email protected]"]);
+ assert.equal((await resolveInboundAddress(f.db, "[email protected]")).mailbox.mailboxId, mailbox.id);
+ assert.equal(await resolveInboundAddress(f.db, "[email protected]"), null);
+ await assert.rejects(getAuthorizedSenderAddress(f.env, { userId: mailbox.userId, mailboxId: mailbox.id, from: "[email protected]" }), /Sender address/);
+ assert.deepEqual(f.calls.filter((call) => call.method === "POST").map((call) => call.body.matchers[0].value), ["[email protected]"]);
+ });
+
+ test(`${kind}: explicit aliases receive and send through the same mailbox`, async (t) => {
+ const f = await fixture(t);
+ const response = await f.post(kind, { useAllDomains: false, aliases: [{ domainId: "two", localPart: " Sales " }, { domainId: "one", localPart: "support" }] });
+ assert.equal(response.status, 201);
+ const body = await response.json();
+ assert.equal(body.account.email, "[email protected]");
+ assert.equal("passwordHash" in body.account, false);
+ const mailbox = f.mailbox();
+ assert.deepEqual((await getMailboxDomainAddresses(f.db, mailbox)).sort(), ["[email protected]", "[email protected]", "[email protected]"]);
+ assert.equal((await resolveInboundAddress(f.db, "[email protected]")).mailbox.mailboxId, mailbox.id);
+ assert.equal((await getAuthorizedSenderAddress(f.env, { userId: mailbox.userId, mailboxId: mailbox.id, from: "[email protected]" })).mailboxId, mailbox.id);
+ assert.equal(await resolveInboundAddress(f.db, "[email protected]"), null);
+ f.database.db.exec("INSERT INTO domains (id, user_id, hostname, zone_id, status, created_at) VALUES ('later', 'admin', 'later.test', 'manual', 'active', 1)");
+ assert.equal(await resolveInboundAddress(f.db, "[email protected]"), null);
+ assert.equal((await getMailboxDomainAddresses(f.db, mailbox)).includes("[email protected]"), false);
+ });
+}
+
+test("omitted settings preserve API compatibility; opting in includes future domains", async (t) => {
+ const f = await fixture(t);
+ assert.equal((await f.post("api")).status, 201);
+ assert.equal(f.mailbox().useAllDomains, true);
+ assert.deepEqual(await getMailboxDomainAddresses(f.db, f.mailbox()), ["[email protected]", "[email protected]"]);
+ f.database.db.exec("INSERT INTO domains (id, user_id, hostname, zone_id, status, created_at) VALUES ('later', 'admin', 'later.test', 'manual', 'active', 1)");
+ assert.equal((await resolveInboundAddress(f.db, "[email protected]")).mailbox.mailboxId, f.mailbox().id);
+ assert.equal((await f.post("dashboard", { username: "jane", useAllDomains: true, aliases: [{ domainId: "two", localPart: "billing" }] })).status, 201);
+ const address = await resolveInboundAddress(f.db, "[email protected]");
+ assert.equal(address.mailbox.localPart, "jane");
+});
+
+test("admin MCP forwards alias selection to the same account creation handler", async (t) => {
+ const f = await fixture(t);
+ const handlers = new Map();
+ registerAdminMcpTools({ registerTool: (name, _schema, handler) => handlers.set(name, handler) }, { scopes: ["accounts"] }, "https://mailflare.test", `Bearer ${key.fullKey}`);
+ const result = await handlers.get("manage_accounts")({ action: "create", data: { username: "sam", domainId: "one", password: "test-password", useAllDomains: false, aliases: [{ domainId: "two", localPart: "sales" }] } });
+ assert.equal(result.isError, false);
+ assert.equal(JSON.parse(result.content[0].text).status, 201);
+ assert.deepEqual((await getMailboxDomainAddresses(f.db, f.mailbox())).sort(), ["[email protected]", "[email protected]"]);
+});
+
+test("invalid, duplicate, foreign, and inactive aliases fail before provisioning", async (t) => {
+ const f = await fixture(t);
+ for (const aliases of [
+ [{ domainId: "one", localPart: "s.a.m+tag" }],
+ [{ domainId: "two", localPart: "sales" }, { domainId: "two", localPart: "SALES" }],
+ [{ domainId: "foreign", localPart: "sales" }],
+ [{ domainId: "pending", localPart: "sales" }],
+ [{ domainId: "missing", localPart: "sales" }],
+ [{ domainId: "two", localPart: "not an address" }],
+ [{ domainId: "two", localPart: "+tag" }],
+ ]) {
+ assert.equal((await f.post("api", { useAllDomains: false, aliases })).status, 400, JSON.stringify(aliases));
+ }
+ assert.equal(f.calls.length, 0);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM users").get().count, 2);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM mailbox_aliases").get().count, 0);
+});
+
+test("mailbox and alias conflicts include normalized primary addresses", async (t) => {
+ const f = await fixture(t);
+ f.database.db.exec(`
+ INSERT INTO mailboxes (id, user_id, domain_id, local_part, created_at) VALUES ('existing', 'admin', 'two', 'sales', 1);
+ INSERT INTO mailbox_aliases (id, mailbox_id, domain_id, local_part, created_at) VALUES ('alias', 'existing', 'one', 'support', 1);
+ `);
+ for (const input of [
+ { aliases: [{ domainId: "two", localPart: "s.a.l.e.s+tag" }] },
+ { aliases: [{ domainId: "one", localPart: "SUPPORT" }] },
+ { username: "support" },
+ { username: "s.u.p.p.o.r.t+tag" },
+ ]) assert.equal((await f.post("dashboard", { useAllDomains: false, ...input })).status, 409);
+ assert.equal(f.calls.length, 0);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM users").get().count, 2);
+});
+
+test("explicit addresses take precedence over implicit all-domain aliases", async (t) => {
+ const f = await fixture(t);
+ f.database.db.exec("INSERT INTO mailboxes (id, user_id, domain_id, local_part, use_all_domains, created_at) VALUES ('existing', 'admin', 'one', 'sales', 1, 1)");
+ assert.equal((await f.post("api", { useAllDomains: false, aliases: [{ domainId: "two", localPart: "sales" }] })).status, 201);
+ assert.equal((await resolveInboundAddress(f.db, "[email protected]")).mailbox.mailboxId, f.mailbox().id);
+ assert.equal((await resolveInboundAddress(f.db, "[email protected]")).mailbox.mailboxId, "existing");
+});
+
+test("database failures leave no partial account, aliases, or routing rules", async (t) => {
+ const f = await fixture(t);
+ f.database.db.exec("CREATE TRIGGER fail_alias BEFORE INSERT ON mailbox_aliases WHEN NEW.local_part = 'alias40' BEGIN SELECT RAISE(ABORT, 'Simulated insert failure'); END");
+ const aliases = Array.from({ length: 41 }, (_, i) => ({ domainId: "two", localPart: `alias${i}` }));
+ assert.equal((await f.post("api", { useAllDomains: false, aliases })).status, 502);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM users").get().count, 2);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM mailboxes").get().count, 0);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM mailbox_aliases").get().count, 0);
+ assert.equal(f.calls.length, 0);
+});
+
+function workerRule(id, address, enabled) {
+ return { id, zoneId: "zone-one", enabled, name: "Existing route", priority: 20, actions: [{ type: "worker", value: ["mailflare"] }], matchers: [{ type: "literal", field: "to", value: address }] };
+}
+
+for (const enabled of [true, false]) {
+ test(`routing failure cleans up completed requests and preserves a previously ${enabled ? "enabled" : "disabled"} rule`, async (t) => {
+ const original = workerRule("old", "[email protected]", enabled);
+ const f = await fixture(t, { rules: [original], failAddress: "[email protected]", slowAddress: "[email protected]" });
+ const response = await f.post("api", { useAllDomains: false, aliases: [{ domainId: "two", localPart: "slow" }, { domainId: "two", localPart: "broken" }] });
+ assert.equal(response.status, 502);
+ assert.deepEqual(f.currentRules, [original]);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM users").get().count, 2);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM mailboxes").get().count, 0);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM mailbox_aliases").get().count, 0);
+ assert.ok(f.calls.some((call) => call.method === "DELETE"), "a successfully provisioned alias must be rolled back");
+ });
+}
+
+test("account creation still enforces admin authorization and the Team license", async (t) => {
+ const f = await fixture(t);
+ assert.equal((await f.post("api", {}, "invalid-test-key")).status, 401);
+ assert.equal((await f.post("dashboard", {}, "invalid-test-session")).status, 403);
+ f.database.db.exec("UPDATE license_settings SET state = 'inactive'");
+ assert.equal((await f.post("api")).status, 403);
+ assert.equal((await f.post("dashboard")).status, 403);
+ assert.equal(f.calls.length, 0);
+});
+
+for (const separateDomains of [false, true]) {
+ test(`more than 50 aliases on ${separateDomains ? "separate domains" : "one domain"} stay within database parameter limits`, async (t) => {
+ const f = await fixture(t);
+ f.database.db.exec("UPDATE domains SET zone_id = 'manual'");
+ const aliases = Array.from({ length: 125 }, (_, i) => ({ domainId: separateDomains ? `domain${i}` : "two", localPart: `alias${i}` }));
+ if (separateDomains) {
+ const insert = f.database.db.prepare("INSERT INTO domains (id, user_id, hostname, zone_id, status, created_at) VALUES (?, 'admin', ?, 'manual', 'active', 1)");
+ for (const alias of aliases) insert.run(alias.domainId, `${alias.domainId}.test`);
+ }
+ const prepare = f.database.prepare.bind(f.database);
+ t.mock.method(f.database, "prepare", (query) => {
+ const statement = prepare(query);
+ const bind = statement.bind.bind(statement);
+ statement.bind = (...values) => {
+ assert.ok(values.length <= 100, "each statement must fit D1's 100-parameter limit");
+ return bind(...values);
+ };
+ return statement;
+ });
+ assert.equal((await f.post("api", { useAllDomains: false, aliases })).status, 201);
+ assert.equal(f.database.db.prepare("SELECT count(*) AS count FROM mailbox_aliases").get().count, 125);
+ assert.equal((await getMailboxDomainAddresses(f.db, f.mailbox())).length, 126);
+ assert.equal(f.calls.length, 0);
+ });
+}
+
+test("the all-domain boolean rejects truthy strings", () => {
+ const input = { username: "sam", domainId: "one", password: "test-password" };
+ assert.equal(createUserAccountSchema.safeParse({ ...input, useAllDomains: "false" }).success, false);
+});