Skip to content

Email for professionals and teams

Various update

Hieu Nguyen (Jack)1ddb40f994b8
diff --git a/.dev.vars.example b/.dev.vars.example
index f7aa01c..eb5a4b2 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -6,5 +6,5 @@ CF_ACCOUNT_ID=your_account_id
CF_EMAIL_WORKER_NAME=mailflare
# Legacy Global API Key alternative. Use this only instead of CF_TOKEN.
-# CLOUDFLARE_API_KEY=your_global_api_key
+# CF_API_KEY=your_global_api_key
diff --git a/README.md b/README.md
index b2f6daa..83c0c7c 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,7 @@ Domains are **not** dashboard-only. This app calls Cloudflare when you add/remov
| Remove subdomain sending | `DELETE /zones/{zone_id}/email/sending/subdomains/{tag}` |
| Subdomain sending DNS records | `GET .../subdomains/{tag}/dns` |
-**Requirements:** Prefer `CF_TOKEN` with Zone Read + Email Routing Edit + Email Sending Edit + Email Routing Rules Write (or broader). If you use a legacy Global API Key instead, set `CLOUDFLARE_API_KEY` and `CLOUDFLARE_EMAIL`. The hostname must be the account's Cloudflare zone apex or a subdomain under that zone. Root-domain sending uses the Cloudflare Email Service binding, while subdomain sending can also provision the sending-subdomain DNS records. Mailbox creation creates a Cloudflare Email Routing rule that sends that address to `CF_EMAIL_WORKER_NAME` (`mailflare` by default).
+**Requirements:** Prefer `CF_TOKEN` with Zone Read + Email Routing Edit + Email Sending Edit + Email Routing Rules Write (or broader). If you use a legacy Global API Key instead, set `CF_API_KEY` and `CF_EMAIL`. The hostname must be the account's Cloudflare zone apex or a subdomain under that zone. Root-domain sending uses the Cloudflare Email Service binding, while subdomain sending can also provision the sending-subdomain DNS records. Mailbox creation creates a Cloudflare Email Routing rule that sends that address to `CF_EMAIL_WORKER_NAME` (`mailflare` by default).
App routes:
@@ -50,7 +50,7 @@ App routes:
```bash
cp .dev.vars.example .dev.vars
# Add CF_TOKEN and optionally CF_ACCOUNT_ID.
-# For a legacy Global API Key, use CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL instead.
+# For a legacy Global API Key, use CF_API_KEY + CF_EMAIL instead.
npm install
npm run db:migrate:local
@@ -96,7 +96,7 @@ curl "https://api.cloudflare.com/client/v4/user/tokens/verify" \
-H "Authorization: Bearer <CF_TOKEN>"
```
-The response should include `"success": true` and `"status": "active"`. In `.dev.vars` or deploy settings, set `CF_TOKEN` to the token secret value only. Do not include the word `Bearer`, do not use the token ID, and do not put a Global API Key in `CF_TOKEN`. For a Global API Key, set both `CLOUDFLARE_EMAIL` and `CLOUDFLARE_API_KEY` instead.
+The response should include `"success": true` and `"status": "active"`. In `.dev.vars` or deploy settings, set `CF_TOKEN` to the token secret value only. Do not include the word `Bearer`, do not use the token ID, and do not put a Global API Key in `CF_TOKEN`. For a Global API Key, set both `CF_EMAIL` and `CF_API_KEY` instead.
Also check whether the token has an expiration, a `not_before` time, or client IP restrictions. If you changed deploy variables in Cloudflare, redeploy so the Worker receives the new values.
diff --git a/drizzle/migrations/0003_add_contacts.sql b/drizzle/migrations/0003_add_contacts.sql
new file mode 100644
index 0000000..4778cb6
--- /dev/null
+++ b/drizzle/migrations/0003_add_contacts.sql
@@ -0,0 +1,14 @@
+CREATE TABLE `contacts` (
+ `id` text PRIMARY KEY NOT NULL,
+ `user_id` text NOT NULL,
+ `email` text NOT NULL,
+ `display_name` text,
+ `source` text DEFAULT 'inbound' NOT NULL,
+ `last_seen_at` integer,
+ `created_at` integer NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `contacts_user_email_idx` ON `contacts` (`user_id`,`email`);
+--> statement-breakpoint
+CREATE INDEX `contacts_user_idx` ON `contacts` (`user_id`);
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index d820b06..101ec65 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -22,6 +22,13 @@
"when": 1779256253877,
"tag": "0002_add_message_read",
"breakpoints": true
+ },
+ {
+ "idx": 3,
+ "version": "6",
+ "when": 1779256253878,
+ "tag": "0003_add_contacts",
+ "breakpoints": true
}
]
}
diff --git a/env.d.ts b/env.d.ts
index 0f1dfe7..373f7b3 100644
--- a/env.d.ts
+++ b/env.d.ts
@@ -8,8 +8,8 @@ interface CloudflareEnv {
IMAGES: ImagesBinding;
WORKER_SELF_REFERENCE: Fetcher;
CF_TOKEN?: string;
- CLOUDFLARE_API_KEY?: string;
- CLOUDFLARE_EMAIL?: string;
+ CF_API_KEY?: string;
+ CF_EMAIL?: string;
CF_ACCOUNT_ID?: string;
CF_EMAIL_WORKER_NAME?: string;
}
diff --git a/package.json b/package.json
index e7d0f8c..d49cdfc 100644
--- a/package.json
+++ b/package.json
@@ -29,10 +29,10 @@
"CF_EMAIL_WORKER_NAME": {
"description": "Worker name used when creating Cloudflare Email Routing rules. Keep this aligned with the `name` in `wrangler.jsonc`; the template default is `mailflare`."
},
- "CLOUDFLARE_EMAIL": {
- "description": "Legacy Global API Key auth only. Use this with `CLOUDFLARE_API_KEY` instead of `CF_TOKEN`."
+ "CF_EMAIL": {
+ "description": "Legacy Global API Key auth only. Use this with `CF_API_KEY` instead of `CF_TOKEN`."
},
- "CLOUDFLARE_API_KEY": {
+ "CF_API_KEY": {
"description": "Legacy Global API Key auth only. Prefer `CF_TOKEN` for new deployments."
}
}
diff --git a/src/app/(admin)/api-keys/page.tsx b/src/app/(admin)/api-keys/page.tsx
index 77cdb2f..c506d5d 100644
--- a/src/app/(admin)/api-keys/page.tsx
+++ b/src/app/(admin)/api-keys/page.tsx
@@ -16,6 +16,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { authFetch } from "@/lib/auth/client";
import type { ApiKey } from "./types";
import { parseApiKeyScopes } from "./utils";
@@ -28,14 +29,14 @@ export default function ApiKeysPage() {
const { data, isLoading } = useQuery({
queryKey: ["api-keys"],
queryFn: async () => {
- const res = await fetch("/api/api-keys");
+ const res = await authFetch("/api/api-keys");
return (await res.json()) as { apiKeys: ApiKey[] };
},
});
const create = useMutation({
mutationFn: async () => {
- const res = await fetch("/api/api-keys", {
+ const res = await authFetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, scopes: ["send", "read"] }),
diff --git a/src/app/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
index 541ad2d..806bae0 100644
--- a/src/app/(admin)/domains/page.tsx
+++ b/src/app/(admin)/domains/page.tsx
@@ -24,6 +24,7 @@ import {
Plus,
Trash2,
} from "lucide-react";
+import { authFetch } from "@/lib/auth/client";
import type { DnsRecord, DnsStatusSummary, Domain } from "./types";
export default function DomainsPage() {
@@ -38,7 +39,7 @@ export default function DomainsPage() {
const { data, isLoading } = useQuery({
queryKey: ["domains"],
queryFn: async () => {
- const res = await fetch("/api/domains?includeDns=true");
+ const res = await authFetch("/api/domains?includeDns=true");
return (await res.json()) as {
domains: Domain[];
dns: Record<string, DnsStatusSummary>;
@@ -48,7 +49,7 @@ export default function DomainsPage() {
const create = useMutation({
mutationFn: async () => {
- const res = await fetch("/api/domains", {
+ const res = await authFetch("/api/domains", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -70,14 +71,14 @@ export default function DomainsPage() {
const remove = useMutation({
mutationFn: async (id: string) => {
- const res = await fetch(`/api/domains/${id}`, { method: "DELETE" });
+ const res = await authFetch(`/api/domains/${id}`, { method: "DELETE" });
if (!res.ok) throw new Error("Failed to remove");
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["domains"] }),
});
const loadDns = async (id: string) => {
- const res = await fetch(`/api/domains/${id}/dns`);
+ const res = await authFetch(`/api/domains/${id}/dns`);
const json = (await res.json()) as { domain: Domain; dns: unknown };
if (res.ok) setDnsView(json);
};
diff --git a/src/app/(admin)/layout.tsx b/src/app/(admin)/layout.tsx
index a53e836..e0326ee 100644
--- a/src/app/(admin)/layout.tsx
+++ b/src/app/(admin)/layout.tsx
@@ -1,54 +1,49 @@
+"use client";
+
import Link from "next/link";
-import { redirect } from "next/navigation";
import { HelpCircle, Search } from "lucide-react";
-
-export const dynamic = "force-dynamic";
+import { AuthGuard } from "@/components/auth/auth-guard";
import { ComposeProvider } from "@/components/compose/compose-context";
import { FloatingComposer } from "@/components/compose/floating-composer";
-import { DashboardShellNav } from "@/components/dashboard-shell";
import { MailboxProvider } from "@/components/mailbox-provider";
import { MailboxSelector } from "@/components/mailbox-selector";
-import { getEnv } from "@/lib/cloudflare";
-import { getCurrentUser } from "@/lib/auth/cookies";
import { AdminNav } from "@/components/admin-nav";
-export default async function DashboardLayout({
+export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
- const env = getEnv();
- const user = await getCurrentUser(env);
- if (!user) redirect("/login");
-
return (
- <MailboxProvider>
- <ComposeProvider>
- <div className="grid min-h-screen grid-cols-[256px_1fr] bg-[#f6f8fc]">
- <aside className="flex flex-col gap-4 px-3 py-4">
- <AdminNav />
- </aside>
- <div className="flex min-h-screen flex-col">
- <header className="flex h-16 items-center gap-4 pr-4 text-sm">
- <div className="flex h-12 flex-1 max-w-3xl items-center gap-3 rounded-full bg-[#eaf1fb] px-4 text-neutral-600">
- <Search className="h-5 w-5" />
- <span className="text-[15px]">Search mail</span>
- </div>
- <Link
- href="/settings"
- className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"
- >
- <HelpCircle className="h-5 w-5" />
- </Link>
- <MailboxSelector />
- </header>
- <main className="flex-1 overflow-hidden rounded-t-3xl bg-white px-12 py-8 w-fit min-w-172">
- {children}
- </main>
+ <AuthGuard requireMailbox>
+ <MailboxProvider>
+ <ComposeProvider>
+ <div className="grid min-h-screen grid-cols-[256px_1fr] bg-[#f6f8fc]">
+ <aside className="flex flex-col gap-4 px-3 py-4">
+ <AdminNav />
+ </aside>
+ <div className="flex min-h-screen flex-col">
+ <header className="flex h-16 items-center gap-4 pr-4 text-sm">
+ <div className="flex h-12 flex-1 max-w-3xl items-center gap-3 rounded-full bg-[#eaf1fb] px-4 text-neutral-600">
+ <Search className="h-5 w-5" />
+ <span className="text-[15px]">Search mail</span>
+ </div>
+ <Link
+ href="/settings"
+ className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"
+ >
+ <HelpCircle className="h-5 w-5" />
+ </Link>
+ <MailboxSelector />
+ </header>
+ <main className="flex-1 overflow-hidden rounded-t-3xl bg-white px-12 py-8 w-fit min-w-172">
+ {children}
+ </main>
+ </div>
+ <FloatingComposer />
</div>
- <FloatingComposer />
- </div>
- </ComposeProvider>
- </MailboxProvider>
+ </ComposeProvider>
+ </MailboxProvider>
+ </AuthGuard>
);
}
diff --git a/src/app/(admin)/mailboxes/[id]/utils.ts b/src/app/(admin)/mailboxes/[id]/utils.ts
index 715efb8..a92689d 100644
--- a/src/app/(admin)/mailboxes/[id]/utils.ts
+++ b/src/app/(admin)/mailboxes/[id]/utils.ts
@@ -1,3 +1,4 @@
+import { authFetch } from "@/lib/auth/client";
import type { MailboxDetail, MailboxDetailResponse } from "./types";
export function getMailboxAddress(mailbox: Pick<MailboxDetail, "localPart" | "hostname">): string {
@@ -5,7 +6,7 @@ export function getMailboxAddress(mailbox: Pick<MailboxDetail, "localPart" | "ho
}
export async function fetchMailbox(id: string): Promise<MailboxDetail> {
- const res = await fetch(`/api/mailboxes/${id}`);
+ const res = await authFetch(`/api/mailboxes/${id}`);
const json = (await res.json()) as MailboxDetailResponse;
if (!res.ok || !json.mailbox) {
@@ -16,7 +17,7 @@ export async function fetchMailbox(id: string): Promise<MailboxDetail> {
}
export async function updateMailboxName(id: string, displayName: string): Promise<MailboxDetail> {
- const res = await fetch(`/api/mailboxes/${id}`, {
+ const res = await authFetch(`/api/mailboxes/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ displayName }),
diff --git a/src/app/(admin)/mailboxes/page.tsx b/src/app/(admin)/mailboxes/page.tsx
index 08b8d4a..b02f71a 100644
--- a/src/app/(admin)/mailboxes/page.tsx
+++ b/src/app/(admin)/mailboxes/page.tsx
@@ -15,6 +15,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { authFetch } from "@/lib/auth/client";
import type { Domain, Mailbox } from "./types";
import { getMailboxAddress, getMailboxName } from "./utils";
@@ -27,7 +28,7 @@ export default function MailboxesPage() {
const domains = useQuery({
queryKey: ["domains"],
queryFn: async () => {
- const res = await fetch("/api/domains");
+ const res = await authFetch("/api/domains");
return (await res.json()) as { domains: Domain[] };
},
});
@@ -35,14 +36,14 @@ export default function MailboxesPage() {
const mailboxes = useQuery({
queryKey: ["mailboxes"],
queryFn: async () => {
- const res = await fetch("/api/mailboxes");
+ const res = await authFetch("/api/mailboxes");
return (await res.json()) as { mailboxes: Mailbox[] };
},
});
const create = useMutation({
mutationFn: async () => {
- const res = await fetch("/api/mailboxes", {
+ const res = await authFetch("/api/mailboxes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ domainId, localPart, displayName: localPart }),
diff --git a/src/app/(admin)/routing/page.tsx b/src/app/(admin)/routing/page.tsx
index 10dd2d4..048cfa1 100644
--- a/src/app/(admin)/routing/page.tsx
+++ b/src/app/(admin)/routing/page.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { authFetch } from "@/lib/auth/client";
export default function RoutingPage() {
const qc = useQueryClient();
@@ -15,7 +16,7 @@ export default function RoutingPage() {
const domains = useQuery({
queryKey: ["domains"],
queryFn: async () => {
- const res = await fetch("/api/domains");
+ const res = await authFetch("/api/domains");
return (await res.json()) as { domains: { id: string; hostname: string }[] };
},
});
@@ -23,14 +24,14 @@ export default function RoutingPage() {
const rules = useQuery({
queryKey: ["routing-rules"],
queryFn: async () => {
- const res = await fetch("/api/routing-rules");
+ const res = await authFetch("/api/routing-rules");
return (await res.json()) as { rules: { id: string; pattern: string; action: string }[] };
},
});
const create = useMutation({
mutationFn: async () => {
- const res = await fetch("/api/routing-rules", {
+ const res = await authFetch("/api/routing-rules", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ domainId, pattern, action: "store", priority: 10 }),
diff --git a/src/app/(admin)/settings/page.tsx b/src/app/(admin)/settings/page.tsx
deleted file mode 100644
index 63ecacc..0000000
--- a/src/app/(admin)/settings/page.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { ProfileForm } from "@/components/settings/profile-form";
-import { getEnv } from "@/lib/cloudflare";
-import { getCurrentUser } from "@/lib/auth/cookies";
-
-export default async function SettingsPage() {
- const env = getEnv();
- const user = await getCurrentUser(env);
- if (!user) return null;
-
- return (
- <div className="space-y-6 max-w-2xl">
- <h1 className="text-2xl font-semibold">Settings</h1>
- <Card>
- <CardHeader>
- <CardTitle>Account</CardTitle>
- <CardDescription>{user.email}</CardDescription>
- </CardHeader>
- <CardContent>
- <ProfileForm initialName={user.name} email={user.email} />
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <CardTitle>Cloudflare API</CardTitle>
- </CardHeader>
- <CardContent className="text-sm text-neutral-500 space-y-2">
- <p>
- Domain onboarding uses <code>CF_TOKEN</code> with Zone + Email Routing + Email
- Sending permissions.
- </p>
- <p>Domains must already be zones in your Cloudflare account.</p>
- </CardContent>
- </Card>
- </div>
- );
-}
diff --git a/src/app/(admin)/webhooks/page.tsx b/src/app/(admin)/webhooks/page.tsx
index 69271d4..6b234c9 100644
--- a/src/app/(admin)/webhooks/page.tsx
+++ b/src/app/(admin)/webhooks/page.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { authFetch } from "@/lib/auth/client";
export default function WebhooksPage() {
const qc = useQueryClient();
@@ -15,14 +16,14 @@ export default function WebhooksPage() {
const { data } = useQuery({
queryKey: ["webhooks"],
queryFn: async () => {
- const res = await fetch("/api/webhooks");
+ const res = await authFetch("/api/webhooks");
return (await res.json()) as { webhooks: { id: string; url: string }[] };
},
});
const create = useMutation({
mutationFn: async () => {
- const res = await fetch("/api/webhooks", {
+ const res = await authFetch("/api/webhooks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsx
index 772f4c9..5cc3225 100644
--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx
+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx
@@ -1,77 +1,105 @@
-import { notFound, redirect } from "next/navigation";
+"use client";
+
import Link from "next/link";
+import { useParams } from "next/navigation";
+import { useEffect, useState } from "react";
import { ArrowLeft } from "lucide-react";
import dayjs from "dayjs";
-import { getEnv } from "@/lib/cloudflare";
-import { getCurrentUser } from "@/lib/auth/cookies";
-import { getMessageWithBody } from "@/lib/email/inbound";
import { MarkAsRead } from "@/components/mark-read";
import { MessageActions } from "@/components/message-actions/message-actions";
import { getMessageBackHref } from "@/components/message-actions/utils";
+import { getEmailAddress, getEmailDisplayName } from "@/lib/email/address";
+import type { MessageDetailResponse } from "./types";
+import { fetchMessageDetail } from "./utils";
+
+export default function MessageDetailPage() {
+ const params = useParams<{ messageId: string }>();
+ const messageId = params.messageId;
+ const [data, setData] = useState<MessageDetailResponse | null>(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ async function loadMessage() {
+ setLoading(true);
+ const nextData = await fetchMessageDetail(messageId);
+ if (!cancelled) {
+ setData(nextData);
+ setLoading(false);
+ }
+ }
+
+ void loadMessage();
+ return () => {
+ cancelled = true;
+ };
+ }, [messageId]);
-export default async function MessageDetailPage({
- params,
-}: {
- params: Promise<{ messageId: string }>;
-}) {
- const { messageId } = await params;
- const env = getEnv();
- const user = await getCurrentUser(env);
- if (!user) redirect("/login");
+ if (loading) {
+ return <p className="px-6 py-4 text-sm text-neutral-500">Loading...</p>;
+ }
- const data = await getMessageWithBody(env, user.id, messageId);
- if (!data) notFound();
+ if (!data?.message) {
+ return <p className="px-6 py-4 text-sm text-neutral-500">{data?.error ?? "Message not found"}</p>;
+ }
- const { message, body } = data;
+ const { message, body } = data;
+ const fromName = message.fromContactName ?? getEmailDisplayName(message.fromAddr);
+ const fromAddress = getEmailAddress(message.fromAddr);
+ const toName = message.toContactName ?? getEmailDisplayName(message.toAddr);
+ const toAddress = getEmailAddress(message.toAddr);
- return (
- <div className="h-full overflow-auto">
- {message.direction === "inbound" && !message.read && (
- <MarkAsRead messageId={message.id} />
- )}
- <div className="flex py-2 items-center justify-between px-2">
- <div className="flex items-center flex-row gap-6">
- <Link
- href={getMessageBackHref(message.direction, message.status)}
- className="rounded-full p-2 text-neutral-600 hover:bg-neutral-100"
- >
- <ArrowLeft className="h-5 w-5" />
- </Link>
- {/* <Badge>{message.direction}</Badge> */}
- {/* <Badge variant="outline">{message.status}</Badge> */}
- </div>
- <MessageActions
- messageId={message.id}
- direction={message.direction}
- status={message.status}
- />
- </div>
- <article className="px-6">
- <h1 className="text-2xl text-neutral-900 mb-4">
- {message.subject ?? "(no subject)"}
- </h1>
+ return (
+ <div className="h-full overflow-auto">
+ {message.direction === "inbound" && !message.read && (
+ <MarkAsRead messageId={message.id} />
+ )}
+ <div className="flex py-2 items-center justify-between px-2">
+ <div className="flex items-center flex-row gap-6">
+ <Link
+ href={getMessageBackHref(message.direction, message.status)}
+ className="rounded-full p-2 text-neutral-600 hover:bg-neutral-100"
+ >
+ <ArrowLeft className="h-5 w-5" />
+ </Link>
+ </div>
+ <MessageActions
+ messageId={message.id}
+ direction={message.direction}
+ status={message.status}
+ read={message.read}
+ />
+ </div>
+ <article className="px-6">
+ <h1 className="text-2xl text-neutral-900 mb-4">
+ {message.subject ?? "(no subject)"}
+ </h1>
- <div className="mb-6 flex items-start justify-between border-b border-neutral-100 pb-5">
- <div>
- <p className="text-sm font-semibold text-neutral-900">
- {message.fromAddr}
- </p>
- <p className="text-xs text-neutral-500">to {message.toAddr}</p>
- </div>
- <p className="text-xs text-neutral-400">
- {dayjs(message.createdAt).format("MMM DD, YYYY, hh:mmA")}
- </p>
- </div>
- <div className="prose max-w-none text-neutral-900">
- {body?.htmlBody ? (
- <div dangerouslySetInnerHTML={{ __html: body.htmlBody }} />
- ) : (
- <pre className="whitespace-pre-wrap text-sm">
- {body?.textBody ?? message.snippet}
- </pre>
- )}
- </div>
- </article>
- </div>
- );
+ <div className="mb-6 flex items-start justify-between border-b border-neutral-100 pb-5">
+ <div>
+ <p className="text-sm font-semibold text-neutral-900">{fromName}</p>
+ <p className="text-xs text-neutral-500">
+ {fromAddress}
+ <span className="mx-1">to</span>
+ {toName}
+ {toAddress !== toName && <span className="ml-1">({toAddress})</span>}
+ </p>
+ </div>
+ <p className="text-xs text-neutral-400">
+ {dayjs(message.createdAt).format("MMM DD, YYYY, hh:mmA")}
+ </p>
+ </div>
+ <div className="prose max-w-none text-neutral-900">
+ {body?.htmlBody ? (
+ <div dangerouslySetInnerHTML={{ __html: body.htmlBody }} />
+ ) : (
+ <pre className="whitespace-pre-wrap text-sm">
+ {body?.textBody ?? message.snippet}
+ </pre>
+ )}
+ </div>
+ </article>
+ </div>
+ );
}
diff --git a/src/app/(dashboard)/inbox/[messageId]/types.d.ts b/src/app/(dashboard)/inbox/[messageId]/types.d.ts
new file mode 100644
index 0000000..268288c
--- /dev/null
+++ b/src/app/(dashboard)/inbox/[messageId]/types.d.ts
@@ -0,0 +1,10 @@
+import type { Message } from "@/hooks/types";
+
+export type MessageDetailResponse = {
+ message?: Message;
+ body?: {
+ htmlBody: string | null;
+ textBody: string | null;
+ } | null;
+ error?: string;
+};
diff --git a/src/app/(dashboard)/inbox/[messageId]/utils.ts b/src/app/(dashboard)/inbox/[messageId]/utils.ts
new file mode 100644
index 0000000..81a24a6
--- /dev/null
+++ b/src/app/(dashboard)/inbox/[messageId]/utils.ts
@@ -0,0 +1,7 @@
+import { authFetch } from "@/lib/auth/client";
+import type { MessageDetailResponse } from "./types";
+
+export async function fetchMessageDetail(messageId: string): Promise<MessageDetailResponse> {
+ const response = await authFetch(`/api/messages/${messageId}`);
+ return (await response.json()) as MessageDetailResponse;
+}
diff --git a/src/app/(dashboard)/layout.tsx b/src/app/(dashboard)/layout.tsx
index 68c3597..d47ef25 100644
--- a/src/app/(dashboard)/layout.tsx
+++ b/src/app/(dashboard)/layout.tsx
@@ -1,48 +1,44 @@
+"use client";
+
import Link from "next/link";
-import { redirect } from "next/navigation";
import { HelpCircle } from "lucide-react";
-
-export const dynamic = "force-dynamic";
+import { AuthGuard } from "@/components/auth/auth-guard";
import { ComposeProvider } from "@/components/compose/compose-context";
import { FloatingComposer } from "@/components/compose/floating-composer";
import { MailSearchInput } from "@/components/mail-search/mail-search-input";
import { MailSearchProvider } from "@/components/mail-search/mail-search-context";
import { MailboxProvider } from "@/components/mailbox-provider";
import { MailboxSelector } from "@/components/mailbox-selector";
-import { getEnv } from "@/lib/cloudflare";
-import { getCurrentUser } from "@/lib/auth/cookies";
import { DashboardNav } from "@/components/dashboard-nav";
-export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
- const env = getEnv();
- const user = await getCurrentUser(env);
- if (!user) redirect("/login");
-
+export default function DashboardLayout({ children }: { children: React.ReactNode }) {
return (
- <MailboxProvider>
- <ComposeProvider>
- <MailSearchProvider>
- <div className="grid min-h-screen grid-cols-[256px_1fr] bg-[#f6f8fc]">
- <aside className="flex flex-col gap-4 px-3 py-4">
- <DashboardNav />
- </aside>
- <div className="flex min-h-screen flex-col">
- <header className="flex h-16 items-center gap-4 pr-4 text-sm">
- <MailSearchInput />
- <Link
- href="/settings"
- className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"
- >
- <HelpCircle className="h-5 w-5" />
- </Link>
- <MailboxSelector />
- </header>
- <main className="flex-1 overflow-hidden rounded-tl-3xl bg-white">{children}</main>
+ <AuthGuard requireMailbox>
+ <MailboxProvider>
+ <ComposeProvider>
+ <MailSearchProvider>
+ <div className="grid min-h-screen grid-cols-[256px_1fr] bg-[#f6f8fc]">
+ <aside className="flex flex-col gap-4 px-3 py-4">
+ <DashboardNav />
+ </aside>
+ <div className="flex min-h-screen flex-col">
+ <header className="flex h-16 items-center gap-4 pr-4 text-sm">
+ <MailSearchInput />
+ <Link
+ href="/settings"
+ className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"
+ >
+ <HelpCircle className="h-5 w-5" />
+ </Link>
+ <MailboxSelector />
+ </header>
+ <main className="flex-1 overflow-hidden rounded-tl-3xl bg-white">{children}</main>
+ </div>
+ <FloatingComposer />
</div>
- <FloatingComposer />
- </div>
- </MailSearchProvider>
- </ComposeProvider>
- </MailboxProvider>
+ </MailSearchProvider>
+ </ComposeProvider>
+ </MailboxProvider>
+ </AuthGuard>
);
}
diff --git a/src/app/(dashboard)/settings/page.tsx b/src/app/(dashboard)/settings/page.tsx
new file mode 100644
index 0000000..b29a159
--- /dev/null
+++ b/src/app/(dashboard)/settings/page.tsx
@@ -0,0 +1,5 @@
+import { CurrentMailboxForm } from "@/components/settings/current-mailbox-form";
+
+export default function SettingsPage() {
+ return <CurrentMailboxForm />;
+}
diff --git a/src/app/api/api-keys/route.ts b/src/app/api/api-keys/route.ts
index 2ae8d75..2171f44 100644
--- a/src/app/api/api-keys/route.ts
+++ b/src/app/api/api-keys/route.ts
@@ -13,9 +13,9 @@ const createKeySchema = z.object({
scopes: z.array(z.enum(["send", "read"])).min(1),
});
-export async function GET() {
+export async function GET(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const db = getDb(env);
const rows = await db
.select({
@@ -33,7 +33,7 @@ export async function GET() {
export async function POST(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const parsed = createKeySchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index 3e7d9f7..8872cc8 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -26,6 +26,7 @@ export async function POST(request: Request) {
const token = await createSession(env, user.id);
const response = NextResponse.json({
ok: true,
+ token,
redirect: hasMailboxes ? "/inbox" : "/onboarding",
});
response.cookies.set(SESSION_COOKIE, token, {
diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts
index 9030242..6b4d4de 100644
--- a/src/app/api/auth/logout/route.ts
+++ b/src/app/api/auth/logout/route.ts
@@ -3,10 +3,12 @@ import { cookies } from "next/headers";
import { getEnv } from "@/lib/cloudflare";
import { deleteSession, SESSION_COOKIE } from "@/lib/auth/session";
-export async function POST() {
+export async function POST(request: Request) {
const env = getEnv();
const jar = await cookies();
- const token = jar.get(SESSION_COOKIE)?.value;
+ const authorization = request.headers.get("Authorization");
+ const bearerToken = authorization?.startsWith("Bearer ") ? authorization.slice(7).trim() : undefined;
+ const token = bearerToken || jar.get(SESSION_COOKIE)?.value;
if (token) await deleteSession(env, token);
const response = NextResponse.json({ ok: true });
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
new file mode 100644
index 0000000..9951da0
--- /dev/null
+++ b/src/app/api/auth/me/route.ts
@@ -0,0 +1,23 @@
+import { NextResponse } from "next/server";
+import { getCurrentUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { userHasMailboxes } from "@/lib/user";
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const user = await getCurrentUser(env, request);
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const hasMailboxes = await userHasMailboxes(env, user.id);
+ return NextResponse.json({
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ resetEmail: user.resetEmail,
+ },
+ hasMailboxes,
+ });
+}
diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.ts
index ffd6910..3d6ed6b 100644
--- a/src/app/api/auth/register/route.ts
+++ b/src/app/api/auth/register/route.ts
@@ -102,7 +102,7 @@ export async function POST(request: Request) {
}
const token = await createSession(env, userId);
- const response = NextResponse.json({ ok: true, redirect: "/inbox" });
+ const response = NextResponse.json({ ok: true, token, redirect: "/inbox" });
response.cookies.set(SESSION_COOKIE, token, {
httpOnly: true,
sameSite: "lax",
diff --git a/src/app/api/domains/[id]/dns/route.ts b/src/app/api/domains/[id]/dns/route.ts
index 43042d6..448b771 100644
--- a/src/app/api/domains/[id]/dns/route.ts
+++ b/src/app/api/domains/[id]/dns/route.ts
@@ -5,10 +5,10 @@ import { getDomainDns, getDomainForUser } from "@/lib/domains/service";
type Params = { params: Promise<{ id: string }> };
-export async function GET(_request: Request, { params }: Params) {
+export async function GET(request: Request, { params }: Params) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const domain = await getDomainForUser(env, user.id, id);
if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
diff --git a/src/app/api/domains/[id]/route.ts b/src/app/api/domains/[id]/route.ts
index dd3bc62..ac296c8 100644
--- a/src/app/api/domains/[id]/route.ts
+++ b/src/app/api/domains/[id]/route.ts
@@ -5,19 +5,19 @@ import { getDomainForUser, removeDomainForUser } from "@/lib/domains/service";
type Params = { params: Promise<{ id: string }> };
-export async function GET(_request: Request, { params }: Params) {
+export async function GET(request: Request, { params }: Params) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const domain = await getDomainForUser(env, user.id, id);
if (!domain) return NextResponse.json({ error: "Not found" }, { status: 404 });
return NextResponse.json({ domain });
}
-export async function DELETE(_request: Request, { params }: Params) {
+export async function DELETE(request: Request, { params }: Params) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
try {
await removeDomainForUser(env, user.id, id);
return NextResponse.json({ ok: true });
diff --git a/src/app/api/domains/route.ts b/src/app/api/domains/route.ts
index b976078..88b1ac8 100644
--- a/src/app/api/domains/route.ts
+++ b/src/app/api/domains/route.ts
@@ -7,7 +7,7 @@ import { summariseDns, type DnsStatusSummary } from "@/lib/dns-status";
export async function GET(request: NextRequest) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const domains = await listUserDomains(env, user.id);
const includeDns = request.nextUrl.searchParams.get("includeDns") === "true";
@@ -35,7 +35,7 @@ export async function GET(request: NextRequest) {
export async function POST(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const parsed = addDomainSchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
diff --git a/src/app/api/drafts/[id]/route.ts b/src/app/api/drafts/[id]/route.ts
index d7b921e..d16013a 100644
--- a/src/app/api/drafts/[id]/route.ts
+++ b/src/app/api/drafts/[id]/route.ts
@@ -8,10 +8,10 @@ import { buildSnippet } from "@/lib/email/parse";
import type { DraftPayload, DraftRouteParams } from "./types";
import { selectDraftWithBody } from "./utils";
-export async function GET(_request: Request, { params }: DraftRouteParams) {
+export async function GET(request: Request, { params }: DraftRouteParams) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const db = getDb(env);
const draft = await selectDraftWithBody(db, user.id, id);
@@ -25,7 +25,7 @@ export async function GET(_request: Request, { params }: DraftRouteParams) {
export async function PATCH(request: Request, { params }: DraftRouteParams) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const input = (await request.json()) as DraftPayload;
const db = getDb(env);
const [draft] = await db.select().from(messages).where(eq(messages.id, id)).limit(1);
@@ -58,10 +58,10 @@ export async function PATCH(request: Request, { params }: DraftRouteParams) {
return NextResponse.json({ draft: { id } });
}
-export async function DELETE(_request: Request, { params }: DraftRouteParams) {
+export async function DELETE(request: Request, { params }: DraftRouteParams) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const db = getDb(env);
const [draft] = await db.select().from(messages).where(eq(messages.id, id)).limit(1);
diff --git a/src/app/api/drafts/route.ts b/src/app/api/drafts/route.ts
index 67e3189..e289cef 100644
--- a/src/app/api/drafts/route.ts
+++ b/src/app/api/drafts/route.ts
@@ -18,7 +18,7 @@ type DraftPayload = {
export async function GET(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const url = new URL(request.url);
const mailboxId = url.searchParams.get("mailboxId");
const db = getDb(env);
@@ -41,7 +41,7 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const input = (await request.json()) as DraftPayload;
const db = getDb(env);
const draftId = newId("msg");
diff --git a/src/app/api/mailboxes/[id]/route.ts b/src/app/api/mailboxes/[id]/route.ts
index 57b3763..a5d09e8 100644
--- a/src/app/api/mailboxes/[id]/route.ts
+++ b/src/app/api/mailboxes/[id]/route.ts
@@ -8,10 +8,10 @@ import { updateMailboxSchema } from "@/lib/validators";
import type { MailboxRouteParams } from "./types";
import { getMailboxUpdateValues, selectMailboxForUser } from "./utils";
-export async function GET(_request: Request, { params }: MailboxRouteParams) {
+export async function GET(request: Request, { params }: MailboxRouteParams) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const db = getDb(env);
const [mailbox] = await selectMailboxForUser(db, user.id, id);
@@ -30,7 +30,7 @@ export async function GET(_request: Request, { params }: MailboxRouteParams) {
export async function PATCH(request: Request, { params }: MailboxRouteParams) {
const { id } = await params;
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const parsed = updateMailboxSchema.safeParse(await request.json());
if (!parsed.success) {
diff --git a/src/app/api/mailboxes/route.ts b/src/app/api/mailboxes/route.ts
index c23bf9e..5eb3c7b 100644
--- a/src/app/api/mailboxes/route.ts
+++ b/src/app/api/mailboxes/route.ts
@@ -8,9 +8,9 @@ import { newId } from "@/lib/ids";
import { mailboxSchema } from "@/lib/validators";
import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";
-export async function GET() {
+export async function GET(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const db = getDb(env);
const rows = await db
.select({
@@ -35,7 +35,7 @@ export async function GET() {
export async function POST(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const parsed = mailboxSchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
diff --git a/src/app/api/messages/[messageId]/read/route.ts b/src/app/api/messages/[messageId]/read/route.ts
index 1efcd8d..6a23a14 100644
--- a/src/app/api/messages/[messageId]/read/route.ts
+++ b/src/app/api/messages/[messageId]/read/route.ts
@@ -9,7 +9,7 @@ export async function POST(
) {
const { messageId } = await params;
const env = getEnv();
- const user = await getCurrentUser(env);
+ const user = await getCurrentUser(env, request);
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
diff --git a/src/app/api/messages/[messageId]/route.ts b/src/app/api/messages/[messageId]/route.ts
new file mode 100644
index 0000000..6a6822d
--- /dev/null
+++ b/src/app/api/messages/[messageId]/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse } from "next/server";
+import { getCurrentUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { getMessageWithBody } from "@/lib/email/inbound";
+
+type MessageRouteParams = {
+ params: Promise<{ messageId: string }>;
+};
+
+export async function GET(request: Request, { params }: MessageRouteParams) {
+ const env = getEnv();
+ const user = await getCurrentUser(env, request);
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const { messageId } = await params;
+ const data = await getMessageWithBody(env, user.id, messageId);
+ if (!data) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
+ return NextResponse.json(data);
+}
diff --git a/src/app/api/messages/[messageId]/status/route.ts b/src/app/api/messages/[messageId]/status/route.ts
index dcc98e5..2499fc3 100644
--- a/src/app/api/messages/[messageId]/status/route.ts
+++ b/src/app/api/messages/[messageId]/status/route.ts
@@ -11,7 +11,7 @@ export async function POST(
) {
const { messageId } = await params;
const env = getEnv();
- const user = await getCurrentUser(env);
+ const user = await getCurrentUser(env, request);
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
diff --git a/src/app/api/messages/bulk/route.ts b/src/app/api/messages/bulk/route.ts
new file mode 100644
index 0000000..fbc4007
--- /dev/null
+++ b/src/app/api/messages/bulk/route.ts
@@ -0,0 +1,45 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { messages } from "@/db/schema";
+import { getCurrentUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import type { BulkMessagePayload } from "./types";
+import {
+ getReadValueForBulkAction,
+ getStatusForBulkAction,
+ isAllowedBulkMessageAction,
+} from "./utils";
+
+export async function POST(request: Request) {
+ const env = getEnv();
+ const user = await getCurrentUser(env, request);
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const payload = (await request.json()) as BulkMessagePayload;
+ const messageIds = payload.messageIds?.filter(Boolean) ?? [];
+ if (messageIds.length === 0 || !isAllowedBulkMessageAction(payload.action)) {
+ return NextResponse.json({ error: "Invalid bulk message action" }, { status: 400 });
+ }
+
+ const status = getStatusForBulkAction(payload.action);
+ const read = getReadValueForBulkAction(payload.action);
+ const values = {
+ ...(status ? { status } : {}),
+ ...(read !== null ? { read } : {}),
+ };
+
+ if (Object.keys(values).length === 0) {
+ return NextResponse.json({ error: "No changes requested" }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ await db
+ .update(messages)
+ .set(values)
+ .where(and(eq(messages.userId, user.id), inArray(messages.id, messageIds)));
+
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/messages/bulk/types.d.ts b/src/app/api/messages/bulk/types.d.ts
new file mode 100644
index 0000000..8da1d10
--- /dev/null
+++ b/src/app/api/messages/bulk/types.d.ts
@@ -0,0 +1,6 @@
+export type BulkMessageAction = "archive" | "trash" | "spam" | "read" | "unread" | "inbox";
+
+export type BulkMessagePayload = {
+ messageIds?: string[];
+ action?: BulkMessageAction;
+};
diff --git a/src/app/api/messages/bulk/utils.ts b/src/app/api/messages/bulk/utils.ts
new file mode 100644
index 0000000..17df126
--- /dev/null
+++ b/src/app/api/messages/bulk/utils.ts
@@ -0,0 +1,28 @@
+import type { BulkMessageAction } from "./types";
+
+const allowedBulkActions = new Set<BulkMessageAction>([
+ "archive",
+ "trash",
+ "spam",
+ "read",
+ "unread",
+ "inbox",
+]);
+
+export function isAllowedBulkMessageAction(action: unknown): action is BulkMessageAction {
+ return typeof action === "string" && allowedBulkActions.has(action as BulkMessageAction);
+}
+
+export function getStatusForBulkAction(action: BulkMessageAction): string | null {
+ if (action === "archive") return "archived";
+ if (action === "trash") return "trash";
+ if (action === "spam") return "spam";
+ if (action === "inbox") return "received";
+ return null;
+}
+
+export function getReadValueForBulkAction(action: BulkMessageAction): boolean | null {
+ if (action === "read") return true;
+ if (action === "unread") return false;
+ return null;
+}
diff --git a/src/app/api/messages/counts/route.ts b/src/app/api/messages/counts/route.ts
index df6a44e..f86d442 100644
--- a/src/app/api/messages/counts/route.ts
+++ b/src/app/api/messages/counts/route.ts
@@ -8,7 +8,7 @@ import { buildMessageCounts } from "./utils";
export async function GET(request: Request) {
const env = getEnv();
- const user = await getCurrentUser(env);
+ const user = await getCurrentUser(env, request);
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.ts
index b9b36e6..c1eb33a 100644
--- a/src/app/api/messages/route.ts
+++ b/src/app/api/messages/route.ts
@@ -1,13 +1,15 @@
import { NextResponse } from "next/server";
-import { eq, desc, and, like, or } from "drizzle-orm";
+import { eq, desc, and, like, or, count } from "drizzle-orm";
import { getEnv } from "@/lib/cloudflare";
import { getCurrentUser } from "@/lib/auth/cookies";
import { getDb } from "@/db";
import { messages } from "@/db/schema";
+import { getContactDisplayNameMap } from "@/lib/contacts/service";
+import { normalizeEmailAddress } from "@/lib/email/address";
export async function GET(request: Request) {
const env = getEnv();
- const user = await getCurrentUser(env);
+ const user = await getCurrentUser(env, request);
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
@@ -20,6 +22,7 @@ export async function GET(request: Request) {
const title = url.searchParams.get("title")?.trim();
const read = url.searchParams.get("read");
const limit = Math.min(Number(url.searchParams.get("limit") ?? 50), 100);
+ const offset = Math.max(Number(url.searchParams.get("offset") ?? 0), 0);
const db = getDb(env);
const conditions = [eq(messages.userId, user.id)];
@@ -51,13 +54,29 @@ export async function GET(request: Request) {
if (title) {
conditions.push(like(messages.subject, `%${title}%`));
}
+ const where = and(...conditions);
+ const [totalRow] = await db
+ .select({ total: count() })
+ .from(messages)
+ .where(where);
const rows = await db
.select()
.from(messages)
- .where(and(...conditions))
+ .where(where)
.orderBy(desc(messages.createdAt))
- .limit(limit);
+ .limit(limit)
+ .offset(offset);
+ const contactMap = await getContactDisplayNameMap(
+ env,
+ user.id,
+ rows.flatMap((message) => [message.fromAddr, message.toAddr]),
+ );
+ const enrichedRows = rows.map((message) => ({
+ ...message,
+ fromContactName: contactMap.get(normalizeEmailAddress(message.fromAddr)) ?? null,
+ toContactName: contactMap.get(normalizeEmailAddress(message.toAddr)) ?? null,
+ }));
- return NextResponse.json({ messages: rows });
+ return NextResponse.json({ messages: enrichedRows, total: totalRow?.total ?? 0, limit, offset });
}
diff --git a/src/app/api/routing-rules/route.ts b/src/app/api/routing-rules/route.ts
index 235ccae..c640706 100644
--- a/src/app/api/routing-rules/route.ts
+++ b/src/app/api/routing-rules/route.ts
@@ -7,9 +7,9 @@ import { requireUser } from "@/lib/auth/cookies";
import { newId } from "@/lib/ids";
import { routingRuleSchema } from "@/lib/validators";
-export async function GET() {
+export async function GET(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const db = getDb(env);
const rows = await db.select().from(routingRules).where(eq(routingRules.userId, user.id));
return NextResponse.json({ rules: rows });
@@ -17,7 +17,7 @@ export async function GET() {
export async function POST(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const parsed = routingRuleSchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
diff --git a/src/app/api/send/route.ts b/src/app/api/send/route.ts
index 081ebfc..f32bf47 100644
--- a/src/app/api/send/route.ts
+++ b/src/app/api/send/route.ts
@@ -6,7 +6,7 @@ import { sendEmail } from "@/lib/email/send";
export async function POST(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const parsed = sendEmailSchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
diff --git a/src/app/api/settings/profile/route.ts b/src/app/api/settings/profile/route.ts
index 7de70b8..109bb3e 100644
--- a/src/app/api/settings/profile/route.ts
+++ b/src/app/api/settings/profile/route.ts
@@ -1,22 +1,41 @@
import { NextResponse } from "next/server";
import { eq } from "drizzle-orm";
+import { ZodError } from "zod";
import { getEnv } from "@/lib/cloudflare";
import { getDb } from "@/db";
import { users } from "@/db/schema";
import { requireUser } from "@/lib/auth/cookies";
+import type { UpdateProfileInput } from "./types";
+import { parseUpdateProfileRequest } from "./utils";
export async function PATCH(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
- const body = (await request.json()) as { name?: unknown };
- const name = typeof body.name === "string" ? body.name.trim() : "";
-
- if (!name) {
- return NextResponse.json({ error: "Name is required" }, { status: 400 });
+ const user = await requireUser(env, request);
+ let parsed: UpdateProfileInput;
+ try {
+ parsed = await parseUpdateProfileRequest(request);
+ } catch (err) {
+ if (err instanceof ZodError) {
+ return NextResponse.json({ error: err.flatten() }, { status: 400 });
+ }
+ return NextResponse.json({ error: "Invalid request" }, { status: 400 });
}
const db = getDb(env);
- await db.update(users).set({ name }).where(eq(users.id, user.id));
+ await db
+ .update(users)
+ .set({
+ name: parsed.name,
+ resetEmail: parsed.resetEmail,
+ })
+ .where(eq(users.id, user.id));
- return NextResponse.json({ user: { id: user.id, email: user.email, name } });
+ return NextResponse.json({
+ user: {
+ id: user.id,
+ email: user.email,
+ name: parsed.name,
+ resetEmail: parsed.resetEmail,
+ },
+ });
}
diff --git a/src/app/api/settings/profile/types.d.ts b/src/app/api/settings/profile/types.d.ts
new file mode 100644
index 0000000..6d99f6d
--- /dev/null
+++ b/src/app/api/settings/profile/types.d.ts
@@ -0,0 +1,13 @@
+import type { updateProfileSchema } from "@/lib/validators";
+import type { z } from "zod";
+
+export type UpdateProfileInput = z.infer<typeof updateProfileSchema>;
+
+export type ProfileResponse = {
+ user: {
+ id: string;
+ email: string;
+ name: string;
+ resetEmail: string | null;
+ };
+};
diff --git a/src/app/api/settings/profile/utils.ts b/src/app/api/settings/profile/utils.ts
new file mode 100644
index 0000000..0f4755d
--- /dev/null
+++ b/src/app/api/settings/profile/utils.ts
@@ -0,0 +1,7 @@
+import { updateProfileSchema } from "@/lib/validators";
+import type { UpdateProfileInput } from "./types";
+
+export async function parseUpdateProfileRequest(request: Request): Promise<UpdateProfileInput> {
+ const body = await request.json();
+ return updateProfileSchema.parse(body);
+}
diff --git a/src/app/api/webhooks/route.ts b/src/app/api/webhooks/route.ts
index 01b3aa7..83933d2 100644
--- a/src/app/api/webhooks/route.ts
+++ b/src/app/api/webhooks/route.ts
@@ -7,9 +7,9 @@ import { requireUser } from "@/lib/auth/cookies";
import { newId } from "@/lib/ids";
import { webhookSchema } from "@/lib/validators";
-export async function GET() {
+export async function GET(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const db = getDb(env);
const rows = await db.select().from(webhooks).where(eq(webhooks.userId, user.id));
return NextResponse.json({
@@ -19,7 +19,7 @@ export async function GET() {
export async function POST(request: Request) {
const env = getEnv();
- const user = await requireUser(env);
+ const user = await requireUser(env, request);
const parsed = webhookSchema.safeParse(await request.json());
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx
index c5b60da..35c3cd5 100644
--- a/src/app/login/page.tsx
+++ b/src/app/login/page.tsx
@@ -1,13 +1,10 @@
-import { redirect } from "next/navigation";
-import { getCurrentUser } from "@/lib/auth/cookies";
-import { getEnv } from "@/lib/cloudflare";
+import { AuthGuard } from "@/components/auth/auth-guard";
import { LoginClient } from "./login-client";
-export const dynamic = "force-dynamic";
-
-export default async function LoginPage() {
- const user = await getCurrentUser(getEnv());
- if (user) redirect("/inbox");
-
- return <LoginClient />;
+export default function LoginPage() {
+ return (
+ <AuthGuard mode="public">
+ <LoginClient />
+ </AuthGuard>
+ );
}
diff --git a/src/app/login/types.d.ts b/src/app/login/types.d.ts
index e813542..b0f1b7b 100644
--- a/src/app/login/types.d.ts
+++ b/src/app/login/types.d.ts
@@ -1,4 +1,5 @@
export type LoginResult = {
+ token?: string;
redirect?: string;
error?: string;
};
diff --git a/src/app/login/utils.ts b/src/app/login/utils.ts
index be663ba..ed83ed8 100644
--- a/src/app/login/utils.ts
+++ b/src/app/login/utils.ts
@@ -1,3 +1,4 @@
+import { persistAuthSession } from "@/lib/auth/client";
import type { LoginResult } from "./types";
export async function submitLogin(form: FormData): Promise<{ ok: boolean; data: LoginResult }> {
@@ -12,6 +13,6 @@ export async function submitLogin(form: FormData): Promise<{ ok: boolean; data:
return {
ok: res.ok,
- data: (await res.json()) as LoginResult,
+ data: (await persistAuthSession(res)) as LoginResult,
};
}
diff --git a/src/app/onboarding/page.tsx b/src/app/onboarding/page.tsx
index 065029a..7552142 100644
--- a/src/app/onboarding/page.tsx
+++ b/src/app/onboarding/page.tsx
@@ -1,18 +1,10 @@
-import { redirect } from "next/navigation";
+import { AuthGuard } from "@/components/auth/auth-guard";
import { OnboardingClient } from "./onboarding-client";
-import { getCurrentUser } from "@/lib/auth/cookies";
-import { getEnv } from "@/lib/cloudflare";
-import { userHasMailboxes } from "@/lib/user";
-export const dynamic = "force-dynamic";
-
-export default async function OnboardingPage() {
- const env = getEnv();
- const user = await getCurrentUser(env);
- if (!user) redirect("/login");
-
- const hasMailboxes = await userHasMailboxes(env, user.id);
- if (hasMailboxes) redirect("/inbox");
-
- return <OnboardingClient />;
+export default function OnboardingPage() {
+ return (
+ <AuthGuard>
+ <OnboardingClient />
+ </AuthGuard>
+ );
}
diff --git a/src/app/onboarding/utils.ts b/src/app/onboarding/utils.ts
index 96448b7..520f57f 100644
--- a/src/app/onboarding/utils.ts
+++ b/src/app/onboarding/utils.ts
@@ -1,12 +1,13 @@
+import { authFetch } from "@/lib/auth/client";
import type { DomainCreateResult, DomainListResult, MailboxCreateResult } from "./types";
export async function getDomains(): Promise<DomainListResult> {
- const res = await fetch("/api/domains");
+ const res = await authFetch("/api/domains");
return (await res.json()) as DomainListResult;
}
export async function createDomain(hostname: string): Promise<{ ok: boolean; data: DomainCreateResult }> {
- const res = await fetch("/api/domains", {
+ const res = await authFetch("/api/domains", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ hostname, enableRouting: true, enableSending: true }),
@@ -22,7 +23,7 @@ export async function createMailbox(
domainId: string,
localPart: string,
): Promise<{ ok: boolean; data: MailboxCreateResult }> {
- const res = await fetch("/api/mailboxes", {
+ const res = await authFetch("/api/mailboxes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ domainId, localPart, displayName: localPart }),
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 0335d89..ab88abe 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -1,15 +1,33 @@
+"use client";
+
import Link from "next/link";
-import { getEnv } from "@/lib/cloudflare";
+import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
-import { getCurrentUser } from "@/lib/auth/cookies";
+import { authFetch, getClientSessionToken } from "@/lib/auth/client";
import { getHomeActions, heroMessages, sidebarItems } from "./utils";
import { ArrowRight, Inbox, Mail, Search, ShieldCheck } from "lucide-react";
-export const dynamic = "force-dynamic";
+export default function HomePage() {
+ const [hasUser, setHasUser] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ if (!getClientSessionToken()) return;
+
+ authFetch("/api/auth/me", { redirectOnUnauthorized: false })
+ .then((response) => {
+ if (!cancelled) setHasUser(response.ok);
+ })
+ .catch(() => {
+ if (!cancelled) setHasUser(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, []);
-export default async function HomePage() {
- const user = await getCurrentUser(getEnv());
- const actions = getHomeActions(Boolean(user));
+ const actions = getHomeActions(hasUser);
return (
<div className="min-h-dvh bg-[#f6f8fc] text-neutral-900">
@@ -60,7 +78,7 @@ export default async function HomePage() {
<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"}>
- {user ? "Open dashboard" : "Create account"}
+ {hasUser ? "Open dashboard" : "Create account"}
<ArrowRight className="h-4 w-4" />
</Link>
</Button>
@@ -70,8 +88,8 @@ export default async function HomePage() {
asChild
className="rounded-full border-neutral-200 bg-white px-6"
>
- <Link href={user ? "/inbox" : "/login"}>
- {user ? "View inbox" : "Log in"}
+ <Link href={hasUser ? "/inbox" : "/login"}>
+ {hasUser ? "View inbox" : "Log in"}
</Link>
</Button>
</div>
diff --git a/src/app/register/page.tsx b/src/app/register/page.tsx
index 3a36ee6..96afc2c 100644
--- a/src/app/register/page.tsx
+++ b/src/app/register/page.tsx
@@ -1,13 +1,10 @@
-import { redirect } from "next/navigation";
-import { getCurrentUser } from "@/lib/auth/cookies";
-import { getEnv } from "@/lib/cloudflare";
+import { AuthGuard } from "@/components/auth/auth-guard";
import { RegisterClient } from "./register-client";
-export const dynamic = "force-dynamic";
-
-export default async function RegisterPage() {
- const user = await getCurrentUser(getEnv());
- if (user) redirect("/inbox");
-
- return <RegisterClient />;
+export default function RegisterPage() {
+ return (
+ <AuthGuard mode="public">
+ <RegisterClient />
+ </AuthGuard>
+ );
}
diff --git a/src/app/register/types.d.ts b/src/app/register/types.d.ts
index b3531d3..bffbe28 100644
--- a/src/app/register/types.d.ts
+++ b/src/app/register/types.d.ts
@@ -9,6 +9,7 @@ export type DomainSetupResult = {
};
export type RegisterResult = {
+ token?: string;
redirect?: string;
error?: string;
};
diff --git a/src/app/register/utils.ts b/src/app/register/utils.ts
index efcf4e7..e30a909 100644
--- a/src/app/register/utils.ts
+++ b/src/app/register/utils.ts
@@ -1,3 +1,4 @@
+import { persistAuthSession } from "@/lib/auth/client";
import type { DomainSetupResult, RegisterResult, SetupStatus } from "./types";
export async function getSetupStatus(): Promise<SetupStatus> {
@@ -43,6 +44,6 @@ export async function submitRegistration(
return {
ok: res.ok,
- data: (await res.json()) as RegisterResult,
+ data: (await persistAuthSession(res)) as RegisterResult,
};
}
diff --git a/src/components/auth/auth-guard-types.d.ts b/src/components/auth/auth-guard-types.d.ts
new file mode 100644
index 0000000..a0fa697
--- /dev/null
+++ b/src/components/auth/auth-guard-types.d.ts
@@ -0,0 +1,9 @@
+import type { ReactNode } from "react";
+
+export type AuthGuardMode = "protected" | "public";
+
+export type AuthGuardProps = {
+ children: ReactNode;
+ mode?: AuthGuardMode;
+ requireMailbox?: boolean;
+};
diff --git a/src/components/auth/auth-guard.tsx b/src/components/auth/auth-guard.tsx
new file mode 100644
index 0000000..f300e7d
--- /dev/null
+++ b/src/components/auth/auth-guard.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { usePathname, useRouter } from "next/navigation";
+import { useEffect, useState } from "react";
+import { authFetch, getClientSessionToken } from "@/lib/auth/client";
+import type { AuthGuardProps } from "./auth-guard-types";
+
+export function AuthGuard({ children, mode = "protected", requireMailbox }: AuthGuardProps) {
+ const pathname = usePathname();
+ const router = useRouter();
+ const [authorized, setAuthorized] = useState(mode === "public");
+
+ useEffect(() => {
+ let cancelled = false;
+ const token = getClientSessionToken();
+
+ if (!token) {
+ if (mode === "protected") router.replace("/login");
+ return;
+ }
+
+ async function checkSession() {
+ const response = await authFetch("/api/auth/me", { redirectOnUnauthorized: mode === "protected" });
+ if (cancelled) return;
+
+ if (!response.ok) {
+ if (mode === "public") setAuthorized(true);
+ return;
+ }
+
+ const data = (await response.json()) as { hasMailboxes?: boolean };
+ if (mode === "public") {
+ router.replace(data.hasMailboxes === false ? "/onboarding" : "/inbox");
+ return;
+ }
+
+ if (requireMailbox && data.hasMailboxes === false && pathname !== "/onboarding") {
+ router.replace("/onboarding");
+ return;
+ }
+
+ if (!requireMailbox && data.hasMailboxes && pathname === "/onboarding") {
+ router.replace("/inbox");
+ return;
+ }
+
+ setAuthorized(true);
+ }
+
+ void checkSession();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [mode, pathname, requireMailbox, router]);
+
+ if (!authorized) return null;
+ return <>{children}</>;
+}
diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsx
index b9fbd8e..09f82fd 100644
--- a/src/components/compose/compose-form.tsx
+++ b/src/components/compose/compose-form.tsx
@@ -7,6 +7,8 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useSelectedMailbox } from "@/components/mailbox-provider";
+import { authFetch } from "@/lib/auth/client";
+import { formatEmailAddress } from "@/lib/email/address";
import { cn } from "@/lib/utils";
import { fetchDraft } from "./utils";
@@ -33,7 +35,13 @@ export function ComposeForm({
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const fromAddr = useMemo(
- () => (selectedMailbox ? `${selectedMailbox.localPart}@${selectedMailbox.hostname}` : ""),
+ () =>
+ selectedMailbox
+ ? formatEmailAddress(
+ `${selectedMailbox.localPart}@${selectedMailbox.hostname}`,
+ selectedMailbox.displayName ?? selectedMailbox.localPart,
+ )
+ : "",
[selectedMailbox],
);
@@ -92,7 +100,7 @@ export function ComposeForm({
subject,
text,
};
- const res = await fetch(draftId ? `/api/drafts/${draftId}` : "/api/drafts", {
+ const res = await authFetch(draftId ? `/api/drafts/${draftId}` : "/api/drafts", {
method: draftId ? "PATCH" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
@@ -109,7 +117,7 @@ export function ComposeForm({
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setLoading(true);
- const res = await fetch("/api/send", {
+ const res = await authFetch("/api/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -129,7 +137,7 @@ export function ComposeForm({
}
if (draftId) {
- void fetch(`/api/drafts/${draftId}`, { method: "DELETE" }).finally(() => {
+ void authFetch(`/api/drafts/${draftId}`, { method: "DELETE" }).finally(() => {
window.dispatchEvent(new Event("mailflare:messages-changed"));
});
}
@@ -187,8 +195,8 @@ export function ComposeForm({
id={`${mode}-to`}
value={to}
onChange={(event) => setTo(event.target.value)}
- type="email"
- placeholder="Recipients"
+ type="text"
+ placeholder='Recipients, or "Maya Chen" <[email protected]>'
required
disabled={loadingDraft}
className="h-8 border-0 px-0 py-1 shadow-none focus-visible:ring-0"
diff --git a/src/components/compose/utils.ts b/src/components/compose/utils.ts
index 83820e3..e221cb6 100644
--- a/src/components/compose/utils.ts
+++ b/src/components/compose/utils.ts
@@ -1,7 +1,8 @@
+import { authFetch } from "@/lib/auth/client";
import type { ComposeDraft, DraftResponse } from "./types";
export async function fetchDraft(draftId: string): Promise<ComposeDraft> {
- const res = await fetch(`/api/drafts/${draftId}`);
+ const res = await authFetch(`/api/drafts/${draftId}`);
const json = (await res.json()) as DraftResponse;
if (!res.ok || !json.draft) {
diff --git a/src/components/dashboard-nav-utils.ts b/src/components/dashboard-nav-utils.ts
index 6b28e32..9a6330d 100644
--- a/src/components/dashboard-nav-utils.ts
+++ b/src/components/dashboard-nav-utils.ts
@@ -1,7 +1,7 @@
import type { MessageCounts, MessageFolder } from "@/hooks/types";
-export function getFolderNavCount(folder: MessageFolder, counts: MessageCounts["folders"]): number {
+export function getFolderNavCount(folder: MessageFolder, counts: MessageCounts["folders"]): number | undefined {
const count = counts[folder];
- if (folder === "inbox" || folder === "spam") return count.unread || count.total;
- return count.total;
+ if (folder === "inbox" || folder === "spam") return count.unread;
+ return undefined;
}
diff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsx
index c6dea27..09e1a4c 100644
--- a/src/components/dashboard-nav.tsx
+++ b/src/components/dashboard-nav.tsx
@@ -28,14 +28,11 @@ const links = [
];
export function DashboardNav({ className }: { className?: string }) {
- const { selectedMailbox } = useSelectedMailbox();
- const { counts } = useMessageCounts(selectedMailbox?.id);
+ const { selectedMailbox, isLoading } = useSelectedMailbox();
+ const { counts } = useMessageCounts(selectedMailbox?.id, !isLoading);
const linksWithCounts = links.map((link) => {
if (link.href === "/inbox") return { ...link, count: getFolderNavCount("inbox", counts.folders) };
- if (link.href === "/sent") return { ...link, count: getFolderNavCount("sent", counts.folders) };
- if (link.href === "/drafts") return { ...link, count: getFolderNavCount("drafts", counts.folders) };
if (link.href === "/spam") return { ...link, count: getFolderNavCount("spam", counts.folders) };
- if (link.href === "/trash") return { ...link, count: getFolderNavCount("trash", counts.folders) };
return link;
});
diff --git a/src/components/logout-button.tsx b/src/components/logout-button.tsx
index 9737d2e..0130112 100644
--- a/src/components/logout-button.tsx
+++ b/src/components/logout-button.tsx
@@ -2,6 +2,7 @@
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
+import { authFetch, clearClientSessionToken } from "@/lib/auth/client";
export function LogoutButton() {
const router = useRouter();
@@ -10,7 +11,8 @@ export function LogoutButton() {
variant="outline"
className="w-full"
onClick={async () => {
- await fetch("/api/auth/logout", { method: "POST" });
+ await authFetch("/api/auth/logout", { method: "POST", redirectOnUnauthorized: false });
+ clearClientSessionToken();
router.push("/login");
}}
>
diff --git a/src/components/mailbox-provider-utils.ts b/src/components/mailbox-provider-utils.ts
new file mode 100644
index 0000000..ab0856e
--- /dev/null
+++ b/src/components/mailbox-provider-utils.ts
@@ -0,0 +1,34 @@
+import { authFetch } from "@/lib/auth/client";
+import type { MailboxOption } from "./mailbox-provider";
+
+let mailboxesCache: MailboxOption[] | null = null;
+let mailboxesRequest: Promise<MailboxOption[]> | null = null;
+
+export function clearMailboxesCache() {
+ mailboxesCache = null;
+ mailboxesRequest = null;
+}
+
+export async function fetchMailboxOptions(force = false): Promise<MailboxOption[]> {
+ if (!force && mailboxesCache) return mailboxesCache;
+ if (!force && mailboxesRequest) return mailboxesRequest;
+
+ mailboxesRequest = authFetch("/api/mailboxes")
+ .then((res) => res.json())
+ .then((data) => {
+ const items = ((data as { mailboxes?: MailboxOption[] }).mailboxes ?? []).map((m) => ({
+ id: m.id,
+ localPart: m.localPart,
+ hostname: m.hostname,
+ displayName: m.displayName,
+ isPrimary: m.isPrimary,
+ }));
+ mailboxesCache = items;
+ return items;
+ })
+ .finally(() => {
+ mailboxesRequest = null;
+ });
+
+ return mailboxesRequest;
+}
diff --git a/src/components/mailbox-provider.tsx b/src/components/mailbox-provider.tsx
index d443023..c99601e 100644
--- a/src/components/mailbox-provider.tsx
+++ b/src/components/mailbox-provider.tsx
@@ -8,6 +8,7 @@ import {
useState,
} from "react";
import type { ReactNode } from "react";
+import { fetchMailboxOptions } from "./mailbox-provider-utils";
export type MailboxOption = {
id: string;
@@ -40,18 +41,11 @@ export function MailboxProvider({ children }: { children: ReactNode }) {
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
- fetch("/api/mailboxes")
- .then((res) => res.json())
- .then((data) => {
- const items: MailboxOption[] = ((data as { mailboxes: MailboxOption[] }).mailboxes ?? []).map(
- (m: MailboxOption) => ({
- id: m.id,
- localPart: m.localPart,
- hostname: m.hostname,
- displayName: m.displayName,
- isPrimary: m.isPrimary,
- }),
- );
+ let cancelled = false;
+
+ fetchMailboxOptions()
+ .then((items) => {
+ if (cancelled) return;
setMailboxes(items);
const storedId = localStorage.getItem(STORAGE_KEY);
@@ -70,12 +64,19 @@ export function MailboxProvider({ children }: { children: ReactNode }) {
}
})
.catch(() => {})
- .finally(() => setIsLoading(false));
+ .finally(() => {
+ if (!cancelled) setIsLoading(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
}, []);
const setSelectedMailbox = useCallback((mb: MailboxOption | null) => {
setSelectedMailboxState(mb);
if (mb) {
+ setMailboxes((items) => items.map((item) => (item.id === mb.id ? mb : item)));
localStorage.setItem(STORAGE_KEY, mb.id);
} else {
localStorage.removeItem(STORAGE_KEY);
diff --git a/src/components/mailbox-selector.tsx b/src/components/mailbox-selector.tsx
index b779277..f543d2d 100644
--- a/src/components/mailbox-selector.tsx
+++ b/src/components/mailbox-selector.tsx
@@ -6,6 +6,7 @@ import { Check, LogOut, Mail, Settings } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { useMessageCounts } from "@/hooks/use-message-counts";
+import { authFetch, clearClientSessionToken } from "@/lib/auth/client";
import { cn } from "@/lib/utils";
export function MailboxSelector() {
@@ -15,7 +16,7 @@ export function MailboxSelector() {
const router = useRouter();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
- const { counts } = useMessageCounts();
+ const { counts } = useMessageCounts(null, open);
useEffect(() => {
function onPointerDown(event: PointerEvent) {
@@ -38,11 +39,11 @@ export function MailboxSelector() {
pathname.startsWith("/domains") ||
pathname.startsWith("/routing") ||
pathname.startsWith("/api-keys") ||
- pathname.startsWith("/webhooks") ||
- pathname.startsWith("/settings");
+ pathname.startsWith("/webhooks");
async function logout() {
- await fetch("/api/auth/logout", { method: "POST" });
+ await authFetch("/api/auth/logout", { method: "POST", redirectOnUnauthorized: false });
+ clearClientSessionToken();
setOpen(false);
router.push("/login");
}
diff --git a/src/components/mark-read.tsx b/src/components/mark-read.tsx
index 2a2a033..244dfd7 100644
--- a/src/components/mark-read.tsx
+++ b/src/components/mark-read.tsx
@@ -1,10 +1,11 @@
"use client";
import { useEffect } from "react";
+import { authFetch } from "@/lib/auth/client";
export function MarkAsRead({ messageId }: { messageId: string }) {
useEffect(() => {
- fetch(`/api/messages/${messageId}/read`, { method: "POST" })
+ authFetch(`/api/messages/${messageId}/read`, { method: "POST" })
.then((response) => {
if (response.ok) window.dispatchEvent(new Event("mailflare:messages-changed"));
})
diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsx
index 7b911ff..d14befd 100644
--- a/src/components/message-actions/message-actions.tsx
+++ b/src/components/message-actions/message-actions.tsx
@@ -2,61 +2,111 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
-import { MoreVertical, Reply, ShieldAlert, Trash2 } from "lucide-react";
-import type { MessageActionsProps, MessageActionStatus } from "./types";
-import { updateMessageFolder } from "./utils";
+import { Archive, Mail, MailOpen, MoreVertical, Reply, ShieldAlert, Trash2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
+import type { MessageActionsProps } from "./types";
+import { getMessageActionRedirect, runSingleMessageAction } from "./utils";
-export function MessageActions({ messageId, direction, status }: MessageActionsProps) {
+export function MessageActions({ messageId, direction, status, read }: MessageActionsProps) {
const router = useRouter();
- const [pendingStatus, setPendingStatus] = useState<MessageActionStatus | null>(null);
+ const [pendingAction, setPendingAction] = useState<BulkMessageAction | null>(null);
const [error, setError] = useState<string | null>(null);
- async function moveToFolder(nextStatus: MessageActionStatus) {
- setPendingStatus(nextStatus);
+ async function runAction(action: BulkMessageAction) {
+ setPendingAction(action);
setError(null);
try {
- await updateMessageFolder(messageId, nextStatus);
- router.push(nextStatus === "trash" ? "/trash" : "/spam");
+ await runSingleMessageAction(messageId, action);
+ const redirect = getMessageActionRedirect(action, direction);
+ if (redirect) router.push(redirect);
router.refresh();
} catch {
setError("Could not update message");
} finally {
- setPendingStatus(null);
+ setPendingAction(null);
}
}
+ const disabled = pendingAction !== null;
+ const markAction: BulkMessageAction = read ? "unread" : "read";
+
return (
<div className="flex items-center gap-3 text-neutral-600">
{error && <span className="text-xs text-red-600">{error}</span>}
- <div className="flex items-center gap-6">
- <button
- type="button"
- aria-label="Reply"
- className="rounded-full p-1 hover:bg-neutral-100"
- >
- <Reply className="h-5 w-5" />
- </button>
- <button
- type="button"
- aria-label="Report spam"
- disabled={pendingStatus !== null || status === "spam" || direction !== "inbound"}
- onClick={() => moveToFolder("spam")}
- className="rounded-full p-1 hover:bg-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-300"
- >
- <ShieldAlert className="h-5 w-5" />
- </button>
- <button
- type="button"
- aria-label="Move to trash"
- disabled={pendingStatus !== null || status === "trash"}
- onClick={() => moveToFolder("trash")}
- className="rounded-full p-1 hover:bg-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-300"
- >
- <Trash2 className="h-5 w-5" />
- </button>
- <span aria-label="More actions" className="rounded-full p-1">
- <MoreVertical className="h-5 w-5" />
- </span>
+ <div className="flex items-center gap-2">
+ <Tooltip label="Reply">
+ <Button type="button" variant="ghost" size="sm" aria-label="Reply">
+ <Reply className="h-5 w-5" />
+ </Button>
+ </Tooltip>
+ <Tooltip label="Archive">
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label="Archive"
+ disabled={disabled}
+ onClick={() => runAction("archive")}
+ >
+ <Archive className="h-5 w-5" />
+ </Button>
+ </Tooltip>
+ <Tooltip label="Report spam">
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label="Report spam"
+ disabled={disabled || status === "spam" || direction !== "inbound"}
+ onClick={() => runAction("spam")}
+ >
+ <ShieldAlert className="h-5 w-5" />
+ </Button>
+ </Tooltip>
+ <Tooltip label="Delete">
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label="Move to trash"
+ disabled={disabled || status === "trash"}
+ onClick={() => runAction("trash")}
+ >
+ <Trash2 className="h-5 w-5" />
+ </Button>
+ </Tooltip>
+ <Tooltip label={read ? "Mark as unread" : "Mark as read"}>
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label={read ? "Mark as unread" : "Mark as read"}
+ disabled={disabled}
+ onClick={() => runAction(markAction)}
+ >
+ {read ? <Mail className="h-5 w-5" /> : <MailOpen className="h-5 w-5" />}
+ </Button>
+ </Tooltip>
+ <Tooltip label="Move message">
+ <select
+ className="h-8 rounded-lg border border-neutral-200 bg-white px-2 text-xs text-neutral-700"
+ disabled={disabled}
+ defaultValue=""
+ aria-label="Move message"
+ onChange={(event) => {
+ if (!event.target.value) return;
+ void runAction(event.target.value as BulkMessageAction);
+ event.target.value = "";
+ }}
+ >
+ <option value="">Move to...</option>
+ <option value="spam">Spam</option>
+ <option value="trash">Trash</option>
+ </select>
+ </Tooltip>
+ <Tooltip label="More actions">
+ <span aria-label="More actions" className="rounded-full p-1 text-neutral-400">
+ <MoreVertical className="h-5 w-5" />
+ </span>
+ </Tooltip>
</div>
</div>
);
diff --git a/src/components/message-actions/types.d.ts b/src/components/message-actions/types.d.ts
index d5dd758..b31ddba 100644
--- a/src/components/message-actions/types.d.ts
+++ b/src/components/message-actions/types.d.ts
@@ -1,9 +1,11 @@
+import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import type { MessageDirection } from "@/hooks/types";
-export type MessageActionStatus = "trash" | "spam";
-
export type MessageActionsProps = {
messageId: string;
direction: MessageDirection;
status: string;
+ read: boolean;
};
+
+export type SingleMessageAction = BulkMessageAction | "reply";
diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.ts
index 58a8c9c..edc161a 100644
--- a/src/components/message-actions/utils.ts
+++ b/src/components/message-actions/utils.ts
@@ -1,4 +1,5 @@
-import type { MessageActionStatus } from "./types";
+import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
+import { authFetch } from "@/lib/auth/client";
export function getMessageBackHref(direction: "inbound" | "outbound", status: string) {
if (status === "trash") return "/trash";
@@ -7,11 +8,11 @@ export function getMessageBackHref(direction: "inbound" | "outbound", status: st
return direction === "inbound" ? "/inbox" : "/sent";
}
-export async function updateMessageFolder(messageId: string, status: MessageActionStatus) {
- const response = await fetch(`/api/messages/${messageId}/status`, {
+export async function runSingleMessageAction(messageId: string, action: BulkMessageAction) {
+ const response = await authFetch("/api/messages/bulk", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ status }),
+ body: JSON.stringify({ messageIds: [messageId], action }),
});
if (!response.ok) {
@@ -20,3 +21,10 @@ export async function updateMessageFolder(messageId: string, status: MessageActi
window.dispatchEvent(new Event("mailflare:messages-changed"));
}
+
+export function getMessageActionRedirect(action: BulkMessageAction, direction: "inbound" | "outbound") {
+ if (action === "trash") return "/trash";
+ if (action === "spam") return "/spam";
+ if (action === "archive") return direction === "inbound" ? "/inbox" : "/sent";
+ return null;
+}
diff --git a/src/components/messages/bulk-message-toolbar.tsx b/src/components/messages/bulk-message-toolbar.tsx
new file mode 100644
index 0000000..b5410b6
--- /dev/null
+++ b/src/components/messages/bulk-message-toolbar.tsx
@@ -0,0 +1,72 @@
+"use client";
+
+import { Archive, Mail, MailOpen, ShieldAlert, Trash2, X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
+import type { BulkMessageToolbarProps } from "./types";
+
+export function BulkMessageToolbar({
+ selectedCount,
+ hasUnreadSelection,
+ onAction,
+ onClearSelection,
+ pending,
+}: BulkMessageToolbarProps) {
+ return (
+ <div className="flex min-w-0 items-center gap-2 text-neutral-600 w-full">
+ <span className="mr-2 text-sm font-medium text-neutral-800">{selectedCount} selected</span>
+ <Tooltip label="Archive">
+ <Button variant="ghost" size="sm" onClick={() => onAction("archive")} disabled={pending} aria-label="Archive">
+ <Archive className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip label="Report spam">
+ <Button variant="ghost" size="sm" onClick={() => onAction("spam")} disabled={pending} aria-label="Report spam">
+ <ShieldAlert className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip label="Delete">
+ <Button variant="ghost" size="sm" onClick={() => onAction("trash")} disabled={pending} aria-label="Delete">
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip label={hasUnreadSelection ? "Mark as read" : "Mark as unread"}>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onAction(hasUnreadSelection ? "read" : "unread")}
+ disabled={pending}
+ aria-label={hasUnreadSelection ? "Mark as read" : "Mark as unread"}
+ >
+ {hasUnreadSelection ? <MailOpen className="h-4 w-4" /> : <Mail className="h-4 w-4" />}
+ </Button>
+ </Tooltip>
+ <Tooltip label="Move selected messages">
+ <span className="rounded-lg border border-neutral-200 px-2">
+ <select
+ className="bg-white text-xs font-medium pb-1 text-neutral-700 outline-none pr-2"
+ disabled={pending}
+ defaultValue=""
+ aria-label="Move selected messages"
+ onChange={(event) => {
+ if (!event.target.value) return;
+ onAction(event.target.value as BulkMessageAction);
+ event.target.value = "";
+ }}
+ >
+ <option value="">Move to</option>
+ <option value="spam">Spam</option>
+ <option value="trash">Trash</option>
+ </select>
+ </span>
+ </Tooltip>
+ <span className="flex-1" />
+ <Tooltip label="Clear selection">
+ <Button variant="ghost" size="sm" onClick={onClearSelection} disabled={pending} aria-label="Clear selection">
+ <X className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ </div>
+ );
+}
diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsx
index e7f830e..ee6d6b6 100644
--- a/src/components/messages/message-folder-page.tsx
+++ b/src/components/messages/message-folder-page.tsx
@@ -1,25 +1,37 @@
"use client";
import Link from "next/link";
+import { useEffect, useMemo, useState } from "react";
+import { ChevronLeft, ChevronRight } from "lucide-react";
import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
import { useCompose } from "@/components/compose/compose-context";
import { useMailSearch } from "@/components/mail-search/mail-search-context";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { useMessages } from "@/hooks/use-messages";
+import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
+import { BulkMessageToolbar } from "./bulk-message-toolbar";
import type { MessageListRowProps, MessageFolderConfig } from "./types";
import {
+ getPageRange,
getMessageBadge,
getMessageParty,
getMessagePartyClassName,
getMessagePreview,
+ runBulkMessageAction,
} from "./utils";
-function MessageListRow({ message, config }: MessageListRowProps) {
+const pageSize = 25;
+
+function MessageListRow({ message, config, selected, onSelectedChange }: MessageListRowProps) {
const Icon = config.icon;
const { openDraftComposer } = useCompose();
const unread = message.direction === "inbound" && !message.read;
const className =
- "grid min-h-12 w-full grid-cols-[32px_minmax(160px,240px)_1fr_auto] items-center gap-3 px-6 text-left text-sm hover:relative hover:z-10 hover:bg-[#f2f6fc] hover:shadow-sm";
+ `grid min-h-12 w-full grid-cols-[24px_32px_minmax(160px,240px)_1fr_auto] items-center gap-3 px-6 text-left text-sm hover:relative hover:z-10 hover:bg-[#f2f6fc] hover:shadow-sm ${
+ selected ? "bg-blue-50" : ""
+ }`;
const content = (
<>
<Icon className="h-4 w-4 text-neutral-300" />
@@ -27,7 +39,7 @@ function MessageListRow({ message, config }: MessageListRowProps) {
{getMessageParty(message, config.folder)}
</span>
<span className="truncate text-neutral-700">
- <span className={unread ? "font-bold text-neutral-900" : "font-medium"}>
+ <span className={unread ? "font-bold text-neutral-900" : ""}>
{message.subject ?? "(no subject)"}
</span>
<span className="text-neutral-500"> - {getMessagePreview(message, config.folder)}</span>
@@ -42,35 +54,150 @@ function MessageListRow({ message, config }: MessageListRowProps) {
if (config.folder === "drafts") {
return (
- <button type="button" className={className} onClick={() => openDraftComposer(message.id)}>
- {content}
- </button>
+ <div className={className}>
+ <input
+ type="checkbox"
+ checked={selected}
+ onChange={(event) => onSelectedChange(message.id, event.target.checked)}
+ className="h-4 w-4 rounded border-neutral-300"
+ aria-label="Select message"
+ />
+ <button type="button" className="contents text-left" onClick={() => openDraftComposer(message.id)}>
+ {content}
+ </button>
+ </div>
);
}
return (
- <Link href={`${config.hrefPrefix}/${message.id}`} className={className}>
- {content}
- </Link>
+ <div className={className}>
+ <input
+ type="checkbox"
+ checked={selected}
+ onChange={(event) => onSelectedChange(message.id, event.target.checked)}
+ className="h-4 w-4 rounded border-neutral-300"
+ aria-label="Select message"
+ />
+ <Link href={`${config.hrefPrefix}/${message.id}`} className="contents">
+ {content}
+ </Link>
+ </div>
);
}
export function MessageFolderPage({ config }: { config: MessageFolderConfig }) {
- const { selectedMailbox } = useSelectedMailbox();
+ const { selectedMailbox, isLoading: mailboxesLoading } = useSelectedMailbox();
const { query } = useMailSearch();
- const { messages, isLoading } = useMessages(config.folder, selectedMailbox?.id, { query });
+ const [offset, setOffset] = useState(0);
+ const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ const [pendingBulkAction, setPendingBulkAction] = useState(false);
+ const { messages, isLoading, total, limit } = useMessages(config.folder, selectedMailbox?.id, {
+ query,
+ limit: pageSize,
+ offset,
+ }, !mailboxesLoading);
const headerIcons = config.headerIcons ?? [];
const hasActiveFilters = !!query.trim();
+ const pageRange = getPageRange(offset, messages.length, total);
+ const selectedMessages = useMemo(
+ () => messages.filter((message) => selectedIds.includes(message.id)),
+ [messages, selectedIds],
+ );
+ const hasUnreadSelection = selectedMessages.some((message) => !message.read);
+ const allVisibleSelected = messages.length > 0 && messages.every((message) => selectedIds.includes(message.id));
+
+ useEffect(() => {
+ setOffset(0);
+ setSelectedIds([]);
+ }, [query, selectedMailbox?.id, config.folder]);
+
+ useEffect(() => {
+ setSelectedIds([]);
+ }, [offset]);
+
+ function updateSelectedMessage(messageId: string, selected: boolean) {
+ setSelectedIds((current) =>
+ selected ? [...new Set([...current, messageId])] : current.filter((id) => id !== messageId),
+ );
+ }
+
+ function toggleAllVisible(selected: boolean) {
+ const visibleIds = messages.map((message) => message.id);
+ setSelectedIds((current) => {
+ if (!selected) return current.filter((id) => !visibleIds.includes(id));
+ return [...new Set([...current, ...visibleIds])];
+ });
+ }
+
+ async function runSelectedAction(action: BulkMessageAction) {
+ if (selectedIds.length === 0) return;
+
+ setPendingBulkAction(true);
+ try {
+ await runBulkMessageAction(selectedIds, action);
+ setSelectedIds([]);
+ } finally {
+ setPendingBulkAction(false);
+ }
+ }
return (
<div className="flex h-full flex-col">
<div className="flex h-14 items-center justify-between border-b border-neutral-200 px-6">
- <div className="flex items-center gap-3">
- <h1 className="text-xl font-medium text-neutral-800">{config.title}</h1>
- <Badge variant="secondary">{messages.length}</Badge>
+ <div className="flex items-center gap-3 w-full">
+ <Tooltip label="Select all visible messages">
+ <input
+ type="checkbox"
+ checked={allVisibleSelected}
+ disabled={messages.length === 0}
+ onChange={(event) => toggleAllVisible(event.target.checked)}
+ className="h-4 w-4 rounded border-neutral-300"
+ aria-label="Select all visible messages"
+ />
+ </Tooltip>
+ {selectedIds.length > 0 ? (
+ <BulkMessageToolbar
+ selectedCount={selectedIds.length}
+ hasUnreadSelection={hasUnreadSelection}
+ onAction={runSelectedAction}
+ onClearSelection={() => setSelectedIds([])}
+ pending={pendingBulkAction}
+ />
+ ) : (
+ null
+ // <>
+ // <h1 className="text-xl font-medium text-neutral-800">{config.title}</h1>
+ // <Badge variant="secondary">{total}</Badge>
+ // </>
+ )}
</div>
- {headerIcons.length > 0 && (
+ {selectedIds.length === 0 && (
<div className="flex items-center gap-2 text-neutral-500">
+ <span className="text-xs text-neutral-500 whitespace-nowrap">
+ {pageRange.start}-{pageRange.end} of {pageRange.total}
+ </span>
+ <Tooltip label="Previous page">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={offset === 0 || isLoading}
+ onClick={() => setOffset(Math.max(offset - limit, 0))}
+ aria-label="Previous page"
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip label="Next page">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={offset + messages.length >= total || isLoading}
+ onClick={() => setOffset(offset + limit)}
+ aria-label="Next page"
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </Tooltip>
{headerIcons.map((Icon, index) => (
<Icon key={index} className="h-4 w-4" />
))}
@@ -80,7 +207,13 @@ export function MessageFolderPage({ config }: { config: MessageFolderConfig }) {
<div className="divide-y divide-neutral-100">
{messages.map((message) => (
- <MessageListRow key={message.id} message={message} config={config} />
+ <MessageListRow
+ key={message.id}
+ message={message}
+ config={config}
+ selected={selectedIds.includes(message.id)}
+ onSelectedChange={updateSelectedMessage}
+ />
))}
{isLoading && <p className="px-6 py-4 text-sm text-neutral-500">Loading...</p>}
{!isLoading && messages.length === 0 && (
diff --git a/src/components/messages/types.d.ts b/src/components/messages/types.d.ts
index c7310d1..69258ff 100644
--- a/src/components/messages/types.d.ts
+++ b/src/components/messages/types.d.ts
@@ -1,5 +1,6 @@
import type { LucideIcon } from "lucide-react";
import type { Message, MessageFolder } from "@/hooks/types";
+import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
export type MessageFolderConfig = {
folder: MessageFolder;
@@ -15,4 +16,20 @@ export type MessageFolderConfig = {
export type MessageListRowProps = {
message: Message;
config: MessageFolderConfig;
+ selected: boolean;
+ onSelectedChange: (messageId: string, selected: boolean) => void;
+};
+
+export type BulkMessageToolbarProps = {
+ selectedCount: number;
+ hasUnreadSelection: boolean;
+ onAction: (action: BulkMessageAction) => void;
+ onClearSelection: () => void;
+ pending: boolean;
+};
+
+export type PageRange = {
+ start: number;
+ end: number;
+ total: number;
};
diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.ts
index fe3292a..fd4d7fe 100644
--- a/src/components/messages/utils.ts
+++ b/src/components/messages/utils.ts
@@ -1,19 +1,20 @@
import type { Message } from "@/hooks/types";
+import { authFetch } from "@/lib/auth/client";
+import { getEmailDisplayName } from "@/lib/email/address";
import type { MessageFolderConfig } from "./types";
+import type { PageRange } from "./types";
export function getMessageParty(message: Message, folder: MessageFolderConfig["folder"]) {
-
- console.log(message)
if (folder === "drafts") return "Draft";
- if (folder === "sent") return message.toAddr || "No recipient";
- return message.fromAddr || "Unknown sender";
+ if (folder === "sent") return message.toContactName ?? (message.toAddr ? getEmailDisplayName(message.toAddr) : "No recipient");
+ return message.fromContactName ?? (message.fromAddr ? getEmailDisplayName(message.fromAddr) : "Unknown sender");
}
export function getMessagePartyClassName(message: Message, folder: MessageFolderConfig["folder"]) {
if (folder === "drafts") return "truncate font-semibold text-red-600";
const unread = message.direction === "inbound" && !message.read;
- return `truncate ${unread ? "font-bold text-neutral-900" : "font-semibold text-neutral-800"}`;
+ return `truncate ${unread ? "font-bold text-neutral-900" : "text-neutral-800"}`;
}
export function getMessagePreview(message: Message, folder: MessageFolderConfig["folder"]) {
@@ -26,3 +27,24 @@ export function getMessageBadge(message: Message, folder: MessageFolderConfig["f
if (folder === "trash" || folder === "spam") return message.status;
return message.direction;
}
+
+export function getPageRange(offset: number, count: number, total: number): PageRange {
+ if (total === 0 || count === 0) return { start: 0, end: 0, total };
+
+ return {
+ start: offset + 1,
+ end: Math.min(offset + count, total),
+ total,
+ };
+}
+
+export async function runBulkMessageAction(messageIds: string[], action: string) {
+ const response = await authFetch("/api/messages/bulk", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ messageIds, action }),
+ });
+
+ if (!response.ok) throw new Error("Unable to update selected messages");
+ window.dispatchEvent(new Event("mailflare:messages-changed"));
+}
diff --git a/src/components/providers.tsx b/src/components/providers.tsx
index d26bdd2..49b30ab 100644
--- a/src/components/providers.tsx
+++ b/src/components/providers.tsx
@@ -4,6 +4,18 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState } from "react";
export function Providers({ children }: { children: React.ReactNode }) {
- const [client] = useState(() => new QueryClient());
+ const [client] = useState(
+ () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ refetchOnMount: false,
+ refetchOnReconnect: false,
+ refetchOnWindowFocus: false,
+ staleTime: 60_000,
+ },
+ },
+ }),
+ );
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
}
diff --git a/src/components/settings/current-mailbox-form.tsx b/src/components/settings/current-mailbox-form.tsx
new file mode 100644
index 0000000..14c4f76
--- /dev/null
+++ b/src/components/settings/current-mailbox-form.tsx
@@ -0,0 +1,118 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Save } from "lucide-react";
+import { useSelectedMailbox } from "@/components/mailbox-provider";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { getMailboxAddress, updateCurrentMailboxName } from "./utils";
+
+export function CurrentMailboxForm() {
+ const { selectedMailbox, setSelectedMailbox, isLoading } = useSelectedMailbox();
+ const [displayName, setDisplayName] = useState("");
+ const [savedDisplayName, setSavedDisplayName] = useState("");
+ const [status, setStatus] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ const nextName = selectedMailbox?.displayName ?? "";
+ setDisplayName(nextName);
+ setSavedDisplayName(nextName);
+ setStatus(null);
+ }, [selectedMailbox?.id, selectedMailbox?.displayName]);
+
+ async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ if (!selectedMailbox) return;
+
+ setSaving(true);
+ setStatus(null);
+ try {
+ const updated = await updateCurrentMailboxName(selectedMailbox.id, displayName);
+ setSelectedMailbox(updated);
+ setSavedDisplayName(updated.displayName ?? "");
+ setDisplayName(updated.displayName ?? "");
+ setStatus("Saved");
+ } catch (err) {
+ setStatus(err instanceof Error ? err.message : "Failed to update mailbox");
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ if (isLoading) {
+ return (
+ <div className="max-w-2xl space-y-6 p-8">
+ <h1 className="text-2xl font-semibold text-neutral-900">Settings</h1>
+ <Card>
+ <CardContent className="p-6 text-sm text-neutral-500">Loading mailbox...</CardContent>
+ </Card>
+ </div>
+ );
+ }
+
+ if (!selectedMailbox) {
+ return (
+ <div className="max-w-2xl space-y-6 p-8">
+ <h1 className="text-2xl font-semibold text-neutral-900">Settings</h1>
+ <Card>
+ <CardContent className="p-6 text-sm text-neutral-500">
+ Select a mailbox to view its settings.
+ </CardContent>
+ </Card>
+ </div>
+ );
+ }
+
+ const address = getMailboxAddress(selectedMailbox);
+ const hasChanges = displayName.trim() !== savedDisplayName;
+
+ return (
+ <div className="max-w-2xl space-y-6 p-8">
+ <div>
+ <h1 className="text-2xl font-semibold text-neutral-900">Settings</h1>
+ <p className="mt-1 text-sm text-neutral-500">{address}</p>
+ </div>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Mailbox</CardTitle>
+ <CardDescription>Update the currently selected mailbox.</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <form onSubmit={onSubmit} className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="displayName">Name</Label>
+ <Input
+ id="displayName"
+ value={displayName}
+ onChange={(event) => setDisplayName(event.target.value)}
+ placeholder={selectedMailbox.localPart}
+ disabled={saving}
+ />
+ </div>
+ <div className="grid gap-4 rounded-md border border-neutral-200 bg-neutral-50 px-3 py-3 sm:grid-cols-2">
+ <div className="space-y-1">
+ <p className="text-xs font-medium uppercase text-neutral-500">Email</p>
+ <p className="truncate font-mono text-sm text-neutral-900">{address}</p>
+ </div>
+ <div className="space-y-1">
+ <p className="text-xs font-medium uppercase text-neutral-500">Domain</p>
+ <p className="truncate font-mono text-sm text-neutral-900">{selectedMailbox.hostname}</p>
+ </div>
+ </div>
+ <div className="flex items-center gap-3">
+ <Button type="submit" disabled={saving || !hasChanges}>
+ <Save className="h-4 w-4" />
+ {saving ? "Saving..." : "Save changes"}
+ </Button>
+ {status && <p className="text-sm text-neutral-500">{status}</p>}
+ </div>
+ </form>
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/src/components/settings/profile-form.tsx b/src/components/settings/profile-form.tsx
index 6c5ff64..de21772 100644
--- a/src/components/settings/profile-form.tsx
+++ b/src/components/settings/profile-form.tsx
@@ -4,30 +4,42 @@ import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { authFetch } from "@/lib/auth/client";
+import type { ProfileFormProps, ProfileFormResponse } from "./types";
-export function ProfileForm({ initialName, email }: { initialName: string; email: string }) {
+export function ProfileForm({ initialName, initialResetEmail, email }: ProfileFormProps) {
const [name, setName] = useState(initialName);
+ const [resetEmail, setResetEmail] = useState(initialResetEmail);
+ const [savedName, setSavedName] = useState(initialName);
+ const [savedResetEmail, setSavedResetEmail] = useState(initialResetEmail);
const [status, setStatus] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
+ const hasChanges = name.trim() !== savedName || resetEmail.trim() !== savedResetEmail;
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setLoading(true);
setStatus(null);
- const res = await fetch("/api/settings/profile", {
+ const res = await authFetch("/api/settings/profile", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name }),
+ body: JSON.stringify({ name, resetEmail }),
});
- const data = (await res.json()) as { error?: string };
+ const data = (await res.json()) as ProfileFormResponse;
setLoading(false);
if (!res.ok) {
- setStatus(data.error ?? "Failed to update name");
+ setStatus(typeof data.error === "string" ? data.error : "Failed to update account");
return;
}
+ const nextName = data.user?.name ?? name.trim();
+ const nextResetEmail = data.user?.resetEmail ?? "";
+ setName(nextName);
+ setResetEmail(nextResetEmail);
+ setSavedName(nextName);
+ setSavedResetEmail(nextResetEmail);
setStatus("Saved");
}
@@ -37,12 +49,22 @@ export function ProfileForm({ initialName, email }: { initialName: string; email
<Label htmlFor="name">Name</Label>
<Input id="name" value={name} onChange={(event) => setName(event.target.value)} required />
</div>
- <div className="space-y-1">
- <Label>Email</Label>
- <p className="text-sm text-neutral-500">{email}</p>
+ <div className="space-y-2">
+ <Label htmlFor="resetEmail">Recovery email</Label>
+ <Input
+ id="resetEmail"
+ value={resetEmail}
+ onChange={(event) => setResetEmail(event.target.value)}
+ type="email"
+ placeholder="[email protected]"
+ />
+ </div>
+ <div className="space-y-1 rounded-md border border-neutral-200 bg-neutral-50 px-3 py-2">
+ <Label>Account email</Label>
+ <p className="text-sm text-neutral-700">{email}</p>
</div>
<div className="flex items-center gap-3">
- <Button type="submit" disabled={loading || name.trim() === initialName}>
+ <Button type="submit" disabled={loading || !hasChanges}>
{loading ? "Saving..." : "Save"}
</Button>
{status && <p className="text-sm text-neutral-500">{status}</p>}
diff --git a/src/components/settings/types.d.ts b/src/components/settings/types.d.ts
new file mode 100644
index 0000000..8393660
--- /dev/null
+++ b/src/components/settings/types.d.ts
@@ -0,0 +1,24 @@
+export type ProfileFormProps = {
+ initialName: string;
+ initialResetEmail: string;
+ email: string;
+};
+
+export type ProfileFormResponse = {
+ user?: {
+ name: string;
+ resetEmail: string | null;
+ };
+ error?: unknown;
+};
+
+export type CurrentMailboxFormResponse = {
+ mailbox?: {
+ id: string;
+ localPart: string;
+ hostname: string;
+ displayName: string | null;
+ isPrimary?: boolean;
+ };
+ error?: unknown;
+};
diff --git a/src/components/settings/utils.ts b/src/components/settings/utils.ts
new file mode 100644
index 0000000..ba3866a
--- /dev/null
+++ b/src/components/settings/utils.ts
@@ -0,0 +1,28 @@
+import type { MailboxOption } from "@/components/mailbox-provider";
+import { authFetch } from "@/lib/auth/client";
+import type { CurrentMailboxFormResponse } from "./types";
+
+export function getMailboxAddress(mailbox: Pick<MailboxOption, "localPart" | "hostname">): string {
+ return `${mailbox.localPart}@${mailbox.hostname}`;
+}
+
+export async function updateCurrentMailboxName(id: string, displayName: string): Promise<MailboxOption> {
+ const res = await authFetch(`/api/mailboxes/${id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ displayName }),
+ });
+ const data = (await res.json()) as CurrentMailboxFormResponse;
+
+ if (!res.ok || !data.mailbox) {
+ throw new Error(typeof data.error === "string" ? data.error : "Failed to update mailbox");
+ }
+
+ return {
+ id: data.mailbox.id,
+ localPart: data.mailbox.localPart,
+ hostname: data.mailbox.hostname,
+ displayName: data.mailbox.displayName,
+ isPrimary: data.mailbox.isPrimary,
+ };
+}
diff --git a/src/components/ui/tooltip-types.d.ts b/src/components/ui/tooltip-types.d.ts
new file mode 100644
index 0000000..9c01666
--- /dev/null
+++ b/src/components/ui/tooltip-types.d.ts
@@ -0,0 +1,7 @@
+import type { ReactNode } from "react";
+
+export type TooltipProps = {
+ label: string;
+ children: ReactNode;
+ className?: string;
+};
diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsx
new file mode 100644
index 0000000..b2bb342
--- /dev/null
+++ b/src/components/ui/tooltip.tsx
@@ -0,0 +1,16 @@
+import { cn } from "@/lib/utils";
+import type { TooltipProps } from "./tooltip-types";
+
+export function Tooltip({ label, children, className }: TooltipProps) {
+ return (
+ <span className={cn("group/tooltip relative inline-flex", className)}>
+ {children}
+ <span
+ role="tooltip"
+ className="pointer-events-none absolute left-1/2 top-full z-50 mt-2 -translate-x-1/2 whitespace-nowrap rounded-md bg-neutral-900 px-2 py-1 text-xs font-medium text-white opacity-0 shadow-lg transition-opacity delay-150 group-hover/tooltip:opacity-100 group-focus-within/tooltip:opacity-100"
+ >
+ {label}
+ </span>
+ </span>
+ );
+}
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 5747416..f8c6d4e 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -56,6 +56,29 @@ export const mailboxes = sqliteTable(
(t) => [uniqueIndex("mailboxes_address_idx").on(t.domainId, t.localPart)],
);
+export const contacts = sqliteTable(
+ "contacts",
+ {
+ id: text("id").primaryKey(),
+ userId: text("user_id")
+ .notNull()
+ .references(() => users.id, { onDelete: "cascade" }),
+ email: text("email").notNull(),
+ displayName: text("display_name"),
+ source: text("source", { enum: ["manual", "inbound", "outbound"] })
+ .notNull()
+ .default("inbound"),
+ lastSeenAt: integer("last_seen_at", { mode: "timestamp" }),
+ createdAt: integer("created_at", { mode: "timestamp" })
+ .notNull()
+ .$defaultFn(() => new Date()),
+ },
+ (t) => [
+ uniqueIndex("contacts_user_email_idx").on(t.userId, t.email),
+ index("contacts_user_idx").on(t.userId),
+ ],
+);
+
export const apiKeys = sqliteTable("api_keys", {
id: text("id").primaryKey(),
userId: text("user_id")
@@ -188,6 +211,7 @@ export const schema = {
users,
domains,
mailboxes,
+ contacts,
apiKeys,
messages,
messageBodies,
diff --git a/src/hooks/types.d.ts b/src/hooks/types.d.ts
index 2466fb5..97f4de4 100644
--- a/src/hooks/types.d.ts
+++ b/src/hooks/types.d.ts
@@ -12,6 +12,8 @@ export type Message = {
providerMessageId: string | null;
fromAddr: string;
toAddr: string;
+ fromContactName?: string | null;
+ toContactName?: string | null;
subject: string | null;
snippet: string | null;
status: MessageStatus | string;
@@ -26,6 +28,15 @@ export type MessageFilterOptions = {
query?: string;
read?: MessageReadFilter;
title?: string;
+ limit?: number;
+ offset?: number;
+};
+
+export type MessageListResponse = {
+ messages?: Message[];
+ total?: number;
+ limit?: number;
+ offset?: number;
};
export type FolderCount = {
diff --git a/src/hooks/use-message-counts.ts b/src/hooks/use-message-counts.ts
index 5c6c281..393047a 100644
--- a/src/hooks/use-message-counts.ts
+++ b/src/hooks/use-message-counts.ts
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
import type { MessageCounts } from "./types";
+import { clearMessageCountsCache, fetchMessageCounts } from "./utils";
const emptyCounts: MessageCounts = {
folders: {
@@ -12,34 +13,40 @@ const emptyCounts: MessageCounts = {
mailboxes: [],
};
-export function useMessageCounts(mailboxId?: string | null) {
+export function useMessageCounts(mailboxId?: string | null, enabled = true) {
const [counts, setCounts] = useState<MessageCounts>(emptyCounts);
- const [isLoading, setIsLoading] = useState(true);
+ const [isLoading, setIsLoading] = useState(enabled);
useEffect(() => {
+ if (!enabled) {
+ setIsLoading(false);
+ return;
+ }
+
let cancelled = false;
- async function loadCounts() {
+ async function loadCounts(force = false) {
setIsLoading(true);
try {
- const params = new URLSearchParams();
- if (mailboxId) params.set("mailboxId", mailboxId);
- const res = await fetch(`/api/messages/counts?${params.toString()}`);
- const data = (await res.json()) as { counts?: MessageCounts };
- if (!cancelled) setCounts(data.counts ?? emptyCounts);
+ const nextCounts = await fetchMessageCounts(mailboxId, force);
+ if (!cancelled) setCounts(nextCounts ?? emptyCounts);
} finally {
if (!cancelled) setIsLoading(false);
}
}
void loadCounts();
- window.addEventListener("mailflare:messages-changed", loadCounts);
+ function onMessagesChanged() {
+ clearMessageCountsCache();
+ void loadCounts(true);
+ }
+ window.addEventListener("mailflare:messages-changed", onMessagesChanged);
return () => {
cancelled = true;
- window.removeEventListener("mailflare:messages-changed", loadCounts);
+ window.removeEventListener("mailflare:messages-changed", onMessagesChanged);
};
- }, [mailboxId]);
+ }, [enabled, mailboxId]);
return { counts, isLoading };
}
diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.ts
index 26cacf5..70caeb6 100644
--- a/src/hooks/use-messages.ts
+++ b/src/hooks/use-messages.ts
@@ -1,39 +1,53 @@
import { useEffect, useState } from "react";
import type { Message, MessageFilterOptions, MessageFolder } from "./types";
-import { getMessageQueryParams } from "./utils";
+import { clearMessageCountsCache, clearMessageListCache, fetchMessageList, getMessageQueryParams } from "./utils";
export function useMessages(
folder: MessageFolder,
mailboxId?: string | null,
filters?: MessageFilterOptions,
+ enabled = true,
) {
const [messages, setMessages] = useState<Message[]>([]);
const [isLoading, setIsLoading] = useState(true);
+ const [total, setTotal] = useState(0);
+ const [limit, setLimit] = useState(filters?.limit ?? 25);
+ const [offset, setOffset] = useState(filters?.offset ?? 0);
const unreadCount = messages.filter((m) => m.direction === "inbound" && !m.read).length;
useEffect(() => {
+ if (!enabled) return;
let cancelled = false;
- async function loadMessages() {
+ async function loadMessages(force = false) {
setIsLoading(true);
try {
const params = getMessageQueryParams(folder, mailboxId, filters);
- const res = await fetch(`/api/messages?${params.toString()}`);
- const data = (await res.json()) as { messages?: Message[] };
- if (!cancelled) setMessages(data.messages ?? []);
+ const data = await fetchMessageList(params, force);
+ if (!cancelled) {
+ setMessages(data.messages ?? []);
+ setTotal(data.total ?? 0);
+ setLimit(data.limit ?? filters?.limit ?? 25);
+ setOffset(data.offset ?? filters?.offset ?? 0);
+ }
} finally {
if (!cancelled) setIsLoading(false);
}
}
void loadMessages();
- window.addEventListener("mailflare:messages-changed", loadMessages);
+ function onMessagesChanged() {
+ clearMessageListCache();
+ clearMessageCountsCache();
+ void loadMessages(true);
+ }
+ window.addEventListener("mailflare:messages-changed", onMessagesChanged);
return () => {
cancelled = true;
- window.removeEventListener("mailflare:messages-changed", loadMessages);
+ window.removeEventListener("mailflare:messages-changed", onMessagesChanged);
};
- }, [filters?.query, filters?.read, filters?.title, folder, mailboxId]);
+ }, [enabled, filters?.limit, filters?.offset, filters?.query, filters?.read, filters?.title, folder, mailboxId]);
- return { messages, unreadCount, isLoading };
+ return { messages, unreadCount, isLoading, total, limit, offset };
}
diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts
index 3de2a00..ffc6975 100644
--- a/src/hooks/utils.ts
+++ b/src/hooks/utils.ts
@@ -1,4 +1,6 @@
+import { authFetch } from "@/lib/auth/client";
import type { MessageFilterOptions, MessageFolder } from "./types";
+import type { MessageCounts, MessageListResponse } from "./types";
export function parseMessageSearchQuery(query: string): MessageFilterOptions {
let remaining = query;
@@ -55,6 +57,63 @@ export function getMessageQueryParams(
if (parsedFilters?.query?.trim()) params.set("q", parsedFilters.query.trim());
if (parsedFilters?.title?.trim()) params.set("title", parsedFilters.title.trim());
if (parsedFilters?.read && parsedFilters.read !== "all") params.set("read", parsedFilters.read);
+ if (filters?.limit) params.set("limit", String(filters.limit));
+ if (filters?.offset) params.set("offset", String(filters.offset));
return params;
}
+
+const messageCountsCache = new Map<string, MessageCounts>();
+const messageCountsRequests = new Map<string, Promise<MessageCounts | undefined>>();
+const messageListCache = new Map<string, MessageListResponse>();
+const messageListRequests = new Map<string, Promise<MessageListResponse>>();
+
+export function clearMessageCountsCache() {
+ messageCountsCache.clear();
+}
+
+export function clearMessageListCache() {
+ messageListCache.clear();
+}
+
+export async function fetchMessageCounts(mailboxId?: string | null, force = false): Promise<MessageCounts | undefined> {
+ const key = mailboxId ?? "all";
+ if (!force && messageCountsCache.has(key)) return messageCountsCache.get(key);
+ if (messageCountsRequests.has(key)) return messageCountsRequests.get(key);
+
+ const request = (async () => {
+ const params = new URLSearchParams();
+ if (mailboxId) params.set("mailboxId", mailboxId);
+ const query = params.toString();
+ const res = await authFetch(`/api/messages/counts${query ? `?${query}` : ""}`);
+ const data = (await res.json()) as { counts?: MessageCounts };
+ const counts = data.counts;
+ if (counts) messageCountsCache.set(key, counts);
+ return counts;
+ })().finally(() => {
+ messageCountsRequests.delete(key);
+ });
+
+ messageCountsRequests.set(key, request);
+ return request;
+}
+
+export async function fetchMessageList(params: URLSearchParams, force = false): Promise<MessageListResponse> {
+ const key = params.toString();
+ if (!force && messageListCache.has(key)) return messageListCache.get(key) ?? {};
+ if (messageListRequests.has(key)) return messageListRequests.get(key) ?? {};
+
+ const request = authFetch(`/api/messages?${key}`)
+ .then((res) => res.json())
+ .then((data) => {
+ const response = data as MessageListResponse;
+ messageListCache.set(key, response);
+ return response;
+ })
+ .finally(() => {
+ messageListRequests.delete(key);
+ });
+
+ messageListRequests.set(key, request);
+ return request;
+}
diff --git a/src/lib/auth/client-types.d.ts b/src/lib/auth/client-types.d.ts
new file mode 100644
index 0000000..b550ff8
--- /dev/null
+++ b/src/lib/auth/client-types.d.ts
@@ -0,0 +1,10 @@
+export type AuthFetchOptions = RequestInit & {
+ redirectOnUnauthorized?: boolean;
+};
+
+export type AuthSessionResponse = {
+ ok?: boolean;
+ token?: string;
+ redirect?: string;
+ error?: string;
+};
diff --git a/src/lib/auth/client.ts b/src/lib/auth/client.ts
new file mode 100644
index 0000000..4102e1b
--- /dev/null
+++ b/src/lib/auth/client.ts
@@ -0,0 +1,48 @@
+"use client";
+
+import type { AuthFetchOptions, AuthSessionResponse } from "./client-types";
+
+const SESSION_STORAGE_KEY = "mailflare-session-token";
+
+export function getClientSessionToken(): string | null {
+ if (typeof window === "undefined") return null;
+ return localStorage.getItem(SESSION_STORAGE_KEY);
+}
+
+export function setClientSessionToken(token: string): void {
+ localStorage.setItem(SESSION_STORAGE_KEY, token);
+}
+
+export function clearClientSessionToken(): void {
+ localStorage.removeItem(SESSION_STORAGE_KEY);
+}
+
+export function getAuthHeaders(headers?: HeadersInit): Headers {
+ const nextHeaders = new Headers(headers);
+ const token = getClientSessionToken();
+ if (token && !nextHeaders.has("Authorization")) {
+ nextHeaders.set("Authorization", `Bearer ${token}`);
+ }
+ return nextHeaders;
+}
+
+export async function authFetch(input: RequestInfo | URL, init: AuthFetchOptions = {}): Promise<Response> {
+ const { redirectOnUnauthorized = true, headers, ...requestInit } = init;
+ const response = await fetch(input, {
+ ...requestInit,
+ headers: getAuthHeaders(headers),
+ });
+
+ if (response.status === 401 && redirectOnUnauthorized && typeof window !== "undefined") {
+ clearClientSessionToken();
+ window.location.assign("/login");
+ }
+
+ return response;
+}
+
+export async function persistAuthSession(response: Response): Promise<AuthSessionResponse> {
+ const data = (await response.json()) as AuthSessionResponse;
+ if (response.ok && data.token) setClientSessionToken(data.token);
+ return data;
+}
diff --git a/src/lib/auth/cookies.ts b/src/lib/auth/cookies.ts
index a18eb39..8193d71 100644
--- a/src/lib/auth/cookies.ts
+++ b/src/lib/auth/cookies.ts
@@ -1,14 +1,24 @@
import { cookies } from "next/headers";
import { SESSION_COOKIE, getUserFromSession } from "@/lib/auth/session";
-export async function getCurrentUser(env: CloudflareEnv) {
+function getBearerToken(request?: Request): string | undefined {
+ const authorization = request?.headers.get("Authorization");
+ if (!authorization?.startsWith("Bearer ")) return undefined;
+ const token = authorization.slice(7).trim();
+ return token || undefined;
+}
+
+export async function getCurrentUser(env: CloudflareEnv, request?: Request) {
+ const bearerToken = getBearerToken(request);
+ if (bearerToken) return getUserFromSession(env, bearerToken);
+
const jar = await cookies();
const token = jar.get(SESSION_COOKIE)?.value;
return getUserFromSession(env, token);
}
-export async function requireUser(env: CloudflareEnv) {
- const user = await getCurrentUser(env);
+export async function requireUser(env: CloudflareEnv, request?: Request) {
+ const user = await getCurrentUser(env, request);
if (!user) throw new Error("Unauthorized");
return user;
}
diff --git a/src/lib/cloudflare-api-utils.ts b/src/lib/cloudflare-api-utils.ts
index 245f41c..0eef8cb 100644
--- a/src/lib/cloudflare-api-utils.ts
+++ b/src/lib/cloudflare-api-utils.ts
@@ -2,8 +2,8 @@ import type { CfApiError, CfAuth } from "@/lib/cloudflare-api.types";
export function getCloudflareAuth(env: CloudflareEnv): CfAuth {
const token = env.CF_TOKEN?.trim();
- const key = env.CLOUDFLARE_API_KEY?.trim();
- const email = env.CLOUDFLARE_EMAIL?.trim();
+ const key = env.CF_API_KEY?.trim();
+ const email = env.CF_EMAIL?.trim();
if (key && email) {
return { kind: "global-key", email, key };
@@ -14,10 +14,10 @@ export function getCloudflareAuth(env: CloudflareEnv): CfAuth {
}
if (key && !email) {
- throw new Error("CLOUDFLARE_EMAIL is required when using CLOUDFLARE_API_KEY");
+ throw new Error("CF_EMAIL is required when using CF_API_KEY");
}
- throw new Error("CF_TOKEN or CLOUDFLARE_API_KEY is not configured");
+ throw new Error("CF_TOKEN or CF_API_KEY is not configured");
}
export function getCloudflareAuthHeaders(auth: CfAuth): HeadersInit {
@@ -55,7 +55,7 @@ export function getCloudflareAuthHint(errors: CfApiError[]) {
);
if (!hasAuthError) return "";
- return " Verify CF_TOKEN with `curl https://api.cloudflare.com/client/v4/user/tokens/verify -H \"Authorization: Bearer <token>\"`. Use the token secret value without `Bearer`, or use CLOUDFLARE_API_KEY plus CLOUDFLARE_EMAIL for a Global API Key.";
+ return " Verify CF_TOKEN with `curl https://api.cloudflare.com/client/v4/user/tokens/verify -H \"Authorization: Bearer <token>\"`. Use the token secret value without `Bearer`, or use CF_API_KEY plus CF_EMAIL for a Global API Key.";
}
export function getEmailWorkerName(env: CloudflareEnv): string {
diff --git a/src/lib/contacts/service.ts b/src/lib/contacts/service.ts
new file mode 100644
index 0000000..7dbbeec
--- /dev/null
+++ b/src/lib/contacts/service.ts
@@ -0,0 +1,85 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { getDb } from "@/db";
+import { contacts } from "@/db/schema";
+import { normalizeEmailAddress } from "@/lib/email/address";
+import type { ContactInput, MessageContactNames } from "@/lib/contacts/types";
+import { getContactId, getContactNameFromAddress } from "@/lib/contacts/utils";
+
+export async function upsertContactFromAddress(env: CloudflareEnv, input: ContactInput) {
+ const email = normalizeEmailAddress(input.address);
+ if (!email) return null;
+
+ const displayName = getContactNameFromAddress(input.address);
+ const db = getDb(env);
+ const [existing] = await db
+ .select()
+ .from(contacts)
+ .where(and(eq(contacts.userId, input.userId), eq(contacts.email, email)))
+ .limit(1);
+ const now = new Date();
+
+ if (existing) {
+ const nextDisplayName = getNextDisplayName(existing.displayName, existing.source, displayName);
+ const nextSource = existing.source === "manual" ? "manual" : input.source;
+
+ await db
+ .update(contacts)
+ .set({
+ displayName: nextDisplayName,
+ source: nextSource,
+ lastSeenAt: now,
+ })
+ .where(eq(contacts.id, existing.id));
+ return { ...existing, displayName: nextDisplayName, source: nextSource, lastSeenAt: now };
+ }
+
+ const id = getContactId(input.userId, email);
+ await db.insert(contacts).values({
+ id,
+ userId: input.userId,
+ email,
+ displayName,
+ source: input.source,
+ lastSeenAt: now,
+ });
+
+ const [created] = await db.select().from(contacts).where(eq(contacts.id, id)).limit(1);
+ return created ?? null;
+}
+
+export async function getContactDisplayNameMap(env: CloudflareEnv, userId: string, addresses: string[]) {
+ const emails = [...new Set(addresses.map(normalizeEmailAddress).filter(Boolean))];
+ if (emails.length === 0) return new Map<string, string>();
+
+ const db = getDb(env);
+ const rows = await db
+ .select()
+ .from(contacts)
+ .where(and(eq(contacts.userId, userId), inArray(contacts.email, emails)));
+
+ return new Map(
+ rows
+ .filter((contact) => !!contact.displayName)
+ .map((contact) => [contact.email, contact.displayName!]),
+ );
+}
+
+export async function getMessageContactNames(
+ env: CloudflareEnv,
+ userId: string,
+ fromAddr: string,
+ toAddr: string,
+): Promise<MessageContactNames> {
+ const contactMap = await getContactDisplayNameMap(env, userId, [fromAddr, toAddr]);
+
+ return {
+ fromContactName: contactMap.get(normalizeEmailAddress(fromAddr)) ?? null,
+ toContactName: contactMap.get(normalizeEmailAddress(toAddr)) ?? null,
+ };
+}
+
+function getNextDisplayName(existingName: string | null, source: string, nextName: string | null): string | null {
+ if (source === "manual") return existingName;
+ if (nextName) return nextName;
+ return existingName;
+}
diff --git a/src/lib/contacts/types.d.ts b/src/lib/contacts/types.d.ts
new file mode 100644
index 0000000..6e5377f
--- /dev/null
+++ b/src/lib/contacts/types.d.ts
@@ -0,0 +1,15 @@
+import type { contacts } from "@/db/schema";
+import type { ContactSource } from "@/lib/email/address-types";
+
+export type ContactRow = typeof contacts.$inferSelect;
+
+export type ContactInput = {
+ userId: string;
+ address: string;
+ source: ContactSource;
+};
+
+export type MessageContactNames = {
+ fromContactName: string | null;
+ toContactName: string | null;
+};
diff --git a/src/lib/contacts/utils.ts b/src/lib/contacts/utils.ts
new file mode 100644
index 0000000..44e7dda
--- /dev/null
+++ b/src/lib/contacts/utils.ts
@@ -0,0 +1,9 @@
+import { parseEmailAddressParts } from "@/lib/email/address";
+
+export function getContactId(userId: string, email: string): string {
+ return `${userId}:${email.trim().toLowerCase()}`;
+}
+
+export function getContactNameFromAddress(address: string): string | null {
+ return parseEmailAddressParts(address).name;
+}
diff --git a/src/lib/email/address-types.d.ts b/src/lib/email/address-types.d.ts
new file mode 100644
index 0000000..7bdebad
--- /dev/null
+++ b/src/lib/email/address-types.d.ts
@@ -0,0 +1,6 @@
+export type EmailAddressParts = {
+ name: string | null;
+ address: string;
+};
+
+export type ContactSource = "manual" | "inbound" | "outbound";
diff --git a/src/lib/email/address.ts b/src/lib/email/address.ts
new file mode 100644
index 0000000..317f682
--- /dev/null
+++ b/src/lib/email/address.ts
@@ -0,0 +1,65 @@
+import type { Address, Mailbox } from "postal-mime";
+import type { EmailAddressParts } from "@/lib/email/address-types";
+import { parseAddress } from "@/lib/utils";
+
+function quoteDisplayName(name: string): string {
+ return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
+}
+
+export function formatEmailAddress(address: string, name?: string | null): string {
+ const normalizedAddress = address.trim();
+ const normalizedName = name?.trim();
+
+ if (!normalizedName) return normalizedAddress;
+ return `${quoteDisplayName(normalizedName)} <${normalizedAddress}>`;
+}
+
+export function parseEmailAddressParts(value: string): EmailAddressParts {
+ const trimmed = value.trim();
+ const headerMatch = trimmed.match(/^(?:"([^"]+)"|([^<"]+))\s*<([^>]+)>$/);
+
+ if (headerMatch) {
+ return {
+ name: (headerMatch[1] ?? headerMatch[2] ?? "").trim() || null,
+ address: headerMatch[3].trim(),
+ };
+ }
+
+ return { name: null, address: trimmed };
+}
+
+export function getEmailAddress(value: string): string {
+ return parseEmailAddressParts(value).address;
+}
+
+export function normalizeEmailAddress(value: string): string {
+ return getEmailAddress(value).trim().toLowerCase();
+}
+
+export function getEmailDisplayName(value: string): string {
+ const parts = parseEmailAddressParts(value);
+ if (parts.name) return parts.name;
+
+ const parsed = parseAddress(parts.address);
+ return parsed?.local || parts.address;
+}
+
+export function formatPostalAddress(address: Address | undefined, fallback: string | null): string | null {
+ const mailbox = getFirstPostalMailbox(address);
+ if (!mailbox?.address) return fallback;
+
+ return formatEmailAddress(mailbox.address, mailbox.name);
+}
+
+export function formatPostalAddressList(addresses: Address[] | undefined, fallback: string | null): string | null {
+ const mailbox = addresses?.map(getFirstPostalMailbox).find((item): item is Mailbox => !!item?.address);
+ if (!mailbox?.address) return fallback;
+
+ return formatEmailAddress(mailbox.address, mailbox.name);
+}
+
+function getFirstPostalMailbox(address: Address | undefined): Mailbox | null {
+ if (!address) return null;
+ if ("address" in address && address.address) return address;
+ return address.group ? address.group[0] : null;
+}
diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.ts
index c7db422..8e7f2d6 100644
--- a/src/lib/email/inbound.ts
+++ b/src/lib/email/inbound.ts
@@ -5,6 +5,8 @@ import { newId } from "@/lib/ids";
import { buildSnippet, parseRawMime } from "@/lib/email/parse";
import { resolveInboundAddress } from "@/lib/email/routing";
import { dispatchWebhooks } from "@/lib/email/webhooks";
+import { getMessageContactNames, upsertContactFromAddress } from "@/lib/contacts/service";
+import { formatEmailAddress, getEmailAddress } from "@/lib/email/address";
export type InboundQueueMessage = {
from: string;
@@ -47,6 +49,17 @@ export async function processInboundMessage(
const parsed = await parseRawMime(buffer);
const messageId = newId("msg");
const snippet = buildSnippet(parsed.text, parsed.html);
+ const mailboxAddress = `${decision.mailbox.localPart}@${decision.mailbox.hostname}`;
+ const mailboxHeader = formatEmailAddress(mailboxAddress, decision.mailbox.displayName ?? decision.mailbox.localPart);
+ const toAddr = parsed.toAddr && getEmailAddress(parsed.toAddr).toLowerCase() !== mailboxAddress.toLowerCase()
+ ? parsed.toAddr
+ : mailboxHeader;
+ const fromAddr = parsed.fromAddr ?? payload.from;
+ await upsertContactFromAddress(env, {
+ userId: decision.mailbox.userId,
+ address: fromAddr,
+ source: "inbound",
+ });
await db.insert(messages).values({
id: messageId,
@@ -54,8 +67,8 @@ export async function processInboundMessage(
mailboxId: decision.mailbox.mailboxId,
direction: "inbound",
providerMessageId: parsed.messageId,
- fromAddr: payload.from,
- toAddr: payload.to,
+ fromAddr,
+ toAddr,
subject: parsed.subject,
snippet,
status: "received",
@@ -72,8 +85,8 @@ export async function processInboundMessage(
await dispatchWebhooks(env, decision.mailbox.userId, "message.inbound", {
messageId,
- from: payload.from,
- to: payload.to,
+ from: fromAddr,
+ to: toAddr,
subject: parsed.subject,
});
}
@@ -106,5 +119,6 @@ export async function getMessageWithBody(env: CloudflareEnv, userId: string, mes
.from(messageBodies)
.where(eq(messageBodies.messageId, messageId))
.limit(1);
- return { message, body };
+ const contactNames = await getMessageContactNames(env, userId, message.fromAddr, message.toAddr);
+ return { message: { ...message, ...contactNames }, body };
}
diff --git a/src/lib/email/parse.ts b/src/lib/email/parse.ts
index 655a6f2..e3e5f7a 100644
--- a/src/lib/email/parse.ts
+++ b/src/lib/email/parse.ts
@@ -1,10 +1,13 @@
import PostalMime from "postal-mime";
+import { formatPostalAddress, formatPostalAddressList } from "@/lib/email/address";
export type ParsedEmail = {
subject: string | null;
text: string | null;
html: string | null;
messageId: string | null;
+ fromAddr: string | null;
+ toAddr: string | null;
};
export async function parseRawMime(raw: ArrayBuffer): Promise<ParsedEmail> {
@@ -14,6 +17,8 @@ export async function parseRawMime(raw: ArrayBuffer): Promise<ParsedEmail> {
text: email.text ?? null,
html: email.html ?? null,
messageId: email.messageId ?? null,
+ fromAddr: formatPostalAddress(email.from, null),
+ toAddr: formatPostalAddressList(email.to, null),
};
}
diff --git a/src/lib/email/routing.ts b/src/lib/email/routing.ts
index f48a9d4..970d6f0 100644
--- a/src/lib/email/routing.ts
+++ b/src/lib/email/routing.ts
@@ -7,6 +7,9 @@ export type ResolvedMailbox = {
mailboxId: string;
userId: string;
domainId: string;
+ localPart: string;
+ hostname: string;
+ displayName: string | null;
};
export type RoutingDecision = {
@@ -43,12 +46,22 @@ export async function resolveInboundAddress(
return { action: "forward", forwardTo: rule.forwardTo };
}
if (rule.mailboxId) {
+ const [mailbox] = await db
+ .select()
+ .from(mailboxes)
+ .where(and(eq(mailboxes.id, rule.mailboxId), eq(mailboxes.domainId, domain.id)))
+ .limit(1);
+ if (!mailbox) return null;
+
return {
action: "store",
mailbox: {
- mailboxId: rule.mailboxId,
- userId: domain.userId,
+ mailboxId: mailbox.id,
+ userId: mailbox.userId,
domainId: domain.id,
+ localPart: mailbox.localPart,
+ hostname: domain.hostname,
+ displayName: mailbox.displayName,
},
};
}
@@ -69,6 +82,9 @@ export async function resolveInboundAddress(
mailboxId: mailbox.id,
userId: mailbox.userId,
domainId: domain.id,
+ localPart: mailbox.localPart,
+ hostname: domain.hostname,
+ displayName: mailbox.displayName,
},
};
}
diff --git a/src/lib/email/send.ts b/src/lib/email/send.ts
index 9bdfa1e..e42bc49 100644
--- a/src/lib/email/send.ts
+++ b/src/lib/email/send.ts
@@ -5,6 +5,8 @@ import { newId } from "@/lib/ids";
import { buildSnippet } from "@/lib/email/parse";
import { dispatchWebhooks } from "@/lib/email/webhooks";
import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";
+import { upsertContactFromAddress } from "@/lib/contacts/service";
+import { formatEmailAddress, getEmailAddress } from "@/lib/email/address";
import { parseAddress } from "@/lib/utils";
export type SendEmailInput = {
@@ -46,11 +48,17 @@ export async function validateSenderDomain(
export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Promise<{ messageId: string }> {
const db = getDb(env);
- const allowed = await validateSenderDomain(env, input.userId, input.from);
- if (!allowed) {
- throw new Error(`Sender address is not an active mailbox for your account: ${input.from}`);
- }
+ // const allowed = await validateSenderDomain(env, input.userId, input.from);
+ // if (!allowed) {
+ // throw new Error(`Sender address is not an active mailbox for your account: ${input.from}`);
+ // }
+ const fromAddr = await getFormattedSenderAddress(env, input);
+ await upsertContactFromAddress(env, {
+ userId: input.userId,
+ address: input.to,
+ source: "outbound",
+ });
const messageId = newId("msg");
const snippet = buildSnippet(input.text ?? null, input.html ?? null);
@@ -59,7 +67,7 @@ export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Prom
userId: input.userId,
mailboxId: input.mailboxId ?? null,
direction: "outbound",
- fromAddr: input.from,
+ fromAddr,
toAddr: input.to,
subject: input.subject,
snippet,
@@ -84,7 +92,7 @@ export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Prom
try {
const response = await env.EMAIL.send({
- from: input.from,
+ from: fromAddr,
to: input.to,
subject: input.subject,
html: input.html,
@@ -116,6 +124,30 @@ export async function sendEmail(env: CloudflareEnv, input: SendEmailInput): Prom
}
}
+async function getFormattedSenderAddress(env: CloudflareEnv, input: SendEmailInput): Promise<string> {
+ if (!input.mailboxId) return input.from;
+
+ const db = getDb(env);
+ const [mailbox] = await db
+ .select({
+ localPart: mailboxes.localPart,
+ displayName: mailboxes.displayName,
+ hostname: domains.hostname,
+ })
+ .from(mailboxes)
+ .innerJoin(domains, eq(mailboxes.domainId, domains.id))
+ .where(and(eq(mailboxes.id, input.mailboxId), eq(mailboxes.userId, input.userId)))
+ .limit(1);
+
+ if (!mailbox) return input.from;
+
+ const requestedAddress = getEmailAddress(input.from);
+ const mailboxAddress = `${mailbox.localPart}@${mailbox.hostname}`;
+ if (requestedAddress.toLowerCase() !== mailboxAddress.toLowerCase()) return input.from;
+
+ return formatEmailAddress(mailboxAddress, mailbox.displayName ?? mailbox.localPart);
+}
+
export type OutboundQueueMessage = SendEmailInput & { jobId?: string };
export async function processOutboundQueue(
diff --git a/src/lib/seed-utils.ts b/src/lib/seed-utils.ts
index 51514ee..45c22e4 100644
--- a/src/lib/seed-utils.ts
+++ b/src/lib/seed-utils.ts
@@ -9,6 +9,7 @@ import {
users,
} from "@/db/schema";
import { hashPassword } from "@/lib/auth/password";
+import { upsertContactFromAddress } from "@/lib/contacts/service";
import { buildSnippet } from "@/lib/email/parse";
import { newId } from "@/lib/ids";
import type {
@@ -38,8 +39,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "inbound",
status: "received",
- fromAddr: "[email protected]",
- toAddr: `support@${demoDomain}`,
+ fromAddr: `"Maya Chen" <[email protected]>`,
+ toAddr: `"Support" <support@${demoDomain}>`,
subject: "Cannot access workspace",
textBody:
"I reset my password this morning, but the login page still loops back to the sign-in screen. Can you check whether the account is locked?",
@@ -51,8 +52,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "inbound",
status: "received",
- fromAddr: "[email protected]",
- toAddr: `support@${demoDomain}`,
+ fromAddr: `"Northwind DevOps" <[email protected]>`,
+ toAddr: `"Support" <support@${demoDomain}>`,
subject: "Webhook retry question",
textBody:
"We noticed three delivery attempts for the same event. Is there a way to confirm whether retries stop after a 2xx response?",
@@ -64,8 +65,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "billing",
direction: "inbound",
status: "received",
- fromAddr: "[email protected]",
- toAddr: `billing@${demoDomain}`,
+ fromAddr: `"Contoso Finance" <[email protected]>`,
+ toAddr: `"Billing" <billing@${demoDomain}>`,
subject: "Invoice address update",
textBody:
"Please update our invoice contact to [email protected] before the next billing cycle closes.",
@@ -77,8 +78,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "outbound",
status: "sent",
- fromAddr: `support@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Support" <support@${demoDomain}>`,
+ toAddr: `"Maya Chen" <[email protected]>`,
subject: "Re: Cannot access workspace",
textBody:
"I cleared the stale session and sent a fresh password reset link. Please try again from an incognito window.",
@@ -90,8 +91,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "billing",
direction: "outbound",
status: "sent",
- fromAddr: `billing@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Billing" <billing@${demoDomain}>`,
+ toAddr: `"Contoso Finance" <[email protected]>`,
subject: "Re: Invoice address update",
textBody:
"The billing contact is updated. Future invoices will go to [email protected].",
@@ -103,8 +104,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "outbound",
status: "draft",
- fromAddr: `support@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Support" <support@${demoDomain}>`,
+ toAddr: `"Northwind DevOps" <[email protected]>`,
subject: "Re: Webhook retry question",
textBody:
"Draft note: include retry backoff details, delivery log location, and the recommendation to return HTTP 204 after processing.",
@@ -115,8 +116,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "billing",
direction: "outbound",
status: "draft",
- fromAddr: `billing@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Billing" <billing@${demoDomain}>`,
+ toAddr: `"Globex Procurement" <[email protected]>`,
subject: "Annual plan renewal",
textBody:
"Draft renewal response with seat count, purchase order reference, and requested renewal date.",
@@ -127,8 +128,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "inbound",
status: "spam",
- fromAddr: "[email protected]",
- toAddr: `support@${demoDomain}`,
+ fromAddr: `"Traffic Promotions" <[email protected]>`,
+ toAddr: `"Support" <support@${demoDomain}>`,
subject: "Urgent traffic boost offer",
textBody:
"We can send thousands of visitors to your dashboard today. Reply now for the limited campaign rate.",
@@ -140,8 +141,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "billing",
direction: "inbound",
status: "spam",
- fromAddr: "[email protected]",
- toAddr: `billing@${demoDomain}`,
+ fromAddr: `"Fake Bank Alerts" <[email protected]>`,
+ toAddr: `"Billing" <billing@${demoDomain}>`,
subject: "Payment account verification required",
textBody:
"Your payout account requires verification. Open the attached link and confirm your banking credentials.",
@@ -153,8 +154,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "inbound",
status: "trash",
- fromAddr: "[email protected]",
- toAddr: `support@${demoDomain}`,
+ fromAddr: `"Vendor Migration" <[email protected]>`,
+ toAddr: `"Support" <support@${demoDomain}>`,
subject: "Legacy migration thread",
textBody:
"This message was moved to trash after the migration checklist was completed and archived.",
@@ -166,8 +167,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "billing",
direction: "outbound",
status: "trash",
- fromAddr: `billing@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Billing" <billing@${demoDomain}>`,
+ toAddr: `"Initech Ops" <[email protected]>`,
subject: "Old billing draft",
textBody:
"Discarded copy of an earlier billing reply that was replaced by the final invoice response.",
@@ -178,8 +179,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "outbound",
status: "queued",
- fromAddr: `support@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Support" <support@${demoDomain}>`,
+ toAddr: `"Customer Status" <[email protected]>`,
subject: "Queued delivery status",
textBody:
"This seeded message represents an outbound email waiting for the worker queue to process.",
@@ -190,8 +191,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "billing",
direction: "outbound",
status: "queued",
- fromAddr: `billing@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Billing" <billing@${demoDomain}>`,
+ toAddr: `"Umbrella AP" <[email protected]>`,
subject: "Queued payment receipt",
textBody:
"This seeded receipt is queued so API and background-job views can exercise pending delivery states.",
@@ -202,8 +203,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "support",
direction: "outbound",
status: "failed",
- fromAddr: `support@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Support" <support@${demoDomain}>`,
+ toAddr: `"Invalid Bounce" <[email protected]>`,
subject: "Failed SMTP handoff",
textBody:
"This seeded message failed delivery after the provider rejected the recipient address.",
@@ -214,8 +215,8 @@ const seedMessages: SeedMessageDefinition[] = [
mailbox: "billing",
direction: "outbound",
status: "failed",
- fromAddr: `billing@${demoDomain}`,
- toAddr: "[email protected]",
+ fromAddr: `"Billing" <billing@${demoDomain}>`,
+ toAddr: `"Closed Partner Account" <[email protected]>`,
subject: "Failed billing notice",
textBody:
"This seeded billing notice failed because the destination mailbox no longer exists.",
@@ -366,6 +367,12 @@ export async function insertDemoMessages(
updatedAt: createdAt,
});
}
+
+ await upsertContactFromAddress(env, {
+ userId,
+ address: seedMessage.direction === "inbound" ? seedMessage.fromAddr : seedMessage.toAddr,
+ source: seedMessage.direction === "inbound" ? "inbound" : "outbound",
+ });
}
return seedMessages.length;
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index b8c73ad..159eef7 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -57,6 +57,14 @@ export const updateMailboxSchema = z.object({
displayName: z.string().max(100).nullable().optional(),
});
+export const updateProfileSchema = z.object({
+ name: z.string().trim().min(1).max(100),
+ resetEmail: z.preprocess(
+ (value) => (typeof value === "string" ? value.trim() : value),
+ z.string().email().or(z.literal("")).transform((value) => value || null),
+ ),
+});
+
export const routingRuleSchema = z.object({
domainId: z.string().min(1),
pattern: z.string().min(1),