Skip to content

Email for professionals and teams

Improve setup page

Hieu Nguyen (Jack)cffd4b142fdd
diff --git a/README.md b/README.md
index a64d94d..97ce802 100644
--- a/README.md
+++ b/README.md
@@ -106,7 +106,10 @@ Deploy with Wrangler or the Cloudflare Git integration so the Durable Object cla
When the socket is temporarily unavailable, the client retries automatically and uses a slower
fallback refresh until the connection recovers.
-Register at `/register`, complete `/onboarding`, or seed dev data:
+Complete first-run configuration at `/setup`, or seed dev data. The first setup step checks the
+required Cloudflare runtime configuration and initializes the schema when the bound D1 database is
+empty. Existing databases are never migrated by the setup page; apply later migrations with the
+normal Wrangler migration command.
```bash
curl -X POST http://localhost:3000/api/seed
@@ -131,6 +134,13 @@ Required setup values:
- `CF_AID` — optional unless your token can access multiple accounts.
- `CF_EMAIL_WORKER_NAME` — must match the deployed Worker name. If the one-click deploy flow asks for a different Worker name, enter that same value here.
+### Database backup workflow binding
+
+Manual and scheduled database backups require the `DATABASE_BACKUP_WORKFLOW` binding declared in
+`wrangler.jsonc`. If the backup page reports that the binding is missing, deploy the complete Worker
+with `npm run deploy`; `next dev` and source-only updates may not provision new Cloudflare bindings.
+The backup also requires `CF_AID`, `D1_DATABASE_ID`, and `D1_BACKUP_TOKEN` at runtime.
+
### Dashboard updates
The admin overview includes an **Update Mailflare** button. `POST /api/admin/update` dispatches
diff --git a/env.d.ts b/env.d.ts
index c68eef8..47e9fe9 100644
--- a/env.d.ts
+++ b/env.d.ts
@@ -10,7 +10,7 @@ interface CloudflareEnv {
REALTIME: DurableObjectNamespace<
import("./src/lib/realtime/hub").RealtimeHub
>;
- DATABASE_BACKUP_WORKFLOW: Workflow<import("./src/lib/backups/types").BackupWorkflowParams>;
+ DATABASE_BACKUP_WORKFLOW?: Workflow<import("./src/lib/backups/types").BackupWorkflowParams>;
LOGIN_RATE_LIMIT?: RateLimit;
CF_TOKEN?: string;
CF_API_KEY?: string;
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index 34c5ab6..181ece3 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -51,7 +51,7 @@ export async function POST(request: Request) {
const response = NextResponse.json({
ok: true,
token,
- redirect: hasMailboxes ? "/inbox" : "/onboarding",
+ redirect: hasMailboxes ? "/inbox" : "/setup",
});
response.headers.set("Cache-Control", "no-store");
response.cookies.set(SESSION_COOKIE, token, {
diff --git a/src/app/api/backups/route.ts b/src/app/api/backups/route.ts
index b89a43d..b272c22 100644
--- a/src/app/api/backups/route.ts
+++ b/src/app/api/backups/route.ts
@@ -10,6 +10,10 @@ import {
listBackups,
updateBackupSettings,
} from "@/lib/backups/service";
+import {
+ BackupWorkflowUnavailableError,
+ getBackupWorkflowBinding,
+} from "@/lib/backups/utils";
import { getEnv } from "@/lib/cloudflare";
import { parseBackupSettingsInput } from "./utils";
@@ -48,9 +52,10 @@ export async function PUT(request: Request) {
export async function POST(request: Request) {
try {
const { env, user } = await requireAdmin(request);
+ const workflow = getBackupWorkflowBinding(env);
const backupId = await createBackupRecord(env, "manual", user.id);
try {
- await env.DATABASE_BACKUP_WORKFLOW.create({
+ await workflow.create({
id: `database-backup-${backupId}`,
params: { backupId, force: true },
});
@@ -65,6 +70,7 @@ export async function POST(request: Request) {
return NextResponse.json({ backupId }, { status: 202 });
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to start backup";
- return NextResponse.json({ error: message }, { status: 400 });
+ const status = error instanceof BackupWorkflowUnavailableError ? 503 : 400;
+ return NextResponse.json({ error: message }, { status });
}
}
diff --git a/src/app/api/setup/prepare/route.ts b/src/app/api/setup/prepare/route.ts
new file mode 100644
index 0000000..b59e617
--- /dev/null
+++ b/src/app/api/setup/prepare/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from "next/server";
+import { hasAdminAccount } from "@/lib/auth/setup";
+import { getEnv } from "@/lib/cloudflare";
+import { getSetupRequirementChecks } from "@/lib/setup/configuration";
+import { migrateCleanDatabase } from "@/lib/setup/migration";
+
+export async function POST() {
+ const env = getEnv();
+ if (await hasAdminAccount(env)) {
+ return NextResponse.json({ error: "Initial setup is already complete" }, { status: 403 });
+ }
+
+ const checks = getSetupRequirementChecks(env);
+ if (checks.some((check) => !check.configured)) {
+ return NextResponse.json({ checks, migrated: false }, { status: 503 });
+ }
+
+ try {
+ const migrated = await migrateCleanDatabase(env.DB);
+ return NextResponse.json({ checks, migrated });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Database preparation failed";
+ return NextResponse.json({ checks, migrated: false, error: message }, { status: 500 });
+ }
+}
diff --git a/src/app/api/setup/status/route.ts b/src/app/api/setup/status/route.ts
index af920c9..b9e658f 100644
--- a/src/app/api/setup/status/route.ts
+++ b/src/app/api/setup/status/route.ts
@@ -5,15 +5,20 @@ import { getPrimaryDomain } from "@/lib/user";
export async function GET() {
const env = getEnv();
- const [adminAccountExists, domain] = await Promise.all([
- hasAdminAccount(env),
- getPrimaryDomain(env),
- ]);
- return NextResponse.json({
- hasAdminAccount: adminAccountExists,
- hasPrimaryDomain: !!domain,
- primaryDomain: domain ? { hostname: domain.hostname } : null,
- }, {
- headers: { "Cache-Control": "no-store" },
- });
+ try {
+ const [adminAccountExists, domain] = await Promise.all([
+ hasAdminAccount(env),
+ getPrimaryDomain(env),
+ ]);
+ return NextResponse.json({
+ hasAdminAccount: adminAccountExists,
+ hasPrimaryDomain: !!domain,
+ primaryDomain: domain ? { hostname: domain.hostname } : null,
+ }, {
+ headers: { "Cache-Control": "no-store" },
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Could not load setup status";
+ return NextResponse.json({ error: message }, { status: 500 });
+ }
}
diff --git a/src/app/login/login-client.tsx b/src/app/login/login-client.tsx
index 8b08d8b..917e31b 100644
--- a/src/app/login/login-client.tsx
+++ b/src/app/login/login-client.tsx
@@ -1,29 +1,21 @@
"use client";
-import Link from "next/link";
import { useRouter } from "next/navigation";
-import { useEffect, useState } from "react";
-import { ArrowRight, Mail } from "lucide-react";
+import { useState } from "react";
+import { Mail } from "lucide-react";
import { AuthShell } from "@/components/auth/auth-shell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { TurnstileField } from "@/components/auth/turnstile";
-import { getRegistrationStatus, submitLogin } from "./utils";
+import { submitLogin } from "./utils";
export function LoginClient() {
const router = useRouter();
- const [registrationOpen, setRegistrationOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [turnstileReset, setTurnstileReset] = useState(0);
- useEffect(() => {
- void getRegistrationStatus()
- .then((status) => setRegistrationOpen(!status.hasAdminAccount))
- .catch(() => setRegistrationOpen(false));
- }, []);
-
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
@@ -45,15 +37,6 @@ export function LoginClient() {
icon={Mail}
title="Sign in"
description="Open your mailbox and continue from the same inbox workspace."
- footer={registrationOpen ? (
- <Link
- href="/register"
- className="inline-flex items-center gap-2 hover:underline"
- >
- Create account
- <ArrowRight className="h-4 w-4" />
- </Link>
- ) : undefined}
>
<form onSubmit={onSubmit} className="space-y-5">
<div className="space-y-2">
diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx
index 35c3cd5..b76645d 100644
--- a/src/app/login/page.tsx
+++ b/src/app/login/page.tsx
@@ -1,7 +1,14 @@
+import { redirect } from "next/navigation";
import { AuthGuard } from "@/components/auth/auth-guard";
+import { hasAdminAccount } from "@/lib/auth/setup";
+import { getEnv } from "@/lib/cloudflare";
import { LoginClient } from "./login-client";
-export default function LoginPage() {
+export const dynamic = "force-dynamic";
+
+export default async function LoginPage() {
+ if (!(await hasAdminAccount(getEnv()))) redirect("/setup");
+
return (
<AuthGuard mode="public">
<LoginClient />
diff --git a/src/app/login/types.d.ts b/src/app/login/types.d.ts
index 05446a0..b0f1b7b 100644
--- a/src/app/login/types.d.ts
+++ b/src/app/login/types.d.ts
@@ -3,7 +3,3 @@ export type LoginResult = {
redirect?: string;
error?: string;
};
-
-export type RegistrationStatus = {
- hasAdminAccount: boolean;
-};
diff --git a/src/app/login/utils.ts b/src/app/login/utils.ts
index df45476..650d999 100644
--- a/src/app/login/utils.ts
+++ b/src/app/login/utils.ts
@@ -1,14 +1,5 @@
import { persistAuthSession } from "@/lib/auth/client";
-import type { LoginResult, RegistrationStatus } from "./types";
-
-export async function getRegistrationStatus(): Promise<RegistrationStatus> {
- const response = await fetch("/api/setup/status", { cache: "no-store" });
- if (!response.ok) {
- throw new Error("Could not load registration status");
- }
-
- return (await response.json()) as RegistrationStatus;
-}
+import type { LoginResult } from "./types";
export async function submitLogin(form: FormData): Promise<{ ok: boolean; data: LoginResult }> {
const res = await fetch("/api/auth/login", {
diff --git a/src/app/onboarding/page.tsx b/src/app/onboarding/page.tsx
index 7552142..0df4a85 100644
--- a/src/app/onboarding/page.tsx
+++ b/src/app/onboarding/page.tsx
@@ -1,10 +1,5 @@
-import { AuthGuard } from "@/components/auth/auth-guard";
-import { OnboardingClient } from "./onboarding-client";
+import { redirect } from "next/navigation";
export default function OnboardingPage() {
- return (
- <AuthGuard>
- <OnboardingClient />
- </AuthGuard>
- );
+ redirect("/setup");
}
diff --git a/src/app/page.tsx b/src/app/page.tsx
index cd3736f..66cb6cc 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -76,7 +76,7 @@ export default function HomePage() {
</p>
<div className="mt-8 flex flex-col gap-3 sm:flex-row">
<Button size="lg" asChild className="rounded-full px-6">
- <Link href={actions.at(-1)?.href ?? "/register"}>
+ <Link href={actions.at(-1)?.href ?? "/setup"}>
{hasUser ? "Open dashboard" : "Create account"}
<ArrowRight className="h-4 w-4" />
</Link>
diff --git a/src/app/register/page.tsx b/src/app/register/page.tsx
index 96afc2c..869a496 100644
--- a/src/app/register/page.tsx
+++ b/src/app/register/page.tsx
@@ -1,10 +1,5 @@
-import { AuthGuard } from "@/components/auth/auth-guard";
-import { RegisterClient } from "./register-client";
+import { redirect } from "next/navigation";
export default function RegisterPage() {
- return (
- <AuthGuard mode="public">
- <RegisterClient />
- </AuthGuard>
- );
+ redirect("/setup");
}
diff --git a/src/app/register/register-client.tsx b/src/app/register/register-client.tsx
index 56293a6..a50685d 100644
--- a/src/app/register/register-client.tsx
+++ b/src/app/register/register-client.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
-import { ArrowRight, MailPlus } from "lucide-react";
+import { ArrowRight, CheckCircle2, LoaderCircle, MailPlus, XCircle } from "lucide-react";
import { useEffect, useState } from "react";
import { AuthShell } from "@/components/auth/auth-shell";
import { Button } from "@/components/ui/button";
@@ -11,9 +11,11 @@ import { Label } from "@/components/ui/label";
import { TurnstileField } from "@/components/auth/turnstile";
import {
getSetupStatus,
+ prepareSetup,
submitPrimaryDomain,
submitRegistration,
} from "./utils";
+import type { SetupRequirementCheck } from "./types";
export function RegisterClient() {
const router = useRouter();
@@ -23,24 +25,44 @@ export function RegisterClient() {
);
const [primaryDomain, setPrimaryDomain] = useState<string | null>(null);
const [setupDomain, setSetupDomain] = useState<string | null>(null);
- const [step, setStep] = useState<1 | 2>(1);
+ const [step, setStep] = useState<1 | 2 | 3>(1);
+ const [checks, setChecks] = useState<SetupRequirementCheck[]>([]);
+ const [databaseMigrated, setDatabaseMigrated] = useState(false);
+ const [preparationComplete, setPreparationComplete] = useState(false);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [turnstileReset, setTurnstileReset] = useState(0);
useEffect(() => {
- void getSetupStatus()
- .then((data) => {
- setHasAdminAccount(data.hasAdminAccount);
- setHasPrimaryDomain(data.hasPrimaryDomain);
- setPrimaryDomain(data.primaryDomain?.hostname ?? null);
- })
- .catch(() => {
- setHasAdminAccount(true);
- setHasPrimaryDomain(true);
- });
+ void runPreparation();
}, []);
+ async function runPreparation() {
+ setLoading(true);
+ setError(null);
+ setPreparationComplete(false);
+
+ try {
+ const preparation = await prepareSetup();
+ setChecks(preparation.data.checks ?? []);
+ setDatabaseMigrated(!!preparation.data.migrated);
+ if (!preparation.ok) {
+ setError(preparation.data.error ?? "Complete the missing configuration before continuing.");
+ return;
+ }
+
+ const data = await getSetupStatus();
+ setHasAdminAccount(data.hasAdminAccount);
+ setHasPrimaryDomain(data.hasPrimaryDomain);
+ setPrimaryDomain(data.primaryDomain?.hostname ?? null);
+ setPreparationComplete(true);
+ } catch (error) {
+ setError(error instanceof Error ? error.message : "Installation preparation failed");
+ } finally {
+ setLoading(false);
+ }
+ }
+
async function onDomainSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
@@ -57,7 +79,7 @@ export function RegisterClient() {
return;
}
setSetupDomain(data.domain.hostname);
- setStep(2);
+ setStep(3);
}
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
@@ -86,7 +108,7 @@ export function RegisterClient() {
}
const accountDomain = setupDomain ?? primaryDomain;
- const showDomainStep = hasPrimaryDomain === false && step === 1;
+ const showDomainStep = hasPrimaryDomain === false && step === 2;
if (hasAdminAccount === true) {
return (
@@ -122,31 +144,78 @@ export function RegisterClient() {
return (
<AuthShell
icon={MailPlus}
- title={showDomainStep ? "Add your domain" : "Create your mailbox"}
+ title={step === 1 ? "Prepare installation" : showDomainStep ? "Add your domain" : "Create your mailbox"}
// description={
// showDomainStep
// ? "Connect the primary Cloudflare zone first so routing records can be created before the first mailbox."
// : `Choose a mailbox username on ${accountDomain ?? "the primary domain"} and add a recovery email.`
// }
steps={
- hasAdminAccount === false && hasPrimaryDomain === false
- ? [
- { label: "Domain", active: step === 1 },
- { label: "Account", active: step === 2 },
- ]
- : undefined
- }
- footer={
- <Link
- href="/login"
- className="inline-flex items-center gap-2 hover:underline"
- >
- Sign in instead
- <ArrowRight className="h-4 w-4" />
- </Link>
+ [
+ { label: "System", active: step === 1 },
+ { label: "Domain", active: step === 2 },
+ { label: "Account", active: step === 3 },
+ ]
}
>
- {showDomainStep ? (
+ {step === 1 ? (
+ <div className="space-y-5">
+ <p className="text-sm leading-6 text-neutral-600">
+ Mailflare checks its required Cloudflare configuration and initializes a clean D1 database before setup continues.
+ </p>
+ <div className="space-y-2">
+ {loading && checks.length === 0 && (
+ <div className="flex items-center gap-3 rounded-2xl bg-neutral-50 px-4 py-3 text-sm text-neutral-600">
+ <LoaderCircle className="h-4 w-4 animate-spin" />
+ Checking installation
+ </div>
+ )}
+ {checks.map((check) => (
+ <div key={check.key} className="flex items-start gap-3 rounded-2xl bg-neutral-50 px-4 py-3">
+ {check.configured ? (
+ <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-green-600" />
+ ) : (
+ <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-red-600" />
+ )}
+ <div>
+ <p className="text-sm font-medium text-neutral-800">{check.key}</p>
+ {!check.configured && <p className="mt-1 text-xs leading-5 text-neutral-500">{check.message}</p>}
+ </div>
+ </div>
+ ))}
+ {preparationComplete && (
+ <div className="flex items-center gap-3 rounded-2xl bg-green-50 px-4 py-3 text-sm text-green-700">
+ <CheckCircle2 className="h-4 w-4" />
+ {databaseMigrated ? "Clean database migrated successfully" : "Database schema is ready"}
+ </div>
+ )}
+ </div>
+ {error && (
+ <p className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">
+ {error}
+ </p>
+ )}
+ {preparationComplete ? (
+ <Button
+ type="button"
+ className="h-11 w-full rounded-full px-6 active:scale-[0.98]"
+ onClick={() => setStep(hasPrimaryDomain ? 3 : 2)}
+ >
+ Continue
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="outline"
+ className="h-11 w-full rounded-full px-6 active:scale-[0.98]"
+ disabled={loading}
+ onClick={() => void runPreparation()}
+ >
+ {loading ? "Checking..." : "Check again"}
+ </Button>
+ )}
+ </div>
+ ) : showDomainStep ? (
<form onSubmit={onDomainSubmit} className="space-y-5">
<div className="space-y-2">
<Label htmlFor="domain">Primary domain</Label>
diff --git a/src/app/register/types.d.ts b/src/app/register/types.d.ts
index a7f00f7..262fad3 100644
--- a/src/app/register/types.d.ts
+++ b/src/app/register/types.d.ts
@@ -2,6 +2,19 @@ export type SetupStatus = {
hasAdminAccount: boolean;
hasPrimaryDomain: boolean;
primaryDomain?: { hostname: string } | null;
+ error?: string;
+};
+
+export type SetupRequirementCheck = {
+ key: string;
+ configured: boolean;
+ message: string;
+};
+
+export type SetupPreparationResult = {
+ checks?: SetupRequirementCheck[];
+ migrated?: boolean;
+ error?: string;
};
export type DomainSetupResult = {
diff --git a/src/app/register/utils.ts b/src/app/register/utils.ts
index 7021e0d..3422368 100644
--- a/src/app/register/utils.ts
+++ b/src/app/register/utils.ts
@@ -1,9 +1,24 @@
import { persistAuthSession } from "@/lib/auth/client";
-import type { DomainSetupResult, RegisterResult, SetupStatus } from "./types";
+import type {
+ DomainSetupResult,
+ RegisterResult,
+ SetupPreparationResult,
+ SetupStatus,
+} from "./types";
+
+export async function prepareSetup(): Promise<{ ok: boolean; data: SetupPreparationResult }> {
+ const res = await fetch("/api/setup/prepare", { method: "POST" });
+ return {
+ ok: res.ok,
+ data: (await res.json()) as SetupPreparationResult,
+ };
+}
export async function getSetupStatus(): Promise<SetupStatus> {
const res = await fetch("/api/setup/status");
- return (await res.json()) as SetupStatus;
+ const data = (await res.json()) as SetupStatus;
+ if (!res.ok) throw new Error(data.error ?? "Could not load setup status");
+ return data;
}
export async function submitPrimaryDomain(form: FormData): Promise<{ ok: boolean; data: DomainSetupResult }> {
diff --git a/src/app/setup/page.tsx b/src/app/setup/page.tsx
new file mode 100644
index 0000000..b1d1fea
--- /dev/null
+++ b/src/app/setup/page.tsx
@@ -0,0 +1,33 @@
+import { cookies } from "next/headers";
+import { redirect } from "next/navigation";
+import { AuthGuard } from "@/components/auth/auth-guard";
+import { SESSION_COOKIE, getUserFromSession } from "@/lib/auth/session";
+import { hasAdminAccount } from "@/lib/auth/setup";
+import { getEnv } from "@/lib/cloudflare";
+import { userHasAccessibleMailboxes } from "@/lib/user";
+import { OnboardingClient } from "@/app/onboarding/onboarding-client";
+import { RegisterClient } from "@/app/register/register-client";
+
+export const dynamic = "force-dynamic";
+
+export default async function SetupPage() {
+ const env = getEnv();
+ if (!(await hasAdminAccount(env))) {
+ return (
+ <AuthGuard mode="public">
+ <RegisterClient />
+ </AuthGuard>
+ );
+ }
+
+ const cookieStore = await cookies();
+ const user = await getUserFromSession(env, cookieStore.get(SESSION_COOKIE)?.value);
+ if (!user || user.disabled) redirect("/login");
+ if (await userHasAccessibleMailboxes(env, user)) redirect("/inbox");
+
+ return (
+ <AuthGuard>
+ <OnboardingClient />
+ </AuthGuard>
+ );
+}
diff --git a/src/app/utils.ts b/src/app/utils.ts
index 6987c50..9a3ef94 100644
--- a/src/app/utils.ts
+++ b/src/app/utils.ts
@@ -65,6 +65,6 @@ export function getHomeActions(isLoggedIn: boolean): HomeAction[] {
return [
{ href: "/login", label: "Log in", variant: "outline" },
- { href: "/register", label: "Create account", variant: "default" },
+ { href: "/setup", label: "Create account", variant: "default" },
];
}
diff --git a/src/components/auth/auth-guard.tsx b/src/components/auth/auth-guard.tsx
index 6eed7f5..03d9e33 100644
--- a/src/components/auth/auth-guard.tsx
+++ b/src/components/auth/auth-guard.tsx
@@ -31,16 +31,16 @@ export function AuthGuard({ children, mode = "protected", requireMailbox, requir
const data = (await response.json()) as { hasMailboxes?: boolean; user?: { role?: string } };
if (mode === "public") {
- router.replace(data.hasMailboxes === false ? "/onboarding" : "/inbox");
+ router.replace(data.hasMailboxes === false ? "/setup" : "/inbox");
return;
}
- if (requireMailbox && data.hasMailboxes === false && pathname !== "/onboarding") {
- router.replace("/onboarding");
+ if (requireMailbox && data.hasMailboxes === false && pathname !== "/setup") {
+ router.replace("/setup");
return;
}
- if (!requireMailbox && data.hasMailboxes && pathname === "/onboarding") {
+ if (!requireMailbox && data.hasMailboxes && pathname === "/setup") {
router.replace("/inbox");
return;
}
diff --git a/src/lib/auth/setup-utils.ts b/src/lib/auth/setup-utils.ts
new file mode 100644
index 0000000..8560cbf
--- /dev/null
+++ b/src/lib/auth/setup-utils.ts
@@ -0,0 +1,15 @@
+export function isMissingUsersTableError(error: unknown): boolean {
+ let current: unknown = error;
+ const visited = new Set<unknown>();
+
+ while (current && !visited.has(current)) {
+ visited.add(current);
+ if (current instanceof Error && /no such table:\s*users/i.test(current.message)) {
+ return true;
+ }
+ if (typeof current !== "object" || !("cause" in current)) break;
+ current = (current as { cause?: unknown }).cause;
+ }
+
+ return false;
+}
diff --git a/src/lib/auth/setup.ts b/src/lib/auth/setup.ts
index 851c90d..1a96ed4 100644
--- a/src/lib/auth/setup.ts
+++ b/src/lib/auth/setup.ts
@@ -1,14 +1,22 @@
import { eq } from "drizzle-orm";
import { getDb } from "@/db";
import { users } from "@/db/schema";
+import { isMissingUsersTableError } from "@/lib/auth/setup-utils";
export async function hasAdminAccount(env: CloudflareEnv): Promise<boolean> {
- const db = getDb(env);
- const [admin] = await db
- .select({ id: users.id })
- .from(users)
- .where(eq(users.role, "admin"))
- .limit(1);
+ if (!env.DB) return false;
- return !!admin;
+ try {
+ const db = getDb(env);
+ const [admin] = await db
+ .select({ id: users.id })
+ .from(users)
+ .where(eq(users.role, "admin"))
+ .limit(1);
+
+ return !!admin;
+ } catch (error) {
+ if (isMissingUsersTableError(error)) return false;
+ throw error;
+ }
}
diff --git a/src/lib/backups/types.d.ts b/src/lib/backups/types.d.ts
index 927f9ba..affba30 100644
--- a/src/lib/backups/types.d.ts
+++ b/src/lib/backups/types.d.ts
@@ -5,6 +5,13 @@ export type BackupWorkflowParams = {
force?: boolean;
};
+export type BackupWorkflowBinding = {
+ create(options?: {
+ id?: string;
+ params?: BackupWorkflowParams;
+ }): Promise<unknown>;
+};
+
export type D1ExportResult = {
at_bookmark?: string;
status?: string;
diff --git a/src/lib/backups/utils.ts b/src/lib/backups/utils.ts
index 3a85277..00f3e53 100644
--- a/src/lib/backups/utils.ts
+++ b/src/lib/backups/utils.ts
@@ -1,8 +1,29 @@
-import type { BackupScheduleType, D1ExportResponse } from "./types";
+import type {
+ BackupScheduleType,
+ BackupWorkflowBinding,
+ D1ExportResponse,
+} from "./types";
export const BACKUP_SETTINGS_ID = "default";
export const BACKUP_PREFIX = "backups/database";
+export class BackupWorkflowUnavailableError extends Error {
+ constructor() {
+ super(
+ "Database backups are unavailable because the DATABASE_BACKUP_WORKFLOW binding is missing. Deploy the app with `npm run deploy` so Wrangler applies the workflow configuration.",
+ );
+ this.name = "BackupWorkflowUnavailableError";
+ }
+}
+
+export function getBackupWorkflowBinding(env: CloudflareEnv): BackupWorkflowBinding {
+ const workflow = env.DATABASE_BACKUP_WORKFLOW as BackupWorkflowBinding | undefined;
+ if (!workflow || typeof workflow.create !== "function") {
+ throw new BackupWorkflowUnavailableError();
+ }
+ return workflow;
+}
+
export function isBackupDue(
scheduleType: BackupScheduleType,
scheduleValue: number | null,
diff --git a/src/lib/setup/configuration.ts b/src/lib/setup/configuration.ts
new file mode 100644
index 0000000..27f2f71
--- /dev/null
+++ b/src/lib/setup/configuration.ts
@@ -0,0 +1,24 @@
+import type { SetupRequirementCheck } from "./types";
+
+export function getSetupRequirementChecks(env: CloudflareEnv): SetupRequirementCheck[] {
+ const hasApiToken = !!env.CF_TOKEN?.trim();
+ const hasGlobalKey = !!env.CF_API_KEY?.trim() && !!env.CF_EMAIL?.trim();
+
+ return [
+ {
+ key: "Cloudflare API credentials",
+ configured: hasApiToken || hasGlobalKey,
+ message: "Set CF_TOKEN, or set both CF_API_KEY and CF_EMAIL.",
+ },
+ {
+ key: "Email Worker name",
+ configured: !!env.CF_EMAIL_WORKER_NAME?.trim(),
+ message: "Set CF_EMAIL_WORKER_NAME to the deployed Worker name.",
+ },
+ {
+ key: "D1 database",
+ configured: !!env.DB,
+ message: "Deploy the Worker with the DB binding from wrangler.jsonc.",
+ },
+ ];
+}
diff --git a/src/lib/setup/migration.ts b/src/lib/setup/migration.ts
new file mode 100644
index 0000000..e8fd888
--- /dev/null
+++ b/src/lib/setup/migration.ts
@@ -0,0 +1,82 @@
+const MIGRATION_NAMES = [
+ "0000_flowery_smasher.sql",
+ "0001_add_reset_email.sql",
+ "0002_add_message_read.sql",
+ "0003_add_contacts.sql",
+ "0004_add_accounts.sql",
+ "0005_add_folders.sql",
+ "0006_add_rule_conditions.sql",
+ "0007_add_shared_mailboxes.sql",
+ "0008_add_message_attachments.sql",
+ "0009_add_backups.sql",
+ "0010_hard_squirrel_girl.sql",
+ "0011_add_folder_colors.sql",
+];
+
+const INITIAL_SCHEMA_SQL = `
+CREATE TABLE IF NOT EXISTS users (id text PRIMARY KEY NOT NULL, email text NOT NULL UNIQUE, reset_email text, password_hash text NOT NULL, name text NOT NULL, avatar_key text, role text DEFAULT 'user' NOT NULL, disabled integer DEFAULT false NOT NULL, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);
+CREATE INDEX IF NOT EXISTS users_created_by_idx ON users(created_by_user_id);
+CREATE TABLE IF NOT EXISTS domains (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, hostname text NOT NULL, zone_id text NOT NULL, status text DEFAULT 'pending' NOT NULL, routing_status text, sending_subdomain_tag text, sending_enabled integer DEFAULT false NOT NULL, routing_enabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);
+CREATE UNIQUE INDEX IF NOT EXISTS domains_hostname_idx ON domains(hostname);
+CREATE INDEX IF NOT EXISTS domains_user_idx ON domains(user_id);
+CREATE TABLE IF NOT EXISTS mailboxes (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, domain_id text NOT NULL REFERENCES domains(id) ON DELETE cascade, local_part text NOT NULL, display_name text, avatar_key text, type text DEFAULT 'personal' NOT NULL, disabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);
+CREATE UNIQUE INDEX IF NOT EXISTS mailboxes_address_idx ON mailboxes(domain_id, local_part);
+CREATE TABLE IF NOT EXISTS mailbox_access (id text PRIMARY KEY NOT NULL, mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, permission text DEFAULT 'read_only' NOT NULL, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);
+CREATE UNIQUE INDEX IF NOT EXISTS mailbox_access_mailbox_user_idx ON mailbox_access(mailbox_id, user_id);
+CREATE INDEX IF NOT EXISTS mailbox_access_user_idx ON mailbox_access(user_id);
+CREATE INDEX IF NOT EXISTS mailbox_access_mailbox_idx ON mailbox_access(mailbox_id);
+CREATE TABLE IF NOT EXISTS contacts (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, email text NOT NULL, display_name text, source text DEFAULT 'inbound' NOT NULL, blocked integer DEFAULT false NOT NULL, last_seen_at integer, created_at integer NOT NULL);
+CREATE UNIQUE INDEX IF NOT EXISTS contacts_user_email_idx ON contacts(user_id, email);
+CREATE INDEX IF NOT EXISTS contacts_user_idx ON contacts(user_id);
+CREATE TABLE IF NOT EXISTS folders (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, mailbox_id text NOT NULL REFERENCES mailboxes(id) ON DELETE cascade, name text NOT NULL, color text DEFAULT '#2563eb' NOT NULL, created_at integer NOT NULL);
+CREATE UNIQUE INDEX IF NOT EXISTS folders_mailbox_name_idx ON folders(mailbox_id, name);
+CREATE INDEX IF NOT EXISTS folders_user_idx ON folders(user_id);
+CREATE INDEX IF NOT EXISTS folders_mailbox_idx ON folders(mailbox_id);
+CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, name text NOT NULL, prefix text NOT NULL, key_hash text NOT NULL, scopes text NOT NULL, created_at integer NOT NULL, last_used_at integer);
+CREATE TABLE IF NOT EXISTS messages (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, direction text NOT NULL, provider_message_id text, folder_id text REFERENCES folders(id) ON DELETE set null, from_addr text NOT NULL, to_addr text NOT NULL, subject text, snippet text, status text DEFAULT 'received' NOT NULL, read integer DEFAULT false NOT NULL, thread_id text, created_at integer NOT NULL);
+CREATE INDEX IF NOT EXISTS messages_user_created_idx ON messages(user_id, created_at);
+CREATE INDEX IF NOT EXISTS messages_mailbox_idx ON messages(mailbox_id);
+CREATE INDEX IF NOT EXISTS messages_folder_idx ON messages(folder_id);
+CREATE TABLE IF NOT EXISTS message_bodies (id text PRIMARY KEY NOT NULL, message_id text NOT NULL UNIQUE REFERENCES messages(id) ON DELETE cascade, text_body text, html_body text, raw_r2_key text);
+CREATE TABLE IF NOT EXISTS message_attachments (id text PRIMARY KEY NOT NULL, message_id text NOT NULL REFERENCES messages(id) ON DELETE cascade, filename text NOT NULL, content_type text NOT NULL, size integer NOT NULL, disposition text DEFAULT 'attachment' NOT NULL, content_id text, r2_key text NOT NULL UNIQUE, created_at integer NOT NULL);
+CREATE INDEX IF NOT EXISTS message_attachments_message_idx ON message_attachments(message_id);
+CREATE TABLE IF NOT EXISTS outbound_jobs (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, message_id text REFERENCES messages(id) ON DELETE set null, status text DEFAULT 'queued' NOT NULL, payload text NOT NULL, error text, created_at integer NOT NULL, updated_at integer NOT NULL);
+CREATE TABLE IF NOT EXISTS routing_rules (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, domain_id text NOT NULL REFERENCES domains(id) ON DELETE cascade, pattern text NOT NULL, match_field text DEFAULT 'email' NOT NULL, match_operator text DEFAULT 'contains' NOT NULL, match_value text DEFAULT '' NOT NULL, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, folder_id text REFERENCES folders(id) ON DELETE set null, action text DEFAULT 'store' NOT NULL, forward_to text, priority integer DEFAULT 0 NOT NULL, created_at integer NOT NULL);
+CREATE TABLE IF NOT EXISTS webhooks (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, url text NOT NULL, secret text NOT NULL, events text NOT NULL, enabled integer DEFAULT true NOT NULL, created_at integer NOT NULL);
+CREATE TABLE IF NOT EXISTS webhook_deliveries (id text PRIMARY KEY NOT NULL, webhook_id text NOT NULL REFERENCES webhooks(id) ON DELETE cascade, event_type text NOT NULL, payload text NOT NULL, status text DEFAULT 'pending' NOT NULL, attempts integer DEFAULT 0 NOT NULL, created_at integer NOT NULL);
+CREATE TABLE IF NOT EXISTS sessions (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, token_hash text NOT NULL UNIQUE, expires_at integer NOT NULL, created_at integer NOT NULL);
+CREATE TABLE IF NOT EXISTS audit_logs (id text PRIMARY KEY NOT NULL, actor_user_id text REFERENCES users(id) ON DELETE set null, target_user_id text REFERENCES users(id) ON DELETE set null, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, message_id text REFERENCES messages(id) ON DELETE set null, action text NOT NULL, metadata text, created_at integer NOT NULL);
+CREATE INDEX IF NOT EXISTS audit_logs_actor_idx ON audit_logs(actor_user_id);
+CREATE INDEX IF NOT EXISTS audit_logs_mailbox_idx ON audit_logs(mailbox_id);
+CREATE INDEX IF NOT EXISTS audit_logs_created_idx ON audit_logs(created_at);
+CREATE TABLE IF NOT EXISTS backup_settings (id text PRIMARY KEY NOT NULL, enabled integer DEFAULT false NOT NULL, schedule_type text DEFAULT 'daily' NOT NULL, schedule_value integer, retention_enabled integer DEFAULT false NOT NULL, retention_days integer DEFAULT 30 NOT NULL, updated_at integer NOT NULL);
+INSERT OR IGNORE INTO backup_settings (id, enabled, schedule_type, retention_enabled, retention_days, updated_at) VALUES ('default', false, 'daily', false, 30, unixepoch());
+CREATE TABLE IF NOT EXISTS backups (id text PRIMARY KEY NOT NULL, status text DEFAULT 'queued' NOT NULL, trigger text NOT NULL, r2_key text, filename text, size integer, error text, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL, started_at integer, completed_at integer);
+CREATE INDEX IF NOT EXISTS backups_created_idx ON backups(created_at);
+CREATE INDEX IF NOT EXISTS backups_status_idx ON backups(status);
+CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);
+`;
+
+export async function migrateCleanDatabase(db: D1Database): Promise<boolean> {
+ const existing = await db
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%' AND name NOT IN ('d1_migrations', 'd1_kv')")
+ .all<{ name: string }>();
+ if (existing.results.length > 0) {
+ const tableNames = new Set(existing.results.map((table) => table.name));
+ if (tableNames.has("users") && tableNames.has("domains")) return false;
+ throw new Error(
+ "The D1 database is not empty, but the Mailflare schema is incomplete. Apply the committed D1 migrations before continuing setup.",
+ );
+ }
+
+ const schemaStatements = INITIAL_SCHEMA_SQL
+ .split(";")
+ .map((statement) => statement.trim())
+ .filter(Boolean)
+ .map((statement) => db.prepare(statement));
+ const migrationStatements = MIGRATION_NAMES.map((name) =>
+ db.prepare("INSERT OR IGNORE INTO d1_migrations (name) VALUES (?)").bind(name),
+ );
+ await db.batch([...schemaStatements, ...migrationStatements]);
+ return true;
+}
diff --git a/src/lib/setup/types.d.ts b/src/lib/setup/types.d.ts
new file mode 100644
index 0000000..6ceb2d3
--- /dev/null
+++ b/src/lib/setup/types.d.ts
@@ -0,0 +1,10 @@
+export type SetupRequirementCheck = {
+ key: string;
+ configured: boolean;
+ message: string;
+};
+
+export type SetupPreparationResult = {
+ checks: SetupRequirementCheck[];
+ migrated: boolean;
+};