Email for professionals and teams
push v0.2.0
Hieu Nguyen (Jack)2d919420d513
diff --git a/README.md b/README.mdindex 97ce802..e07432a 100644--- a/README.md+++ b/README.md@@ -134,6 +134,11 @@ Required setup values:- `CF_AID` — optional unless your token can access multiple accounts.- `CF_EMAIL_WORKER_NAME` — must match the deployed Worker name. If the one-click deploy flow asks for a different Worker name, enter that same value here.+Activate a purchased Pro or Team key from **Admin → Licenses**. Mailflare sends the key directly to+Paymug and stores only a one-way key hash with the activation state. Without an active license,+Mailflare uses the original app name, icon, and favicon and custom branding remains unavailable.+Apply all D1 migrations before activating a license.+### Database backup workflow bindingManual and scheduled database backups require the `DATABASE_BACKUP_WORKFLOW` binding declared indiff --git a/drizzle/migrations/0012_add_app_settings.sql b/drizzle/migrations/0012_add_app_settings.sqlnew file mode 100644index 0000000..1ebf6de--- /dev/null+++ b/drizzle/migrations/0012_add_app_settings.sql@@ -0,0 +1,9 @@+CREATE TABLE `app_settings` (+ `id` text PRIMARY KEY NOT NULL,+ `app_name` text DEFAULT 'Mailflare' NOT NULL,+ `icon_key` text,+ `updated_at` integer NOT NULL+);++INSERT INTO `app_settings` (`id`, `app_name`, `updated_at`)+VALUES ('default', 'Mailflare', unixepoch());diff --git a/drizzle/migrations/0013_add_license_settings.sql b/drizzle/migrations/0013_add_license_settings.sqlnew file mode 100644index 0000000..407c733--- /dev/null+++ b/drizzle/migrations/0013_add_license_settings.sql@@ -0,0 +1,14 @@+CREATE TABLE `license_settings` (+ `id` text PRIMARY KEY NOT NULL,+ `instance_id` text NOT NULL,+ `instance_url` text,+ `license_key_hash` text,+ `plan` text DEFAULT 'community' NOT NULL,+ `state` text DEFAULT 'inactive' NOT NULL,+ `features` text DEFAULT '[]' NOT NULL,+ `activated_at` integer,+ `validated_at` integer,+ `updated_at` integer NOT NULL+);++CREATE UNIQUE INDEX `license_settings_instance_id_unique` ON `license_settings` (`instance_id`);diff --git a/drizzle/migrations/0014_add_account_permissions.sql b/drizzle/migrations/0014_add_account_permissions.sqlnew file mode 100644index 0000000..6fc1e19--- /dev/null+++ b/drizzle/migrations/0014_add_account_permissions.sql@@ -0,0 +1 @@+ALTER TABLE `users` ADD `can_manage_mailboxes` integer DEFAULT false NOT NULL;diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.jsonindex 75e4878..699e6f5 100644--- a/drizzle/migrations/meta/_journal.json+++ b/drizzle/migrations/meta/_journal.json@@ -85,6 +85,27 @@"when": 1787529600000,"tag": "0011_add_folder_colors","breakpoints": true+ },+ {+ "idx": 12,+ "version": "6",+ "when": 1787616000000,+ "tag": "0012_add_app_settings",+ "breakpoints": true+ },+ {+ "idx": 13,+ "version": "6",+ "when": 1787702400000,+ "tag": "0013_add_license_settings",+ "breakpoints": true+ },+ {+ "idx": 14,+ "version": "6",+ "when": 1787792400000,+ "tag": "0014_add_account_permissions",+ "breakpoints": true}]}diff --git a/package.json b/package.jsonindex abd450b..0a336c0 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "mailflare",- "version": "0.1.11",+ "version": "0.2.0","private": true,"scripts": {"dev": "next dev",diff --git a/src/app/(admin)/accounts/[id]/page.tsx b/src/app/(admin)/accounts/[id]/page.tsxindex 14d8052..9ac30a1 100644--- a/src/app/(admin)/accounts/[id]/page.tsx+++ b/src/app/(admin)/accounts/[id]/page.tsx@@ -1,5 +1,90 @@-import { redirect } from "next/navigation";+"use client";-export default function AccountDetailPage() {- redirect("/admin");+import { useEffect, useState } from "react";+import { useParams } from "next/navigation";+import { Plus, Trash2, Upload } from "lucide-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 { ManagedAccount, ManagedDomain, ManagedMailbox } from "./types";++export default function AccountDetailsPage() {+ const { id } = useParams<{ id: string }>();+ const [account, setAccount] = useState<ManagedAccount | null>(null);+ const [mailboxes, setMailboxes] = useState<ManagedMailbox[]>([]);+ const [domains, setDomains] = useState<ManagedDomain[]>([]);+ const [localPart, setLocalPart] = useState("");+ const [domainId, setDomainId] = useState("");+ const [saving, setSaving] = useState(false);+ const [message, setMessage] = useState<string | null>(null);+ const [avatarVersion, setAvatarVersion] = useState(0);++ async function load() {+ const [accountResponse, mailboxResponse, domainResponse] = await Promise.all([+ authFetch(`/api/accounts/${id}`),+ authFetch(`/api/accounts/${id}/mailboxes`),+ authFetch("/api/domains"),+ ]);+ const accountData = (await accountResponse.json()) as { account?: ManagedAccount; error?: string };+ if (!accountResponse.ok || !accountData.account) throw new Error(accountData.error ?? "Unable to load account");+ setAccount(accountData.account);+ setMailboxes(((await mailboxResponse.json()) as { mailboxes?: ManagedMailbox[] }).mailboxes ?? []);+ const nextDomains = ((await domainResponse.json()) as { domains?: ManagedDomain[] }).domains ?? [];+ setDomains(nextDomains);+ setDomainId((current) => current || nextDomains[0]?.id || "");+ }++ useEffect(() => { void load().catch((error) => setMessage(error instanceof Error ? error.message : "Unable to load account")); }, [id]);++ async function saveAccount() {+ if (!account) return;+ setSaving(true);+ const response = await authFetch(`/api/accounts/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: account.name, role: account.role, disabled: account.disabled, canManageMailboxes: account.canManageMailboxes }) });+ const data = (await response.json()) as { error?: string };+ setMessage(response.ok ? "Account updated" : data.error ?? "Unable to update account");+ setSaving(false);+ }++ async function uploadAvatar(file: File | undefined) {+ if (!file) return;+ const form = new FormData();+ form.set("file", file);+ const response = await authFetch(`/api/accounts/${id}/avatar`, { method: "POST", body: form });+ if (response.ok) {+ setAccount((current) => current ? { ...current, hasAvatar: true } : current);+ setAvatarVersion(Date.now());+ }+ }++ async function addMailbox(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault();+ if (!account) return;+ const response = await authFetch("/api/mailboxes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ownerUserId: account.id, domainId, localPart, displayName: account.name }) });+ const data = (await response.json()) as { error?: string };+ if (!response.ok) return setMessage(data.error ?? "Unable to add inbox");+ setLocalPart("");+ await load();+ }++ async function removeMailbox(mailboxId: string) {+ const response = await authFetch(`/api/mailboxes/${mailboxId}`, { method: "DELETE" });+ if (!response.ok) return setMessage("Unable to remove inbox");+ await load();+ }++ if (!account) return <p className="text-sm text-neutral-500">{message ?? "Loading account..."}</p>;+ return <div className="space-y-6">+ <div><h1 className="text-3xl font-medium">{account.name}</h1><p className="mt-2 text-sm text-neutral-500">{account.email}</p></div>+ <section className="space-y-5 rounded-3xl bg-white p-6">+ <div className="flex items-center gap-4"><span className="relative flex h-16 w-16 items-center justify-center overflow-hidden rounded-full bg-blue-100 text-xl font-semibold text-blue-700">{account.name.charAt(0).toUpperCase()}{account.hasAvatar && <img src={`/api/accounts/${id}/avatar?v=${avatarVersion}`} alt="" className="absolute inset-0 h-full w-full object-cover" />}</span><Label className="cursor-pointer"><span className="inline-flex h-9 items-center gap-2 rounded-md border border-neutral-200 px-3 text-sm"><Upload className="h-4 w-4" />Change avatar</span><input type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="sr-only" onChange={(event) => void uploadAvatar(event.target.files?.[0])} /></Label></div>+ <div className="space-y-2"><Label htmlFor="account-name">Name</Label><Input id="account-name" value={account.name} onChange={(event) => setAccount({ ...account, name: event.target.value })} /></div>+ <div className="space-y-2"><Label htmlFor="account-role">Role</Label><select id="account-role" value={account.role} onChange={(event) => setAccount({ ...account, role: event.target.value as "admin" | "user" })} className="h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm"><option value="user">User</option><option value="admin">Admin</option></select></div>+ <label className="flex items-center gap-3 text-sm"><input type="checkbox" checked={account.canManageMailboxes} onChange={(event) => setAccount({ ...account, canManageMailboxes: event.target.checked })} />Allow this account to add and remove inboxes</label>+ <label className="flex items-center gap-3 text-sm"><input type="checkbox" checked={!account.disabled} onChange={(event) => setAccount({ ...account, disabled: !event.target.checked })} />Account enabled</label>+ <Button onClick={() => void saveAccount()} disabled={saving}>{saving ? "Saving..." : "Save changes"}</Button>+ </section>+ <section className="space-y-4 rounded-3xl bg-white p-6"><div><h2 className="font-semibold">Inboxes</h2><p className="text-sm text-neutral-500">Mailboxes owned by this account.</p></div><div className="space-y-2">{mailboxes.map((mailbox) => <div key={mailbox.id} className="flex items-center justify-between rounded-2xl bg-neutral-50 px-4 py-3"><span><span className="block font-medium">{mailbox.displayName || mailbox.localPart}</span><span className="block text-sm text-neutral-500">{mailbox.localPart}@{mailbox.hostname}</span></span><Button type="button" variant="ghost" size="icon" onClick={() => void removeMailbox(mailbox.id)} aria-label="Remove inbox"><Trash2 className="h-4 w-4" /></Button></div>)}</div><form onSubmit={addMailbox} className="flex gap-2"><Input value={localPart} onChange={(event) => setLocalPart(event.target.value)} placeholder="inbox" required /><select value={domainId} onChange={(event) => setDomainId(event.target.value)} className="rounded-md border border-neutral-200 bg-white px-3 text-sm">{domains.map((domain) => <option key={domain.id} value={domain.id}>@{domain.hostname}</option>)}</select><Button type="submit"><Plus className="h-4 w-4" />Add inbox</Button></form></section>+ {message && <p className="text-sm text-neutral-500">{message}</p>}+ </div>;}diff --git a/src/app/(admin)/accounts/[id]/types.d.ts b/src/app/(admin)/accounts/[id]/types.d.tsindex 71df371..5feb95a 100644--- a/src/app/(admin)/accounts/[id]/types.d.ts+++ b/src/app/(admin)/accounts/[id]/types.d.ts@@ -1,43 +1,19 @@-export type AccountDetail = {+export type ManagedAccount = {id: string;email: string;name: string;- resetEmail: string | null;role: "admin" | "user";- disabled?: boolean;- createdAt: string;+ disabled: boolean;+ canManageMailboxes: boolean;+ hasAvatar: boolean;};-export type DomainOption = {+export type ManagedMailbox = {id: string;- hostname: string;-};--export type AccountMailboxItem = {- id: string;- domainId: string;localPart: string;- hostname: string;displayName: string | null;- type: "personal" | "shared";- createdAt: string;-};--export type AccountMailboxAccessItem = {- mailboxId: string;- localPart: string;+ domainId: string;hostname: string;- displayName: string | null;- permission: "read_only" | "send_as" | "send_on_behalf" | "full_access" | null;};-export type AccountMailboxAccessResponse = {- account?: AccountDetail;- access?: AccountMailboxAccessItem[];- error?: string;-};--export type AccountDetailResponse = {- account?: AccountDetail;- error?: string;-};+export type ManagedDomain = { id: string; hostname: string };diff --git a/src/app/(admin)/accounts/page.tsx b/src/app/(admin)/accounts/page.tsxindex d6c2b10..17dc5d2 100644--- a/src/app/(admin)/accounts/page.tsx+++ b/src/app/(admin)/accounts/page.tsx@@ -1,5 +1,79 @@-import { redirect } from "next/navigation";+"use client";++import { useEffect, useState } from "react";+import Link from "next/link";+import { Plus } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { authFetch } from "@/lib/auth/client";+import type { Account, AccountResponse, Domain } from "./types";export default function AccountsPage() {- redirect("/admin");+ const [accounts, setAccounts] = useState<Account[]>([]);+ const [domains, setDomains] = useState<Domain[]>([]);+ const [username, setUsername] = useState("");+ const [domainId, setDomainId] = useState("");+ const [role, setRole] = useState<"admin" | "user">("user");+ const [password, setPassword] = useState("");+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [createOpen, setCreateOpen] = useState(false);+ const [message, setMessage] = useState<string | null>(null);+ const [teamRequired, setTeamRequired] = useState(false);++ async function loadAccounts() {+ const response = await authFetch("/api/accounts");+ const data = (await response.json()) as AccountResponse;+ if (!response.ok) throw new Error(data.error ?? "Unable to load accounts");+ setAccounts(data.accounts ?? []);+ }++ useEffect(() => {+ loadAccounts().then(async () => {+ const response = await authFetch("/api/domains");+ const data = (await response.json()) as { domains?: Domain[]; error?: string };+ if (!response.ok) throw new Error(data.error ?? "Unable to load domains");+ setDomains(data.domains ?? []);+ setDomainId(data.domains?.[0]?.id ?? "");+ }).catch((error) => {+ const text = error instanceof Error ? error.message : "Unable to load accounts";+ setTeamRequired(/team license/i.test(text));+ setMessage(text);+ }).finally(() => setLoading(false));+ }, []);++ async function createAccount(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault();+ setSaving(true);+ setMessage(null);+ try {+ const response = await authFetch("/api/accounts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, domainId, password, role }) });+ const data = (await response.json()) as AccountResponse;+ if (!response.ok) throw new Error(data.error ?? "Unable to create account");+ setUsername("");+ setPassword("");+ setCreateOpen(false);+ await loadAccounts();+ } catch (error) {+ setMessage(error instanceof Error ? error.message : "Unable to create account");+ } finally {+ setSaving(false);+ }+ }++ return <div className="space-y-6">+ <div className="flex items-center justify-between gap-4"><div><h1 className="text-3xl font-medium text-neutral-900">Accounts</h1><p className="mt-2 text-sm text-neutral-500">Manage Team accounts and their inboxes.</p></div>{!teamRequired && <Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4" />New account</Button>}</div>+ {teamRequired ? <div className="rounded-3xl bg-white p-6"><h2 className="font-semibold">Team license required</h2><p className="mt-2 text-sm text-neutral-600">Adding user accounts is available with a Team license.</p><Button asChild className="mt-4"><Link href="/licenses">View licenses</Link></Button></div> : <div className="grid gap-3">+ {loading && <p className="text-sm text-neutral-500">Loading...</p>}+ {accounts.map((account) => <Link key={account.id} href={`/accounts/${account.id}`} className="flex items-center gap-4 rounded-3xl bg-white p-5 transition-colors hover:bg-blue-50/40"><span className="relative flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-full bg-blue-100 font-semibold text-blue-700">{account.name.charAt(0).toUpperCase()}{account.hasAvatar && <img src={`/api/accounts/${account.id}/avatar`} alt="" className="absolute inset-0 h-full w-full object-cover" />}</span><span className="min-w-0"><span className="flex items-center gap-2"><span className="truncate font-semibold text-neutral-900">{account.name}</span><span className="rounded-full bg-neutral-100 px-2 py-0.5 text-xs font-medium capitalize text-neutral-600">{account.role}</span></span><span className="block truncate text-sm text-neutral-500">{account.email}</span></span></Link>)}+ </div>}+ <Dialog open={createOpen} onOpenChange={setCreateOpen}><DialogContent><DialogHeader><DialogTitle>Add user account</DialogTitle><DialogDescription>The user can sign in with this email and password.</DialogDescription></DialogHeader><form onSubmit={createAccount} className="space-y-4">+ <div className="space-y-2"><Label htmlFor="account-username">Email</Label><div className="flex h-10 overflow-hidden rounded-md border border-neutral-200 bg-white"><Input id="account-username" value={username} onChange={(event) => setUsername(event.target.value)} placeholder="username" className="min-w-0 flex-1 rounded-none border-0 shadow-none" required /><span className="flex items-center text-sm text-neutral-400">@</span><select aria-label="Domain" value={domainId} onChange={(event) => setDomainId(event.target.value)} className="max-w-[55%] bg-transparent px-3 text-sm" required><option value="">Select domain</option>{domains.map((domain) => <option key={domain.id} value={domain.id}>{domain.hostname}</option>)}</select></div></div>+ <div className="space-y-2"><Label htmlFor="account-password">Password</Label><Input id="account-password" type="password" minLength={8} value={password} onChange={(event) => setPassword(event.target.value)} required /></div>+ <div className="space-y-2"><Label htmlFor="account-role">Role</Label><select id="account-role" value={role} onChange={(event) => setRole(event.target.value as "admin" | "user")} className="h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm"><option value="user">User</option><option value="admin">Admin</option></select></div>+ {message && <p className="text-sm text-red-600">{message}</p>}<Button type="submit" disabled={saving || !domainId}>{saving ? "Creating..." : "Create account"}</Button>+ </form></DialogContent></Dialog>+ </div>;}diff --git a/src/app/(admin)/accounts/types.d.ts b/src/app/(admin)/accounts/types.d.tsindex e3e0a00..b7840e3 100644--- a/src/app/(admin)/accounts/types.d.ts+++ b/src/app/(admin)/accounts/types.d.ts@@ -10,8 +10,16 @@ export type Account = {resetEmail: string | null;role: "admin" | "user";disabled?: boolean;+ hasAvatar?: boolean;+ canManageMailboxes?: boolean;createdAt: string;mailboxId?: string | null;localPart?: string | null;hostname?: string | null;};++export type AccountResponse = {+ accounts?: Account[];+ account?: Account;+ error?: string;+};diff --git a/src/app/(admin)/admin/page.tsx b/src/app/(admin)/admin/page.tsxindex 1859c63..90c6ad6 100644--- a/src/app/(admin)/admin/page.tsx+++ b/src/app/(admin)/admin/page.tsx@@ -1,5 +1,5 @@import Link from "next/link";-import { Globe2, KeyRound, Mail, Settings, Webhook } from "lucide-react";+import { BadgeDollarSign, Globe2, KeyRound, Mail, Palette, Settings, Users, Webhook } from "lucide-react";import { AdminUpdateCard } from "@/components/admin-update-card";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";@@ -16,6 +16,24 @@ const sections = [description: "Add Cloudflare domains and inspect DNS state.",icon: Globe2,},+ {+ href: "/branding",+ title: "Branding",+ description: "Customize the app name, icon, and favicon.",+ icon: Palette,+ },+ {+ href: "/licenses",+ title: "Licenses",+ description: "Compare Pro and Team perpetual licenses.",+ icon: BadgeDollarSign,+ },+ {+ href: "/accounts",+ title: "Accounts",+ description: "Add and manage user accounts with a Team license.",+ icon: Users,+ },// {// href: "/api-keys",// title: "API Keys",diff --git a/src/app/(admin)/branding/page.tsx b/src/app/(admin)/branding/page.tsxnew file mode 100644index 0000000..d10fef5--- /dev/null+++ b/src/app/(admin)/branding/page.tsx@@ -0,0 +1,100 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { ExternalLink, ImagePlus, LockKeyhole, Palette } from "lucide-react";+import { useBranding } from "@/components/branding-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 { BRANDING_ICON_ACCEPT, saveBranding } from "./utils";++export default function BrandingPage() {+ const branding = useBranding();+ const [appName, setAppName] = useState(branding.appName);+ const [icon, setIcon] = useState<File | null>(null);+ const [preview, setPreview] = useState<string | null>(null);+ const [status, setStatus] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ setAppName(branding.appName);+ }, [branding.appName]);++ if (!branding.canCustomizeBranding) {+ return (+ <div className="space-y-6">+ <div>+ <h1 className="text-3xl font-medium text-neutral-900">Branding</h1>+ <p className="mt-2 text-sm text-neutral-500">Custom branding is available with a Pro or Team license.</p>+ </div>+ <Card className="rounded-3xl border-0 bg-white p-6">+ <CardHeader className="py-0">+ <CardTitle className="flex items-center gap-2"><LockKeyhole className="h-5 w-5" />License required</CardTitle>+ <CardDescription>This installation continues to use the original Mailflare name, app icon, and favicon.</CardDescription>+ </CardHeader>+ <CardContent className="flex flex-col gap-3 pt-6 sm:flex-row">+ <Button asChild><a href="https://app.paymug.co/buy/mailflare-pro" target="_blank" rel="noopener noreferrer">Buy Pro · $19 <ExternalLink className="h-4 w-4" /></a></Button>+ <Button asChild variant="outline"><a href="https://app.paymug.co/buy/mailflare-team" target="_blank" rel="noopener noreferrer">Buy Team · from $249 <ExternalLink className="h-4 w-4" /></a></Button>+ </CardContent>+ </Card>+ </div>+ );+ }++ function pickIcon(file: File | null) {+ setIcon(file);+ if (preview) URL.revokeObjectURL(preview);+ setPreview(file ? URL.createObjectURL(file) : null);+ }++ async function submit(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault();+ setSaving(true);+ setStatus(null);+ try {+ await saveBranding(appName.trim(), icon);+ await branding.refreshBranding();+ setIcon(null);+ setStatus("Branding updated");+ } catch (error) {+ setStatus(error instanceof Error ? error.message : "Unable to save branding");+ } finally {+ setSaving(false);+ }+ }++ return (+ <div className="space-y-6">+ <div>+ <h1 className="text-3xl font-medium text-neutral-900">Branding</h1>+ <p className="mt-2 text-sm text-neutral-500">Customize the app identity shown to everyone using this installation.</p>+ </div>+ <Card className="rounded-3xl border-0 bg-white p-6">+ <CardHeader className="py-0">+ <CardTitle className="flex items-center gap-2"><Palette className="h-5 w-5" />App identity</CardTitle>+ <CardDescription>The icon is also used as the browser favicon.</CardDescription>+ </CardHeader>+ <CardContent className="pt-6">+ <form onSubmit={submit} className="space-y-6">+ <div className="space-y-2">+ <Label htmlFor="appName">App name</Label>+ <Input id="appName" value={appName} maxLength={60} onChange={(event) => setAppName(event.target.value)} required />+ </div>+ <div className="space-y-2">+ <Label>App icon</Label>+ <input ref={inputRef} type="file" accept={BRANDING_ICON_ACCEPT} className="hidden" onChange={(event) => pickIcon(event.target.files?.[0] ?? null)} />+ <button type="button" onClick={() => inputRef.current?.click()} className="flex items-center gap-4 rounded-2xl border border-dashed border-neutral-300 p-4 text-left hover:bg-neutral-50">+ <img src={preview ?? branding.iconUrl} alt="App icon preview" className="h-16 w-16 rounded-2xl object-cover" />+ <span className="text-sm text-neutral-600"><ImagePlus className="mb-1 h-5 w-5" />Choose PNG, JPEG, WebP, or GIF<br /><span className="text-xs text-neutral-400">Maximum 2 MB</span></span>+ </button>+ </div>+ {status && <p className="text-sm text-neutral-600">{status}</p>}+ <Button type="submit" disabled={saving || !appName.trim()}>{saving ? "Saving..." : "Save branding"}</Button>+ </form>+ </CardContent>+ </Card>+ </div>+ );+}diff --git a/src/app/(admin)/branding/types.d.ts b/src/app/(admin)/branding/types.d.tsnew file mode 100644index 0000000..f4e5c09--- /dev/null+++ b/src/app/(admin)/branding/types.d.ts@@ -0,0 +1,5 @@+export type BrandingFormResponse = {+ appName?: string;+ hasCustomIcon?: boolean;+ error?: string;+};diff --git a/src/app/(admin)/branding/utils.ts b/src/app/(admin)/branding/utils.tsnew file mode 100644index 0000000..076adba--- /dev/null+++ b/src/app/(admin)/branding/utils.ts@@ -0,0 +1,14 @@+import { authFetch } from "@/lib/auth/client";+import type { BrandingFormResponse } from "./types";++export const BRANDING_ICON_ACCEPT = "image/png,image/jpeg,image/webp,image/gif";++export async function saveBranding(appName: string, icon: File | null): Promise<BrandingFormResponse> {+ const form = new FormData();+ form.set("appName", appName);+ if (icon) form.set("icon", icon, icon.name);+ const response = await authFetch("/api/branding", { method: "PUT", body: form });+ const data = (await response.json()) as BrandingFormResponse;+ if (!response.ok) throw new Error(data.error ?? "Unable to save branding");+ return data;+}diff --git a/src/app/(admin)/layout.tsx b/src/app/(admin)/layout.tsxindex 23efc6f..a0ef10e 100644--- a/src/app/(admin)/layout.tsx+++ b/src/app/(admin)/layout.tsx@@ -7,6 +7,7 @@ import { ComposeProvider } from "@/components/compose/compose-context";import { FloatingComposer } from "@/components/compose/floating-composer";import { MailboxProvider } from "@/components/mailbox-provider";import { MailboxSelector } from "@/components/mailbox-selector";+import { LicenseIndicator } from "@/components/license-indicator";import { AdminNav } from "@/components/admin-nav";export default function DashboardLayout({@@ -23,7 +24,8 @@ export default function DashboardLayout({<AdminNav /></aside><div className="flex min-h-0 min-w-0 flex-col">- <span className="fixed top-6 right-6">+ <span className="fixed top-6 right-6 flex items-center gap-2">+ <LicenseIndicator /><MailboxSelector /></span><main className="min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain px-6 py-10 scrollbar-gutter-stable lg:px-12">diff --git a/src/app/(admin)/licenses/license-activation.tsx b/src/app/(admin)/licenses/license-activation.tsxnew file mode 100644index 0000000..4e3afc0--- /dev/null+++ b/src/app/(admin)/licenses/license-activation.tsx@@ -0,0 +1,159 @@+"use client";++import { useEffect, useState } from "react";+import { CheckCircle2 } from "lucide-react";+import { Badge } from "@/components/ui/badge";+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 { Skeleton } from "@/components/ui/skeleton";+import type { LicenseStatus } from "@/lib/licenses/types";+import type { ActivatableLicensePlan, LicenseAction } from "./types";+import { formatLicensePlan, loadLicenseStatus, runLicenseAction } from "./utils";++export function LicenseActivation() {+ const [license, setLicense] = useState<LicenseStatus | null>(null);+ const [licenseKey, setLicenseKey] = useState("");+ const [selectedPlan, setSelectedPlan] = useState<ActivatableLicensePlan>("pro");+ const [loading, setLoading] = useState(true);+ const [action, setAction] = useState<LicenseAction | null>(null);+ const [status, setStatus] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ loadLicenseStatus()+ .then((nextLicense) => {+ if (!cancelled) setLicense(nextLicense);+ })+ .catch((error) => {+ if (!cancelled) setStatus(error instanceof Error ? error.message : "Unable to load license status");+ })+ .finally(() => {+ if (!cancelled) setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ async function submit(nextAction: LicenseAction) {+ if (nextAction !== "deactivate" && !licenseKey.trim()) {+ setStatus("Enter your license key");+ return;+ }+ if (nextAction === "deactivate" && !window.confirm("Deactivate this license on this installation?")) return;++ setAction(nextAction);+ setStatus(null);+ try {+ const nextLicense = await runLicenseAction(nextAction, licenseKey, nextAction === "activate" ? selectedPlan : undefined);+ setLicense(nextLicense);+ setLicenseKey("");+ setStatus(nextAction === "deactivate" ? "License deactivated" : nextAction === "validate" ? "License validated" : "License activated");+ } catch (error) {+ setStatus(error instanceof Error ? error.message : "License request failed");+ try {+ setLicense(await loadLicenseStatus());+ } catch {+ // Keep the last visible status when the local status endpoint is unavailable.+ }+ } finally {+ setAction(null);+ }+ }++ if (loading) return <Skeleton className="h-64 w-full rounded-3xl" />;++ const hasActivation = !!license?.activatedAt && license.state !== "deactivated";++ if (license?.active) {+ return (+ <Card className="rounded-3xl border-0 bg-white px-6">+ <CardContent className="flex items-start gap-4 py-8">+ <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-green-100 text-green-700">+ <CheckCircle2 className="h-6 w-6" />+ </span>+ <div className="min-w-0 flex-1">+ <CardTitle>License activated</CardTitle>+ <p className="mt-2 text-sm leading-6 text-neutral-600">+ Your {formatLicensePlan(license.plan)} license is active. Licensed features are ready to use.+ </p>+ <Button type="button" variant="outline" className="mt-5" onClick={() => void submit("deactivate")} disabled={action !== null}>+ {action === "deactivate" ? "Deactivating..." : "Deactivate license"}+ </Button>+ {status && <p className="mt-3 text-sm text-neutral-500">{status}</p>}+ </div>+ </CardContent>+ </Card>+ );+ }++ return (+ <Card className="rounded-3xl border-0 bg-white px-6">+ <CardHeader>+ <div className="flex items-center justify-between gap-4">+ <div className="space-y-1.5">+ <CardTitle>License activation</CardTitle>+ <CardDescription>Activate the key delivered after your Paymug purchase.</CardDescription>+ </div>+ <Badge variant={license?.active ? "default" : "outline"}>+ {formatLicensePlan(license?.plan ?? "community")}+ </Badge>+ </div>+ </CardHeader>+ <CardContent className="space-y-5 pb-6">+ {hasActivation && license && (+ <p className="rounded-2xl bg-amber-50 px-4 py-3 text-sm text-amber-800">+ This license is currently {license.state}. Enter its key to validate or deactivate it.+ </p>+ )}+ {!hasActivation && (+ <div className="space-y-2">+ <Label htmlFor="licensePlan">Product</Label>+ <select+ id="licensePlan"+ value={selectedPlan}+ onChange={(event) => setSelectedPlan(event.target.value as ActivatableLicensePlan)}+ disabled={action !== null}+ className="flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 disabled:cursor-not-allowed disabled:opacity-50"+ >+ <option value="pro">Pro</option>+ <option value="team">Team</option>+ </select>+ </div>+ )}+ <div className="space-y-2">+ <Label htmlFor="licenseKey">License key</Label>+ <Input+ id="licenseKey"+ type="password"+ autoComplete="off"+ value={licenseKey}+ onChange={(event) => setLicenseKey(event.target.value)}+ placeholder="Enter your Paymug license key"+ disabled={action !== null}+ />+ <p className="text-xs text-neutral-500">The key is sent directly to Paymug and is not stored. Mailflare keeps only a one-way hash. Activation binds the key to this installation and URL.</p>+ </div>+ <div className="flex flex-wrap items-center gap-3">+ {hasActivation ? (+ <>+ <Button type="button" onClick={() => void submit("validate")} disabled={action !== null}>+ {action === "validate" ? "Validating..." : "Validate license"}+ </Button>+ <Button type="button" variant="outline" onClick={() => void submit("deactivate")} disabled={action !== null}>+ {action === "deactivate" ? "Deactivating..." : "Deactivate"}+ </Button>+ </>+ ) : (+ <Button type="button" onClick={() => void submit("activate")} disabled={action !== null}>+ {action === "activate" ? "Activating..." : "Activate license"}+ </Button>+ )}+ {status && <p className="text-sm text-neutral-500">{status}</p>}+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/src/app/(admin)/licenses/page.tsx b/src/app/(admin)/licenses/page.tsxnew file mode 100644index 0000000..7bb81a1--- /dev/null+++ b/src/app/(admin)/licenses/page.tsx@@ -0,0 +1,81 @@+import { Check, ExternalLink } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { LicenseActivation } from "./license-activation";+import { LICENSE_PLANS } from "./utils";++export default function LicensesPage() {+ return (+ <div className="space-y-6">+ <div>+ <h1 className="text-3xl font-medium text-neutral-900">Licenses</h1>+ <p className="mt-2 text-sm text-neutral-500">+ Choose a perpetual license. Each purchase includes updates released+ during the first year.+ </p>+ </div>+ <LicenseActivation />+ <div className="grid gap-4 md:grid-cols-2">+ {LICENSE_PLANS.map((plan) => {+ const Icon = plan.icon;+ return (+ <Card+ key={plan.name}+ className="rounded-3xl border-0 bg-white p-6 flex flex-col"+ >+ <CardHeader className="space-y-4 py-0">+ <div className="flex items-center justify-between">+ <span className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 text-blue-700">+ <Icon className="h-5 w-5" />+ </span>+ </div>+ <div className="relative">+ <CardTitle>{plan.name}</CardTitle>+ <p className="mt-2 text-6xl text-neutral-950 flex">+ <span className="text-[12px] mt-2">$</span>+ <b>{plan.price}</b>+ {plan.originalPrice && (+ <span className="absolute right-0 bottom-6 line-through text-base opacity-40">+ ${plan.originalPrice}+ </span>+ )}+ </p>+ </div>+ <CardDescription>{plan.description}</CardDescription>+ </CardHeader>+ <CardContent className="space-y-3 pt-6 flex flex-col flex-1 min-h-0">+ {plan.features.map((feature) => (+ <p+ key={feature}+ className="flex gap-2 text-sm text-neutral-600"+ >+ <Check className="mt-0.5 h-4 w-4 shrink-0 text-green-600" />+ {feature}+ </p>+ ))}+ <span className="flex-1" />+ <Button asChild className="mt-4 w-full">+ <a+ href={plan.checkoutUrl}+ target="_blank"+ rel="noopener noreferrer"+ >+ Get {plan.name}+ <ExternalLink className="h-4 w-4" />+ </a>+ </Button>+ </CardContent>+ </Card>+ );+ })}+ </div>+ </div>+ );+}diff --git a/src/app/(admin)/licenses/types.d.ts b/src/app/(admin)/licenses/types.d.tsnew file mode 100644index 0000000..5c404e5--- /dev/null+++ b/src/app/(admin)/licenses/types.d.ts@@ -0,0 +1,21 @@+import type { LucideIcon } from "lucide-react";+import type { LicenseStatus } from "@/lib/licenses/types";++export type LicensePlan = {+ name: string;+ price: number;+ description: string;+ features: string[];+ icon: LucideIcon;+ checkoutUrl: string;+ originalPrice?: number,+};++export type LicenseAction = "activate" | "validate" | "deactivate";++export type ActivatableLicensePlan = "pro" | "team";++export type LicenseResponse = {+ license?: LicenseStatus;+ error?: string;+};diff --git a/src/app/(admin)/licenses/utils.ts b/src/app/(admin)/licenses/utils.tsnew file mode 100644index 0000000..25be017--- /dev/null+++ b/src/app/(admin)/licenses/utils.ts@@ -0,0 +1,57 @@+import { Building2, Sparkles } from "lucide-react";+import type { LicensePlan } from "./types";+import { authFetch } from "@/lib/auth/client";+import { LICENSE_STATUS_CHANGED_EVENT } from "@/lib/licenses/constants";+import type { ActivatableLicensePlan, LicenseAction, LicenseResponse } from "./types";++export const LICENSE_PLANS: LicensePlan[] = [+ {+ name: "Pro",+ price: 19,+ originalPrice: 39,+ description: "A perpetual license for one account, including one year of product updates.",+ features: ["Custom branding", "All future Pro features", "One year of updates", "Keep the licensed version forever"],+ icon: Sparkles,+ checkoutUrl: "https://app.paymug.co/buy/mailflare-pro",+ },+ {+ name: "Team",+ price: 249,+ description: "A perpetual multi-account license with every Pro capability and one year of updates.",+ features: ["Everything in Pro", "Add and manage other accounts", "Shared mailbox access as available", "One year of updates", "Keep the licensed version forever"],+ icon: Building2,+ checkoutUrl: "https://app.paymug.co/buy/mailflare-team",+ },+];++export async function loadLicenseStatus(): Promise<NonNullable<LicenseResponse["license"]>> {+ const response = await authFetch("/api/licenses");+ const data = (await response.json()) as LicenseResponse;+ if (!response.ok || !data.license) throw new Error(data.error ?? "Unable to load license status");+ return data.license;+}++export async function runLicenseAction(+ action: LicenseAction,+ licenseKey: string,+ plan?: ActivatableLicensePlan,+): Promise<NonNullable<LicenseResponse["license"]>> {+ const response = await authFetch(`/api/licenses/${action}`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ licenseKey, ...(plan ? { plan } : {}) }),+ });+ const data = (await response.json()) as LicenseResponse;+ if (!response.ok || !data.license) throw new Error(data.error ?? "License request failed");+ window.dispatchEvent(new Event(LICENSE_STATUS_CHANGED_EVENT));+ return data.license;+}++export function formatLicensePlan(plan: string): string {+ return plan === "team" ? "Team" : plan === "pro" ? "Pro" : "Community";+}++export function formatLicenseDate(value: Date | string | null): string | null {+ if (!value) return null;+ return new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(new Date(value));+}diff --git a/src/app/(admin)/mailboxes/page.tsx b/src/app/(admin)/mailboxes/page.tsxindex 52d108e..ca75a69 100644--- a/src/app/(admin)/mailboxes/page.tsx+++ b/src/app/(admin)/mailboxes/page.tsx@@ -18,7 +18,7 @@ import { Label } from "@/components/ui/label";import { CardGridSkeleton } from "@/components/page-skeletons";import { clearMailboxesCache } from "@/components/mailbox-provider-utils";import { authFetch } from "@/lib/auth/client";-import type { CurrentAccountResponse, Domain, Mailbox } from "./types";+import type { CurrentAccountResponse, Domain, Mailbox, MailboxOwner } from "./types";import { getMailboxAddress, getMailboxName } from "./utils";export default function MailboxesPage() {@@ -26,6 +26,7 @@ export default function MailboxesPage() {const [displayName, setDisplayName] = useState("");const [localPart, setLocalPart] = useState("");const [domainId, setDomainId] = useState("");+ const [ownerUserId, setOwnerUserId] = useState("");const [createOpen, setCreateOpen] = useState(false);const account = useQuery({@@ -39,7 +40,18 @@ export default function MailboxesPage() {useEffect(() => {if (!createOpen) return;setDisplayName((currentName) => currentName || account.data?.user?.name?.trim() || "");- }, [account.data?.user?.name, createOpen]);+ setOwnerUserId((currentId) => currentId || account.data?.user?.id || "");+ }, [account.data?.user?.id, account.data?.user?.name, createOpen]);++ const accounts = useQuery({+ queryKey: ["accounts", "mailbox-owners"],+ queryFn: async () => {+ const res = await authFetch("/api/accounts");+ if (!res.ok) return { accounts: [] as MailboxOwner[] };+ return (await res.json()) as { accounts: MailboxOwner[] };+ },+ enabled: createOpen,+ });const domains = useQuery({queryKey: ["domains"],@@ -62,13 +74,14 @@ export default function MailboxesPage() {const res = await authFetch("/api/mailboxes", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ domainId, localPart, displayName: displayName.trim() }),+ body: JSON.stringify({ domainId, ownerUserId, localPart, displayName: displayName.trim() }),});const json = (await res.json()) as { error?: string };if (!res.ok) throw new Error(json.error ?? "Failed");setDisplayName("");setLocalPart("");setDomainId("");+ setOwnerUserId("");},onSuccess: () => {clearMailboxesCache();@@ -80,6 +93,15 @@ export default function MailboxesPage() {const domainMap = new Map((domains.data?.domains ?? []).map((d) => [d.id, d.hostname]),);+ const mailboxOwners = [...(accounts.data?.accounts ?? [])];+ if (account.data?.user?.id && !mailboxOwners.some((owner) => owner.id === account.data?.user?.id)) {+ mailboxOwners.unshift({+ id: account.data.user.id,+ email: account.data.user.email ?? "",+ name: account.data.user.name ?? account.data.user.email ?? "Current account",+ role: "admin",+ });+ }return (<div className="space-y-6">@@ -98,6 +120,25 @@ export default function MailboxesPage() {<DialogDescription>Add an address and provision its routing rule automatically.</DialogDescription></DialogHeader><div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="mailbox-owner">Account</Label>+ <select+ id="mailbox-owner"+ value={ownerUserId}+ onChange={(event) => {+ const owner = mailboxOwners.find((item) => item.id === event.target.value);+ setOwnerUserId(event.target.value);+ if (owner) setDisplayName(owner.name);+ }}+ className="flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm shadow-sm shadow-neutral-200/50 focus-visible:border-blue-600 focus-visible:outline-none"+ >+ {mailboxOwners.map((owner) => (+ <option key={owner.id} value={owner.id}>+ {owner.name} ({owner.email})+ </option>+ ))}+ </select>+ </div><div className="space-y-2"><Label htmlFor="mailbox-name">Name</Label><Input@@ -138,7 +179,7 @@ export default function MailboxesPage() {)}<ButtononClick={() => create.mutate()}- disabled={!displayName.trim() || !domainId || !localPart || create.isPending}+ disabled={!ownerUserId || !displayName.trim() || !domainId || !localPart || create.isPending}>{create.isPending ? "Creating..." : "Create mailbox"}</Button>diff --git a/src/app/(admin)/mailboxes/types.d.ts b/src/app/(admin)/mailboxes/types.d.tsindex 6e003e0..37e8301 100644--- a/src/app/(admin)/mailboxes/types.d.ts+++ b/src/app/(admin)/mailboxes/types.d.ts@@ -17,6 +17,15 @@ export type Domain = {export type CurrentAccountResponse = {user?: {+ id?: string;+ email?: string;name?: string | null;};};++export type MailboxOwner = {+ id: string;+ email: string;+ name: string;+ role: "admin" | "user";+};diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsxindex 67a7edc..f730740 100644--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx@@ -12,6 +12,7 @@ import { MessageActions } from "@/components/message-actions/message-actions";import { MessageAttachmentViewer } from "@/components/message-attachment-viewer";import { MessageAttachmentCard } from "@/components/message-attachment-card";import { MessageDetailSkeleton } from "@/components/page-skeletons";+import { usePageLoading } from "@/components/page-loading";import { PreviousMessage } from "@/components/previous-message";import { getMessageBackHref } from "@/components/message-actions/utils";import type { MessageAttachment, MessageDetailResponse } from "./types";@@ -32,6 +33,7 @@ export default function MessageDetailPage() {const [loading, setLoading] = useState(true);const [previewAttachment, setPreviewAttachment] =useState<MessageAttachment | null>(null);+ usePageLoading(loading);useEffect(() => {let cancelled = false;diff --git a/src/app/(dashboard)/layout.tsx b/src/app/(dashboard)/layout.tsxindex e42d89d..37f1730 100644--- a/src/app/(dashboard)/layout.tsx+++ b/src/app/(dashboard)/layout.tsx@@ -9,6 +9,7 @@ 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 { LicenseIndicator } from "@/components/license-indicator";import { DashboardNav } from "@/components/dashboard-nav";export default function DashboardLayout({@@ -17,11 +18,11 @@ export default function DashboardLayout({children: React.ReactNode;}) {return (- <AuthGuard requireMailbox>+ <AuthGuard><MailboxProvider><ComposeProvider><MailSearchProvider>- <div className="grid h-[100dvh] grid-cols-[256px_minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]">+ <div className="grid h-[100dvh] grid-cols-[240px_minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]"><aside className="min-h-0 overflow-y-auto overscroll-contain px-3 py-4 [scrollbar-gutter:stable]"><DashboardNav /></aside>@@ -34,6 +35,7 @@ export default function DashboardLayout({><HelpCircle className="h-5 w-5" /></Link>+ <LicenseIndicator /><MailboxSelector /></header><main className="min-h-0 flex-1 overflow-y-auto overscroll-contain rounded-tl-3xl bg-white [scrollbar-gutter:stable]">diff --git a/src/app/(settings)/layout.tsx b/src/app/(settings)/layout.tsxindex 2263895..45a33c2 100644--- a/src/app/(settings)/layout.tsx+++ b/src/app/(settings)/layout.tsx@@ -9,6 +9,7 @@ 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 { LicenseIndicator } from "@/components/license-indicator";import { DashboardNav } from "@/components/dashboard-nav";export default function DashboardLayout({@@ -17,11 +18,11 @@ export default function DashboardLayout({children: React.ReactNode;}) {return (- <AuthGuard requireMailbox>+ <AuthGuard><MailboxProvider><ComposeProvider><MailSearchProvider>- <div className="grid h-[100dvh] grid-cols-[256px_minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]">+ <div className="grid h-[100dvh] grid-cols-[240px_minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]"><aside className="min-h-0 overflow-y-auto overscroll-contain px-3 py-4 [scrollbar-gutter:stable]"><DashboardNav /></aside>@@ -34,6 +35,7 @@ export default function DashboardLayout({><HelpCircle className="h-5 w-5" /></Link>+ <LicenseIndicator /><MailboxSelector /></header><main className="min-h-0 flex-1 overflow-y-auto overscroll-contain scrollbar-gutter-stable">diff --git a/src/app/(settings)/settings/page.tsx b/src/app/(settings)/settings/page.tsxindex a88c060..331d189 100644--- a/src/app/(settings)/settings/page.tsx+++ b/src/app/(settings)/settings/page.tsx@@ -1,7 +1,7 @@-import { CurrentMailboxForm } from "@/components/settings/current-mailbox-form";+import { AccountSettings } from "@/components/settings/account-settings";export default function SettingsPage() {return (- <CurrentMailboxForm />+ <AccountSettings />);}diff --git a/src/app/api/accounts/[id]/avatar/route.ts b/src/app/api/accounts/[id]/avatar/route.tsnew file mode 100644index 0000000..5e15014--- /dev/null+++ b/src/app/api/accounts/[id]/avatar/route.ts@@ -0,0 +1,44 @@+import { eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { users } from "@/db/schema";+import {+ ALLOWED_AVATAR_TYPES,+ MAX_AVATAR_SIZE,+ avatarKeyFor,+ isUploadedAvatarFile,+} from "@/app/api/profile/avatar/utils";+import type { AccountRouteParams } from "../types";+import { getManagedAccount } from "./utils";++export async function GET(request: Request, { params }: AccountRouteParams) {+ const { id } = await params;+ const { access, account } = await getManagedAccount(request, id);+ if (access.error) return access.error;+ if (!account?.avatarKey) return new Response("Not found", { status: 404 });+ const object = await access.env.BUCKET.get(account.avatarKey);+ if (!object) return new Response("Not found", { status: 404 });+ return new Response(object.body, {+ headers: {+ "Content-Type": object.httpMetadata?.contentType ?? "application/octet-stream",+ "Cache-Control": "private, no-cache",+ "X-Content-Type-Options": "nosniff",+ },+ });+}++export async function POST(request: Request, { params }: AccountRouteParams) {+ const { id } = await params;+ const { access, account } = await getManagedAccount(request, id);+ if (access.error) return access.error;+ if (!account) return NextResponse.json({ error: "Account not found" }, { status: 404 });+ const form = await request.formData();+ const file = form.get("file");+ if (!isUploadedAvatarFile(file)) return NextResponse.json({ error: "Missing image file" }, { status: 400 });+ if (!ALLOWED_AVATAR_TYPES.includes(file.type)) return NextResponse.json({ error: "Use a JPEG, PNG, WebP, or GIF image" }, { status: 400 });+ if (file.size > MAX_AVATAR_SIZE) return NextResponse.json({ error: "Image must be 2 MB or smaller" }, { status: 413 });+ const key = avatarKeyFor(account.id);+ await access.env.BUCKET.put(key, await file.arrayBuffer(), { httpMetadata: { contentType: file.type } });+ await getDb(access.env).update(users).set({ avatarKey: key }).where(eq(users.id, account.id));+ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/accounts/[id]/avatar/utils.ts b/src/app/api/accounts/[id]/avatar/utils.tsnew file mode 100644index 0000000..d01eb53--- /dev/null+++ b/src/app/api/accounts/[id]/avatar/utils.ts@@ -0,0 +1,13 @@+import { getDb } from "@/db";+import { requireTeamAdmin } from "../../utils";+import { selectAccountById } from "../utils";++export async function getManagedAccount(request: Request, id: string) {+ const access = await requireTeamAdmin(request);+ if (access.error) return { access, account: null };+ const account = await selectAccountById(getDb(access.env), id);+ if (!account || (account.id !== access.user!.id && account.createdByUserId !== access.user!.id)) {+ return { access, account: null };+ }+ return { access, account };+}diff --git a/src/app/api/accounts/[id]/mailboxes/route.ts b/src/app/api/accounts/[id]/mailboxes/route.tsindex e297367..56ec484 100644--- a/src/app/api/accounts/[id]/mailboxes/route.ts+++ b/src/app/api/accounts/[id]/mailboxes/route.ts@@ -1,12 +1,26 @@+import { eq } from "drizzle-orm";import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { domains, mailboxes } from "@/db/schema";+import { requireTeamAdmin } from "../../utils";+import { selectAccountById } from "../utils";+import type { AccountRouteParams } from "../types";-const accountsRemovedResponse = () =>- NextResponse.json({ error: "Multiple accounts are not available in this build" }, { status: 410 });--export async function GET() {- return accountsRemovedResponse();-}--export async function POST() {- return accountsRemovedResponse();+export async function GET(request: Request, { params }: AccountRouteParams) {+ const access = await requireTeamAdmin(request);+ if (access.error) return access.error;+ const { id } = await params;+ const db = getDb(access.env);+ const account = await selectAccountById(db, id);+ if (!account || (account.id !== access.user!.id && account.createdByUserId !== access.user!.id)) {+ return NextResponse.json({ error: "Account not found" }, { status: 404 });+ }+ const rows = await db.select({+ id: mailboxes.id,+ localPart: mailboxes.localPart,+ displayName: mailboxes.displayName,+ domainId: mailboxes.domainId,+ hostname: domains.hostname,+ }).from(mailboxes).innerJoin(domains, eq(mailboxes.domainId, domains.id)).where(eq(mailboxes.userId, id));+ return NextResponse.json({ mailboxes: rows });}diff --git a/src/app/api/accounts/[id]/route.ts b/src/app/api/accounts/[id]/route.tsindex b74301c..6c17ea9 100644--- a/src/app/api/accounts/[id]/route.ts+++ b/src/app/api/accounts/[id]/route.ts@@ -1,12 +1,49 @@import { NextResponse } from "next/server";+import { eq } from "drizzle-orm";+import { getDb } from "@/db";+import { users } from "@/db/schema";+import { updateManagedAccountSchema } from "@/lib/validators";+import { requireTeamAdmin } from "../utils";+import type { AccountRouteParams } from "./types";+import { selectAccountById, updateAccountCredentials } from "./utils";-const accountsRemovedResponse = () =>- NextResponse.json({ error: "Multiple accounts are not available in this build" }, { status: 410 });--export async function GET() {- return accountsRemovedResponse();+export async function GET(request: Request, { params }: AccountRouteParams) {+ const access = await requireTeamAdmin(request);+ if (access.error) return access.error;+ const { id } = await params;+ const account = await selectAccountById(getDb(access.env), id);+ if (!account || (account.id !== access.user!.id && account.createdByUserId !== access.user!.id)) {+ return NextResponse.json({ error: "Account not found" }, { status: 404 });+ }+ return NextResponse.json({+ account: {+ id: account.id,+ email: account.email,+ name: account.name,+ role: account.role,+ disabled: account.disabled,+ canManageMailboxes: account.canManageMailboxes,+ hasAvatar: !!account.avatarKey,+ },+ });}-export async function PATCH() {- return accountsRemovedResponse();+export async function PATCH(request: Request, { params }: AccountRouteParams) {+ const access = await requireTeamAdmin(request);+ if (access.error) return access.error;+ const { id } = await params;+ const db = getDb(access.env);+ const account = await selectAccountById(db, id);+ if (!account || (account.id !== access.user!.id && account.createdByUserId !== access.user!.id)) {+ return NextResponse.json({ error: "Account not found" }, { status: 404 });+ }+ const parsed = updateManagedAccountSchema.safeParse(await request.json());+ if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });+ await updateAccountCredentials(db, id, { name: parsed.data.name, password: null });+ await db.update(users).set({+ role: parsed.data.role,+ disabled: parsed.data.disabled,+ canManageMailboxes: parsed.data.canManageMailboxes,+ }).where(eq(users.id, id));+ return NextResponse.json({ ok: true });}diff --git a/src/app/api/accounts/route.ts b/src/app/api/accounts/route.tsindex e297367..992645b 100644--- a/src/app/api/accounts/route.ts+++ b/src/app/api/accounts/route.ts@@ -1,12 +1,83 @@import { NextResponse } from "next/server";+import { eq } from "drizzle-orm";+import { getDb } from "@/db";+import { mailboxes, users } from "@/db/schema";+import { hashPassword } from "@/lib/auth/password";+import { newId } from "@/lib/ids";+import { createUserAccountSchema } from "@/lib/validators";+import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";+import type { CreateUserAccountInput } from "./types";+import {+ accountListItemFromUser,+ getDomainForAdmin,+ getExistingMailbox,+ listAccountsForAdmin,+ requireTeamAdmin,+} from "./utils";-const accountsRemovedResponse = () =>- NextResponse.json({ error: "Multiple accounts are not available in this build" }, { status: 410 });--export async function GET() {- return accountsRemovedResponse();+export async function GET(request: Request) {+ const access = await requireTeamAdmin(request);+ if (access.error) return access.error;+ const rows = await listAccountsForAdmin(getDb(access.env));+ return NextResponse.json({+ accounts: rows.map((row) => accountListItemFromUser(row)),+ });}-export async function POST() {- return accountsRemovedResponse();+export async function POST(request: Request) {+ const access = await requireTeamAdmin(request);+ if (access.error) return access.error;++ const parsed = createUserAccountSchema.safeParse(await request.json());+ if (!parsed.success) {+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });+ }++ const input: CreateUserAccountInput = parsed.data;+ const db = getDb(access.env);+ const domain = await getDomainForAdmin(db, access.user!.id, input.domainId);+ if (!domain) return NextResponse.json({ error: "Domain not found" }, { status: 404 });+ const username = input.username.toLowerCase().trim();+ const email = `${username}@${domain.hostname}`;+ const [existing] = await db.select({ id: users.id }).from(users).where(eq(users.email, email)).limit(1);+ if (existing) return NextResponse.json({ error: "Email already registered" }, { status: 409 });+ const mailbox = await getExistingMailbox(db, domain.id, username);+ if (mailbox) return NextResponse.json({ error: "Email address is already assigned" }, { status: 409 });++ const userId = newId("usr");+ try {+ await ensureEmailRoutingRuleToWorker(access.env, domain.zoneId, email);+ const [account] = await db+ .insert(users)+ .values({+ id: userId,+ email,+ passwordHash: hashPassword(input.password),+ name: username,+ role: input.role,+ createdByUserId: access.user!.id,+ })+ .returning({+ id: users.id,+ email: users.email,+ name: users.name,+ resetEmail: users.resetEmail,+ role: users.role,+ disabled: users.disabled,+ createdAt: users.createdAt,+ });+ await db.insert(mailboxes).values({+ id: newId("mbx"),+ userId,+ domainId: domain.id,+ localPart: username,+ displayName: username,+ });++ return NextResponse.json({ account: accountListItemFromUser(account) }, { status: 201 });+ } catch (error) {+ await db.delete(users).where(eq(users.id, userId));+ const message = error instanceof Error ? error.message : "Failed to create account mailbox";+ return NextResponse.json({ error: message }, { status: 502 });+ }}diff --git a/src/app/api/accounts/types.d.ts b/src/app/api/accounts/types.d.tsindex c74e320..d79d7df 100644--- a/src/app/api/accounts/types.d.ts+++ b/src/app/api/accounts/types.d.ts@@ -5,6 +5,8 @@ export type AccountListItem = {resetEmail: string | null;role: "admin" | "user";createdAt: Date;+ hasAvatar?: boolean;+ canManageMailboxes?: boolean;mailboxId: string | null;localPart: string | null;hostname: string | null;@@ -16,3 +18,15 @@ export type CreateAccountResult = {mailboxId?: string;error?: unknown;};++export type CreateUserAccountInput = {+ username: string;+ domainId: string;+ password: string;+ role: "admin" | "user";+};++export type AccountListResponse = {+ accounts?: AccountListItem[];+ error?: string;+};diff --git a/src/app/api/accounts/utils.ts b/src/app/api/accounts/utils.tsindex d3552fe..8688892 100644--- a/src/app/api/accounts/utils.ts+++ b/src/app/api/accounts/utils.ts@@ -1,6 +1,11 @@import { and, desc, eq } from "drizzle-orm";+import { NextResponse } from "next/server";import type { getDb } from "@/db";import { domains, mailboxes, users } from "@/db/schema";+import { assertAdmin } from "@/lib/auth/admin";+import { requireUser } from "@/lib/auth/cookies";+import { getLicenseEntitlements } from "@/lib/licenses/service";+import { getEnv } from "@/lib/cloudflare";type Db = ReturnType<typeof getDb>;@@ -13,6 +18,8 @@ export function listAccountsForAdmin(db: Db) {resetEmail: users.resetEmail,role: users.role,disabled: users.disabled,+ avatarKey: users.avatarKey,+ canManageMailboxes: users.canManageMailboxes,createdAt: users.createdAt,}).from(users)@@ -36,3 +43,45 @@ export async function getExistingMailbox(db: Db, domainId: string, localPart: st.limit(1);return mailbox ?? null;}++export function accountListItemFromUser(user: {+ id: string;+ email: string;+ name: string;+ resetEmail: string | null;+ role: "admin" | "user";+ disabled: boolean;+ avatarKey?: string | null;+ canManageMailboxes?: boolean;+ createdAt: Date;+}) {+ return {+ id: user.id,+ email: user.email,+ name: user.name,+ resetEmail: user.resetEmail,+ role: user.role,+ disabled: user.disabled,+ hasAvatar: !!user.avatarKey,+ canManageMailboxes: !!user.canManageMailboxes,+ createdAt: user.createdAt,+ };+}++export async function requireTeamAdmin(request: Request) {+ const env = getEnv();+ try {+ const user = await requireUser(env, request);+ assertAdmin(user);+ if (!(await getLicenseEntitlements(env)).canManageAccounts) {+ return {+ env,+ user,+ error: NextResponse.json({ error: "A Team license is required to manage accounts" }, { status: 403 }),+ };+ }+ return { env, user, error: null };+ } catch {+ return { env, user: null, error: NextResponse.json({ error: "Forbidden" }, { status: 403 }) };+ }+}diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex 181ece3..a5faf50 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -6,7 +6,6 @@ import { users } from "@/db/schema";import { verifyPassword } from "@/lib/auth/password";import { createSession, SESSION_COOKIE } from "@/lib/auth/session";import { loginSchema } from "@/lib/validators";-import { userHasAccessibleMailboxes } from "@/lib/user";import { allowLoginAttempt } from "@/lib/auth/rate-limit";import { verifyTurnstileToken } from "@/lib/auth/turnstile";import { readJsonBody } from "@/lib/http/request";@@ -45,13 +44,12 @@ export async function POST(request: Request) {return NextResponse.json({ error: "Account disabled" }, { status: 403 });}- const hasMailboxes = await userHasAccessibleMailboxes(env, user);const token = await createSession(env, user.id);await recordAuthActivity(env, { action: "auth.login", userId: user.id, request });const response = NextResponse.json({ok: true,token,- redirect: hasMailboxes ? "/inbox" : "/setup",+ redirect: "/inbox",});response.headers.set("Cache-Control", "no-store");response.cookies.set(SESSION_COOKIE, token, {diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsindex b9f66a5..b1e061a 100644--- a/src/app/api/auth/me/route.ts+++ b/src/app/api/auth/me/route.ts@@ -1,7 +1,7 @@import { NextResponse } from "next/server";import { getCurrentUser } from "@/lib/auth/cookies";import { getEnv } from "@/lib/cloudflare";-import { userHasMailboxes } from "@/lib/user";+import { hasPrimaryDomain, userHasMailboxes } from "@/lib/user";export async function GET(request: Request) {const env = getEnv();@@ -10,7 +10,16 @@ export async function GET(request: Request) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 });}- const hasMailboxes = await userHasMailboxes(env, user.id);+ let hasMailboxes = false;+ let isSetup = true;+ try {+ [hasMailboxes, isSetup] = await Promise.all([+ userHasMailboxes(env, user.id),+ hasPrimaryDomain(env),+ ]);+ } catch {+ // Authentication remains valid when optional mailbox/setup metadata is unavailable.+ }return NextResponse.json({user: {id: user.id,@@ -18,8 +27,10 @@ export async function GET(request: Request) {name: user.name,resetEmail: user.resetEmail,role: user.role,+ canManageMailboxes: user.canManageMailboxes,hasAvatar: !!user.avatarKey,},hasMailboxes,+ isSetup,});}diff --git a/src/app/api/branding/icon/route.ts b/src/app/api/branding/icon/route.tsnew file mode 100644index 0000000..a311087--- /dev/null+++ b/src/app/api/branding/icon/route.ts@@ -0,0 +1,42 @@+import { eq } from "drizzle-orm";+import { getDb } from "@/db";+import { appSettings } from "@/db/schema";+import { APP_SETTINGS_ID } from "@/lib/branding/service";+import { getEnv } from "@/lib/cloudflare";+import { getLicenseEntitlements } from "@/lib/licenses/service";++async function getDefaultIcon(env: CloudflareEnv): Promise<Response> {+ const asset = await env.ASSETS.fetch("https://mailflare.local/icon-96.png");+ return new Response(await asset.arrayBuffer(), {+ status: asset.status,+ statusText: asset.statusText,+ headers: asset.headers,+ });+}++export async function GET(request: Request) {+ const env = getEnv();+ if (!(await getLicenseEntitlements(env)).canCustomizeBranding) return getDefaultIcon(env);+ try {+ const [settings] = await getDb(env)+ .select({ iconKey: appSettings.iconKey })+ .from(appSettings)+ .where(eq(appSettings.id, APP_SETTINGS_ID))+ .limit(1);+ if (settings?.iconKey) {+ const object = await env.BUCKET.get(settings.iconKey);+ if (object) {+ return new Response(object.body, {+ headers: {+ "Content-Type": object.httpMetadata?.contentType ?? "image/png",+ "Cache-Control": "no-cache",+ "X-Content-Type-Options": "nosniff",+ },+ });+ }+ }+ } catch {+ // Use the packaged icon until the branding migration is available.+ }+ return getDefaultIcon(env);+}diff --git a/src/app/api/branding/route.ts b/src/app/api/branding/route.tsnew file mode 100644index 0000000..6864e88--- /dev/null+++ b/src/app/api/branding/route.ts@@ -0,0 +1,43 @@+import { NextResponse } from "next/server";+import { assertAdmin } from "@/lib/auth/admin";+import { requireUser } from "@/lib/auth/cookies";+import { getBranding, updateBranding } from "@/lib/branding/service";+import { getEnv } from "@/lib/cloudflare";+import { BRANDING_ICON_TYPES, isBrandingIcon, MAX_BRANDING_ICON_SIZE } from "./utils";++export async function GET() {+ return NextResponse.json(await getBranding(getEnv()), {+ headers: { "Cache-Control": "no-store" },+ });+}++export async function PUT(request: Request) {+ const env = getEnv();+ try {+ assertAdmin(await requireUser(env, request));+ } catch {+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });+ }++ const form = await request.formData();+ const appName = String(form.get("appName") ?? "").trim();+ const iconValue = form.get("icon");+ if (!appName || appName.length > 60) {+ return NextResponse.json({ error: "App name must be between 1 and 60 characters" }, { status: 400 });+ }+ const icon = isBrandingIcon(iconValue) && iconValue.size > 0 ? iconValue : null;+ if (icon && !BRANDING_ICON_TYPES.includes(icon.type)) {+ return NextResponse.json({ error: "Use a PNG, JPEG, WebP, or GIF image" }, { status: 400 });+ }+ if (icon && icon.size > MAX_BRANDING_ICON_SIZE) {+ return NextResponse.json({ error: "Icon must be 2 MB or smaller" }, { status: 413 });+ }++ try {+ return NextResponse.json(await updateBranding(env, { appName, icon }));+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unable to update branding";+ const status = /license is required/i.test(message) ? 403 : 500;+ return NextResponse.json({ error: message }, { status });+ }+}diff --git a/src/app/api/branding/types.d.ts b/src/app/api/branding/types.d.tsnew file mode 100644index 0000000..8fcc053--- /dev/null+++ b/src/app/api/branding/types.d.ts@@ -0,0 +1,3 @@+export type UploadedBrandingIcon = File & {+ arrayBuffer(): Promise<ArrayBuffer>;+};diff --git a/src/app/api/branding/utils.ts b/src/app/api/branding/utils.tsnew file mode 100644index 0000000..86388bb--- /dev/null+++ b/src/app/api/branding/utils.ts@@ -0,0 +1,8 @@+import type { UploadedBrandingIcon } from "./types";++export const MAX_BRANDING_ICON_SIZE = 2 * 1024 * 1024;+export const BRANDING_ICON_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];++export function isBrandingIcon(value: FormDataEntryValue | null): value is UploadedBrandingIcon {+ return value !== null && typeof value !== "string" && typeof value.arrayBuffer === "function";+}diff --git a/src/app/api/domains/route.ts b/src/app/api/domains/route.tsindex 88b1ac8..7351278 100644--- a/src/app/api/domains/route.ts+++ b/src/app/api/domains/route.ts@@ -8,7 +8,8 @@ import { summariseDns, type DnsStatusSummary } from "@/lib/dns-status";export async function GET(request: NextRequest) {const env = getEnv();const user = await requireUser(env, request);- const domains = await listUserDomains(env, user.id);+ const domainOwnerId = user.canManageMailboxes && user.createdByUserId ? user.createdByUserId : user.id;+ const domains = await listUserDomains(env, domainOwnerId);const includeDns = request.nextUrl.searchParams.get("includeDns") === "true";diff --git a/src/app/api/licenses/activate/route.ts b/src/app/api/licenses/activate/route.tsnew file mode 100644index 0000000..a6b041e--- /dev/null+++ b/src/app/api/licenses/activate/route.ts@@ -0,0 +1,24 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { activateLicense } from "@/lib/licenses/service";+import {+ getLicenseErrorResponse,+ getLicenseInstanceUrl,+ parseLicenseKeyRequest,+ requireLicenseAdmin,+} from "../utils";++export async function POST(request: Request) {+ const env = getEnv();+ const forbidden = await requireLicenseAdmin(env, request);+ if (forbidden) return forbidden;++ try {+ const { licenseKey, plan } = await parseLicenseKeyRequest(request);+ if (!plan) return NextResponse.json({ error: "Choose Pro or Team" }, { status: 400 });+ const license = await activateLicense(env, licenseKey, getLicenseInstanceUrl(request), plan);+ return NextResponse.json({ license });+ } catch (error) {+ return getLicenseErrorResponse(error);+ }+}diff --git a/src/app/api/licenses/deactivate/route.ts b/src/app/api/licenses/deactivate/route.tsnew file mode 100644index 0000000..ea18c8c--- /dev/null+++ b/src/app/api/licenses/deactivate/route.ts@@ -0,0 +1,17 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { deactivateLicense } from "@/lib/licenses/service";+import { getLicenseErrorResponse, requireLicenseAdmin } from "../utils";++export async function POST(request: Request) {+ const env = getEnv();+ const forbidden = await requireLicenseAdmin(env, request);+ if (forbidden) return forbidden;++ try {+ const license = await deactivateLicense(env);+ return NextResponse.json({ license });+ } catch (error) {+ return getLicenseErrorResponse(error);+ }+}diff --git a/src/app/api/licenses/route.ts b/src/app/api/licenses/route.tsnew file mode 100644index 0000000..b5a47b3--- /dev/null+++ b/src/app/api/licenses/route.ts@@ -0,0 +1,18 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { getLicenseStatus } from "@/lib/licenses/service";+import { getLicenseErrorResponse, requireLicenseAdmin } from "./utils";++export async function GET(request: Request) {+ const env = getEnv();+ const forbidden = await requireLicenseAdmin(env, request);+ if (forbidden) return forbidden;++ try {+ return NextResponse.json({ license: await getLicenseStatus(env) }, {+ headers: { "Cache-Control": "no-store" },+ });+ } catch (error) {+ return getLicenseErrorResponse(error);+ }+}diff --git a/src/app/api/licenses/types.d.ts b/src/app/api/licenses/types.d.tsnew file mode 100644index 0000000..e464a2f--- /dev/null+++ b/src/app/api/licenses/types.d.ts@@ -0,0 +1,11 @@+import type { LicensePlan, LicenseStatus } from "@/lib/licenses/types";++export type LicenseKeyRequest = {+ licenseKey: string;+ plan?: Exclude<LicensePlan, "community">;+};++export type LicenseApiResponse = {+ license?: LicenseStatus;+ error?: string;+};diff --git a/src/app/api/licenses/utils.ts b/src/app/api/licenses/utils.tsnew file mode 100644index 0000000..9f14252--- /dev/null+++ b/src/app/api/licenses/utils.ts@@ -0,0 +1,39 @@+import { NextResponse } from "next/server";+import { z } from "zod";+import { assertAdmin } from "@/lib/auth/admin";+import { requireUser } from "@/lib/auth/cookies";+import type { LicenseKeyRequest } from "./types";++const licenseKeySchema = z.object({+ licenseKey: z.string().trim().min(1).max(500),+ plan: z.enum(["pro", "team"]).optional(),+});++export async function requireLicenseAdmin(env: CloudflareEnv, request: Request): Promise<NextResponse | null> {+ try {+ assertAdmin(await requireUser(env, request));+ return null;+ } catch {+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });+ }+}++export async function parseLicenseKeyRequest(request: Request): Promise<LicenseKeyRequest> {+ return licenseKeySchema.parse(await request.json());+}++export function getLicenseInstanceUrl(request: Request): string {+ return new URL(request.url).origin;+}++export function getLicenseErrorResponse(error: unknown): NextResponse {+ if (error instanceof z.ZodError) {+ return NextResponse.json({ error: "Enter a valid license key" }, { status: 400 });+ }+ const message = error instanceof Error ? error.message : "License request failed";+ const migrationMissing = /no such table|license_settings/i.test(message);+ return NextResponse.json(+ { error: migrationMissing ? "Apply the latest database migration before activating a license" : message },+ { status: migrationMissing ? 503 : 400 },+ );+}diff --git a/src/app/api/licenses/validate/route.ts b/src/app/api/licenses/validate/route.tsnew file mode 100644index 0000000..962e9b4--- /dev/null+++ b/src/app/api/licenses/validate/route.ts@@ -0,0 +1,23 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { validateLicense } from "@/lib/licenses/service";+import {+ getLicenseErrorResponse,+ getLicenseInstanceUrl,+ parseLicenseKeyRequest,+ requireLicenseAdmin,+} from "../utils";++export async function POST(request: Request) {+ const env = getEnv();+ const forbidden = await requireLicenseAdmin(env, request);+ if (forbidden) return forbidden;++ try {+ const { licenseKey } = await parseLicenseKeyRequest(request);+ const license = await validateLicense(env, licenseKey, getLicenseInstanceUrl(request));+ return NextResponse.json({ license });+ } catch (error) {+ return getLicenseErrorResponse(error);+ }+}diff --git a/src/app/api/mailboxes/[id]/route.ts b/src/app/api/mailboxes/[id]/route.tsindex 23f5626..ca903ff 100644--- a/src/app/api/mailboxes/[id]/route.ts+++ b/src/app/api/mailboxes/[id]/route.ts@@ -1,7 +1,7 @@import { eq } from "drizzle-orm";import { NextResponse } from "next/server";import { getDb } from "@/db";-import { mailboxes } from "@/db/schema";+import { mailboxes, users } from "@/db/schema";import { requireUser } from "@/lib/auth/cookies";import { getEnv } from "@/lib/cloudflare";import { getMailboxAccessLevel } from "@/lib/mailboxes/access";@@ -73,3 +73,21 @@ export async function PATCH(request: Request, { params }: MailboxRouteParams) {},});}++export async function DELETE(request: Request, { params }: MailboxRouteParams) {+ const { id } = await params;+ const env = getEnv();+ const user = await requireUser(env, request);+ const db = getDb(env);+ const [mailbox] = await db.select().from(mailboxes).where(eq(mailboxes.id, id)).limit(1);+ if (!mailbox) return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });++ let allowed = mailbox.userId === user.id && user.canManageMailboxes;+ if (!allowed && user.role === "admin") {+ const [owner] = await db.select({ createdByUserId: users.createdByUserId }).from(users).where(eq(users.id, mailbox.userId)).limit(1);+ allowed = mailbox.userId === user.id || owner?.createdByUserId === user.id;+ }+ if (!allowed) return NextResponse.json({ error: "Forbidden" }, { status: 403 });+ await db.delete(mailboxes).where(eq(mailboxes.id, id));+ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/mailboxes/route.ts b/src/app/api/mailboxes/route.tsindex bbe9c4e..31a193f 100644--- a/src/app/api/mailboxes/route.ts+++ b/src/app/api/mailboxes/route.ts@@ -2,18 +2,18 @@ import { NextResponse } from "next/server";import { and, eq } from "drizzle-orm";import { getEnv } from "@/lib/cloudflare";import { getDb } from "@/db";-import { domains, mailboxes } from "@/db/schema";+import { domains, mailboxes, users } from "@/db/schema";import { requireUser } from "@/lib/auth/cookies";import { newId } from "@/lib/ids";import { mailboxSchema } from "@/lib/validators";import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";-import { listAccessibleMailboxes } from "@/lib/mailboxes/access";+import { ensurePersonalMailbox } from "./utils";export async function GET(request: Request) {const env = getEnv();const user = await requireUser(env, request);const db = getDb(env);- const rows = await listAccessibleMailboxes(db, user);+ const rows = await ensurePersonalMailbox(env, db, user);return NextResponse.json({ mailboxes: rows });}@@ -27,12 +27,28 @@ export async function POST(request: Request) {const db = getDb(env);const mailboxType = "personal";+ const ownerUserId = parsed.data.ownerUserId ?? user.id;+ if (ownerUserId !== user.id) {+ if (user.role !== "admin") {+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });+ }+ const [owner] = await db+ .select({ id: users.id })+ .from(users)+ .where(and(eq(users.id, ownerUserId), eq(users.createdByUserId, user.id)))+ .limit(1);+ if (!owner) return NextResponse.json({ error: "Account not found" }, { status: 404 });+ }const [domain] = await db.select().from(domains).where(eq(domains.id, parsed.data.domainId)).limit(1);- if (!domain || domain.userId !== user.id) {+ const canUseDomain = domain && (+ domain.userId === user.id ||+ (user.canManageMailboxes && !!user.createdByUserId && domain.userId === user.createdByUserId)+ );+ if (!canUseDomain) {return NextResponse.json({ error: "Domain not found" }, { status: 404 });}@@ -57,7 +73,7 @@ export async function POST(request: Request) {const id = newId("mbx");await db.insert(mailboxes).values({id,- userId: user.id,+ userId: ownerUserId,domainId: parsed.data.domainId,localPart,displayName: parsed.data.displayName,diff --git a/src/app/api/mailboxes/utils.ts b/src/app/api/mailboxes/utils.tsnew file mode 100644index 0000000..bbf41e8--- /dev/null+++ b/src/app/api/mailboxes/utils.ts@@ -0,0 +1,45 @@+import { and, eq } from "drizzle-orm";+import type { AppDatabase } from "@/db";+import { domains, mailboxes } from "@/db/schema";+import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";+import { newId } from "@/lib/ids";+import { listAccessibleMailboxes } from "@/lib/mailboxes/access";+import type { SessionUser } from "@/lib/auth/types";++export async function ensurePersonalMailbox(env: CloudflareEnv, db: AppDatabase, user: SessionUser) {+ const current = await listAccessibleMailboxes(db, user);+ if (current.length > 0) return current;++ const [localPart, hostname] = user.email.toLowerCase().split("@");+ if (!localPart || !hostname) return current;+ const [domain] = await db.select().from(domains).where(eq(domains.hostname, hostname)).limit(1);+ if (!domain) return current;++ const [existing] = await db+ .select({ id: mailboxes.id })+ .from(mailboxes)+ .where(and(eq(mailboxes.domainId, domain.id), eq(mailboxes.localPart, localPart)))+ .limit(1);+ if (existing) return current;++ try {+ await ensureEmailRoutingRuleToWorker(env, domain.zoneId, user.email);+ } catch {+ // Mailbox visibility should not depend on routing API availability.+ }++ try {+ await db.insert(mailboxes).values({+ id: newId("mbx"),+ userId: user.id,+ domainId: domain.id,+ localPart,+ displayName: user.name || localPart,+ type: "personal",+ });+ } catch {+ return current;+ }++ return listAccessibleMailboxes(db, user);+}diff --git a/src/app/api/settings/password/route.ts b/src/app/api/settings/password/route.tsnew file mode 100644index 0000000..b65c03f--- /dev/null+++ b/src/app/api/settings/password/route.ts@@ -0,0 +1,41 @@+import { eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { ZodError } from "zod";+import { getDb } from "@/db";+import { users } from "@/db/schema";+import { requireUser } from "@/lib/auth/cookies";+import { hashPassword, verifyPassword } from "@/lib/auth/password";+import { getEnv } from "@/lib/cloudflare";+import type { ChangePasswordInput } from "./types";+import { parseChangePasswordRequest } from "./utils";++export async function PATCH(request: Request) {+ const env = getEnv();+ const user = await requireUser(env, request);+ let parsed: ChangePasswordInput;++ try {+ parsed = await parseChangePasswordRequest(request);+ } catch (err) {+ if (err instanceof ZodError) {+ return NextResponse.json({ error: err.flatten() }, { status: 400 });+ }+ return NextResponse.json({ error: "Invalid request" }, { status: 400 });+ }++ if (!verifyPassword(parsed.currentPassword, user.passwordHash)) {+ return NextResponse.json({ error: "Current password is incorrect" }, { status: 400 });+ }++ if (verifyPassword(parsed.newPassword, user.passwordHash)) {+ return NextResponse.json({ error: "New password must be different from the current password" }, { status: 400 });+ }++ const db = getDb(env);+ await db+ .update(users)+ .set({ passwordHash: hashPassword(parsed.newPassword) })+ .where(eq(users.id, user.id));++ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/settings/password/types.d.ts b/src/app/api/settings/password/types.d.tsnew file mode 100644index 0000000..1efc2a2--- /dev/null+++ b/src/app/api/settings/password/types.d.ts@@ -0,0 +1,4 @@+import type { changePasswordSchema } from "@/lib/validators";+import type { z } from "zod";++export type ChangePasswordInput = z.infer<typeof changePasswordSchema>;diff --git a/src/app/api/settings/password/utils.ts b/src/app/api/settings/password/utils.tsnew file mode 100644index 0000000..e542eaa--- /dev/null+++ b/src/app/api/settings/password/utils.ts@@ -0,0 +1,7 @@+import { changePasswordSchema } from "@/lib/validators";+import type { ChangePasswordInput } from "./types";++export async function parseChangePasswordRequest(request: Request): Promise<ChangePasswordInput> {+ const body = await request.json();+ return changePasswordSchema.parse(body);+}diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex 722496b..95b6d31 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -16,13 +16,14 @@ const geistMono = Geist_Mono({export const metadata: Metadata = {title: "Mailflare",description: "Multi-tenant email on Cloudflare",+ icons: { icon: "/api/branding/icon" },};export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {return (<html lang="en"><head>- <link rel="icon" type="image/x-icon" href="/favicon.ico"></link>+ <link rel="icon" href="/api/branding/icon"></link></head><body className={`${geistSans.variable} ${geistMono.variable} antialiased light`}><Providers>{children}</Providers>diff --git a/src/app/loading.tsx b/src/app/loading.tsxdeleted file mode 100644index daebc9f..0000000--- a/src/app/loading.tsx+++ /dev/null@@ -1,3 +0,0 @@-import { PageSkeleton } from "@/components/page-skeletons";--export default PageSkeleton;diff --git a/src/app/login/login-client.tsx b/src/app/login/login-client.tsxindex 917e31b..05a922f 100644--- a/src/app/login/login-client.tsx+++ b/src/app/login/login-client.tsx@@ -21,15 +21,25 @@ export function LoginClient() {setLoading(true);setError(null);- const { ok, data } = await submitLogin(new FormData(e.currentTarget));- setLoading(false);- if (!ok) {- setError(data.error ?? "Login failed");+ try {+ const { ok, data } = await submitLogin(new FormData(e.currentTarget));+ if (!ok) {+ setError(data.error ?? "Login failed");+ setTurnstileReset((value) => value + 1);+ return;+ }+ router.replace(data.redirect ?? "/inbox");+ router.refresh();+ } catch (error) {+ setError(+ error instanceof DOMException && error.name === "TimeoutError"+ ? "Login timed out. Please try again."+ : "Unable to reach the login service. Please try again.",+ );setTurnstileReset((value) => value + 1);- return;+ } finally {+ setLoading(false);}- router.replace(data.redirect ?? "/inbox");- router.refresh();}return (@@ -38,7 +48,7 @@ export function LoginClient() {title="Sign in"description="Open your mailbox and continue from the same inbox workspace.">- <form onSubmit={onSubmit} className="space-y-5">+ <form method="post" onSubmit={onSubmit} className="space-y-5"><div className="space-y-2"><Label htmlFor="email">Email</Label><Inputdiff --git a/src/app/login/page.tsx b/src/app/login/page.tsxindex b76645d..29e65f0 100644--- a/src/app/login/page.tsx+++ b/src/app/login/page.tsx@@ -1,13 +1,19 @@+import { cookies } from "next/headers";import { redirect } from "next/navigation";import { AuthGuard } from "@/components/auth/auth-guard";import { hasAdminAccount } from "@/lib/auth/setup";+import { getUserFromSession, SESSION_COOKIE } from "@/lib/auth/session";import { getEnv } from "@/lib/cloudflare";import { LoginClient } from "./login-client";export const dynamic = "force-dynamic";export default async function LoginPage() {- if (!(await hasAdminAccount(getEnv()))) redirect("/setup");+ const env = getEnv();+ if (!(await hasAdminAccount(env))) redirect("/setup");+ const cookieStore = await cookies();+ const user = await getUserFromSession(env, cookieStore.get(SESSION_COOKIE)?.value);+ if (user && !user.disabled) redirect("/inbox");return (<AuthGuard mode="public">diff --git a/src/app/login/utils.ts b/src/app/login/utils.tsindex 650d999..848ccc1 100644--- a/src/app/login/utils.ts+++ b/src/app/login/utils.ts@@ -5,6 +5,7 @@ export async function submitLogin(form: FormData): Promise<{ ok: boolean; data:const res = await fetch("/api/auth/login", {method: "POST",headers: { "Content-Type": "application/json" },+ signal: AbortSignal.timeout(20_000),body: JSON.stringify({email: form.get("email"),password: form.get("password"),diff --git a/src/app/page.tsx b/src/app/page.tsxindex 66cb6cc..ca720ea 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -6,8 +6,10 @@ import { Button } from "@/components/ui/button";import { authFetch, getClientSessionToken } from "@/lib/auth/client";import { getHomeActions, heroMessages, sidebarItems } from "./utils";import { ArrowRight, Inbox, Mail, Search, ShieldCheck } from "lucide-react";+import { useBranding } from "@/components/branding-provider";export default function HomePage() {+ const branding = useBranding();const [hasUser, setHasUser] = useState(false);useEffect(() => {@@ -37,9 +39,9 @@ export default function HomePage() {className="flex items-center gap-3"aria-label="Email Platform home">- <img src="/icon-96.png" height={32} width={32} />+ <img src={branding.iconUrl} height={32} width={32} alt="" /><span className="text-base font-semibold tracking-tight">- Mailflare+ {branding.appName}</span></Link>diff --git a/src/app/register/register-client.tsx b/src/app/register/register-client.tsxindex a50685d..99cf48e 100644--- a/src/app/register/register-client.tsx+++ b/src/app/register/register-client.tsx@@ -216,7 +216,7 @@ export function RegisterClient() {)}</div>) : showDomainStep ? (- <form onSubmit={onDomainSubmit} className="space-y-5">+ <form method="post" onSubmit={onDomainSubmit} className="space-y-5"><div className="space-y-2"><Label htmlFor="domain">Primary domain</Label><Input@@ -244,7 +244,7 @@ export function RegisterClient() {</Button></form>) : (- <form onSubmit={onSubmit} className="space-y-5">+ <form method="post" onSubmit={onSubmit} className="space-y-5"><div className="space-y-2"><Label htmlFor="username">Username</Label><div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2 relative">diff --git a/src/app/setup/page.tsx b/src/app/setup/page.tsxindex b1d1fea..87ea74e 100644--- a/src/app/setup/page.tsx+++ b/src/app/setup/page.tsx@@ -4,7 +4,7 @@ import { AuthGuard } from "@/components/auth/auth-guard";import { SESSION_COOKIE, getUserFromSession } from "@/lib/auth/session";import { hasAdminAccount } from "@/lib/auth/setup";import { getEnv } from "@/lib/cloudflare";-import { userHasAccessibleMailboxes } from "@/lib/user";+import { getPrimaryDomain } from "@/lib/user";import { OnboardingClient } from "@/app/onboarding/onboarding-client";import { RegisterClient } from "@/app/register/register-client";@@ -13,6 +13,9 @@ export const dynamic = "force-dynamic";export default async function SetupPage() {const env = getEnv();if (!(await hasAdminAccount(env))) {+ const cookieStore = await cookies();+ const user = await getUserFromSession(env, cookieStore.get(SESSION_COOKIE)?.value);+ if (user && !user.disabled) redirect("/inbox");return (<AuthGuard mode="public"><RegisterClient />@@ -23,10 +26,11 @@ export default async function SetupPage() {const cookieStore = await cookies();const user = await getUserFromSession(env, cookieStore.get(SESSION_COOKIE)?.value);if (!user || user.disabled) redirect("/login");- if (await userHasAccessibleMailboxes(env, user)) redirect("/inbox");+ if (user.role !== "admin") redirect("/inbox");+ if (await getPrimaryDomain(env)) redirect("/inbox");return (- <AuthGuard>+ <AuthGuard requireRole="admin"><OnboardingClient /></AuthGuard>);diff --git a/src/components/admin-nav.tsx b/src/components/admin-nav.tsxindex cbb1ff1..aaf005d 100644--- a/src/components/admin-nav.tsx+++ b/src/components/admin-nav.tsx@@ -8,10 +8,14 @@ import {Activity,Mail,Settings,+ Palette,+ BadgeDollarSign,+ Users,} from "lucide-react";import { cn } from "@/lib/utils";import { NavItem } from "./components-nav";import { SidebarFooter } from "./sidebar-footer";+import { useBranding } from "./branding-provider";const links = [{ href: "/admin", label: "Overview", icon: Settings },@@ -19,12 +23,16 @@ const links = [{ href: "/domains", label: "Domains", icon: Globe2 },{ href: "/activity", label: "Activity", icon: Activity },{ href: "/backups", label: "Backups", icon: DatabaseBackup },+ { href: "/branding", label: "Branding", icon: Palette },+ { href: "/licenses", label: "Licenses", icon: BadgeDollarSign },+ { href: "/accounts", label: "Accounts", icon: Users },// { href: "/api-keys", label: "API Keys", icon: KeyRound },// { href: "/webhooks", label: "Webhooks", icon: Webhook }];export function AdminNav({ className }: { className?: string }) {const pathname = usePathname();+ const branding = useBranding();return (<nav className={cn("flex min-h-full flex-col gap-1", className)}>@@ -32,10 +40,12 @@ export function AdminNav({ className }: { className?: string }) {href="/inbox"className="mb-3 flex h-10 items-center gap-3 px-3 text-neutral-600">- <img src="/icon-96.png" height={28} width={28} />+ <img src={branding.iconUrl} height={28} width={28} alt="" /><span className="text-lg font-semibold text-neutral-800">Admin</span></Link>- {links.map((link) => <NavItem link={link} key={link.href} />)}+ {links+ .filter((link) => link.href !== "/branding" || branding.canCustomizeBranding)+ .map((link) => <NavItem link={link} key={link.href} />)}<span className="flex-1" /><SidebarFooter /></nav>diff --git a/src/components/auth/auth-guard.tsx b/src/components/auth/auth-guard.tsxindex 03d9e33..c1af6fb 100644--- a/src/components/auth/auth-guard.tsx+++ b/src/components/auth/auth-guard.tsx@@ -2,9 +2,9 @@import { usePathname, useRouter } from "next/navigation";import { useEffect, useState } from "react";-import { authFetch, getClientSessionToken } from "@/lib/auth/client";+import { authFetch } from "@/lib/auth/client";import type { AuthGuardProps } from "./auth-guard-types";-import { PageSkeleton } from "@/components/page-skeletons";+import { LoadingTransition } from "@/components/loading-transition";export function AuthGuard({ children, mode = "protected", requireMailbox, requireRole }: AuthGuardProps) {const pathname = usePathname();@@ -13,44 +13,52 @@ export function AuthGuard({ children, mode = "protected", requireMailbox, requiruseEffect(() => {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;+ try {+ const cookieResponse = await fetch("/api/auth/me", {+ cache: "no-store",+ signal: AbortSignal.timeout(5_000),+ });+ const response = cookieResponse.ok || cookieResponse.status !== 401+ ? cookieResponse+ : await authFetch("/api/auth/me", {+ redirectOnUnauthorized: false,+ signal: AbortSignal.timeout(5_000),+ });+ if (cancelled) return;- if (!response.ok) {- if (mode === "public") setAuthorized(true);- return;- }+ if (!response.ok) {+ if (mode === "protected" && response.status === 401) router.replace("/login");+ else setAuthorized(true);+ return;+ }- const data = (await response.json()) as { hasMailboxes?: boolean; user?: { role?: string } };- if (mode === "public") {- router.replace(data.hasMailboxes === false ? "/setup" : "/inbox");- return;- }+ const data = (await response.json()) as { hasMailboxes?: boolean; isSetup?: boolean; user?: { role?: string } };+ if (mode === "public") {+ router.replace("/inbox");+ return;+ }- if (requireMailbox && data.hasMailboxes === false && pathname !== "/setup") {- router.replace("/setup");- return;- }+ if (requireMailbox && data.hasMailboxes === false && data.user?.role === "admin" && data.isSetup === false && pathname !== "/setup") {+ router.replace("/setup");+ return;+ }- if (!requireMailbox && data.hasMailboxes && pathname === "/setup") {- router.replace("/inbox");- return;- }+ if (pathname === "/setup" && data.isSetup === true) {+ router.replace("/inbox");+ return;+ }- if (requireRole && data.user?.role !== requireRole) {- router.replace("/inbox");- return;- }+ if (requireRole && data.user?.role !== requireRole) {+ router.replace("/inbox");+ return;+ }- setAuthorized(true);+ setAuthorized(true);+ } catch {+ if (!cancelled) setAuthorized(true);+ }}void checkSession();@@ -60,6 +68,6 @@ export function AuthGuard({ children, mode = "protected", requireMailbox, requir};}, [mode, pathname, requireMailbox, requireRole, router]);- if (!authorized) return <PageSkeleton />;- return <>{children}</>;+ if (mode === "public") return <>{children}</>;+ return <LoadingTransition ready={authorized}>{children}</LoadingTransition>;}diff --git a/src/components/branding-provider-types.d.ts b/src/components/branding-provider-types.d.tsnew file mode 100644index 0000000..5e08031--- /dev/null+++ b/src/components/branding-provider-types.d.ts@@ -0,0 +1,6 @@+import type { Branding } from "@/lib/branding/types";++export type BrandingContextValue = Branding & {+ iconUrl: string;+ refreshBranding(): Promise<void>;+};diff --git a/src/components/branding-provider-utils.ts b/src/components/branding-provider-utils.tsnew file mode 100644index 0000000..10f8240--- /dev/null+++ b/src/components/branding-provider-utils.ts@@ -0,0 +1,13 @@+import type { Branding } from "@/lib/branding/types";++export const DEFAULT_BRANDING: Branding = {+ appName: "Mailflare",+ hasCustomIcon: false,+ canCustomizeBranding: false,+};++export async function fetchBranding(): Promise<Branding> {+ const response = await fetch("/api/branding", { cache: "no-store" });+ if (!response.ok) return DEFAULT_BRANDING;+ return (await response.json()) as Branding;+}diff --git a/src/components/branding-provider.tsx b/src/components/branding-provider.tsxnew file mode 100644index 0000000..a965be4--- /dev/null+++ b/src/components/branding-provider.tsx@@ -0,0 +1,43 @@+"use client";++import { createContext, useContext, useEffect, useState } from "react";+import type { BrandingContextValue } from "./branding-provider-types";+import { DEFAULT_BRANDING, fetchBranding } from "./branding-provider-utils";++const BrandingContext = createContext<BrandingContextValue | null>(null);++export function BrandingProvider({ children }: { children: React.ReactNode }) {+ const [branding, setBranding] = useState(DEFAULT_BRANDING);+ const [iconVersion, setIconVersion] = useState(0);++ async function refreshBranding() {+ const nextBranding = await fetchBranding();+ setBranding(nextBranding);+ setIconVersion(Date.now());+ if (document.title === "Mailflare" || document.title === branding.appName) {+ document.title = nextBranding.appName;+ }+ }++ useEffect(() => {+ void refreshBranding();+ }, []);++ return (+ <BrandingContext.Provider value={{+ ...branding,+ iconUrl: branding.hasCustomIcon ? `/api/branding/icon?v=${iconVersion}` : "/icon-96.png",+ refreshBranding,+ }}>+ {children}+ </BrandingContext.Provider>+ );+}++export function useBranding() {+ return useContext(BrandingContext) ?? {+ ...DEFAULT_BRANDING,+ iconUrl: "/icon-96.png",+ refreshBranding: async () => undefined,+ };+}diff --git a/src/components/components-nav-types.d.ts b/src/components/components-nav-types.d.tsindex cf44371..4ce6b97 100644--- a/src/components/components-nav-types.d.ts+++ b/src/components/components-nav-types.d.ts@@ -6,6 +6,7 @@ export type NavLink = {icon?: LucideIcon;iconColor?: string;primary?: boolean;+ preloadMessages?: boolean;count?: number;onMessageDrop?: (messageIds: string[]) => void;};diff --git a/src/components/components-nav-utils.ts b/src/components/components-nav-utils.tsnew file mode 100644index 0000000..214394a--- /dev/null+++ b/src/components/components-nav-utils.ts@@ -0,0 +1,21 @@+import { getMessageQueryParams, fetchMessageList } from "@/hooks/utils";+import type { MessageFolder } from "@/hooks/types";++export async function preloadMailboxPage(href: string, mailboxId?: string) {+ const customFolderMatch = href.match(/^\/folders\/([^/]+)$/);+ const folder = (customFolderMatch ? "inbox" : href.slice(1)) as MessageFolder;+ const supportedFolders: MessageFolder[] = ["inbox", "sent", "drafts", "archived", "spam", "trash"];+ if (!supportedFolders.includes(folder)) return;++ const params = getMessageQueryParams(+ folder,+ mailboxId,+ { limit: 25, offset: 0 },+ customFolderMatch?.[1],+ );+ await fetchMessageList(params);+}++export function waitForNavigationProgress(duration = 350) {+ return new Promise<void>((resolve) => window.setTimeout(resolve, duration));+}diff --git a/src/components/components-nav.tsx b/src/components/components-nav.tsxindex a602015..7a79844 100644--- a/src/components/components-nav.tsx+++ b/src/components/components-nav.tsx@@ -1,18 +1,30 @@import Link from "next/link";-import type { DragEvent } from "react";-import { useState } from "react";+import type { DragEvent, MouseEvent } from "react";+import { useEffect, useState } from "react";import { cn } from "@/lib/utils";-import { usePathname } from "next/navigation";+import { usePathname, useRouter } from "next/navigation";import { getMessageDragData } from "@/lib/messages/drag-utils";+import { useSelectedMailbox } from "./mailbox-provider";import { useCompose } from "./compose/compose-context";+import { preloadMailboxPage, waitForNavigationProgress } from "./components-nav-utils";import type { NavLink } from "./components-nav-types";export function NavItem({ link }:{ link: NavLink }) {const pathname = usePathname();+ const router = useRouter();const { openComposer } = useCompose();+ const { selectedMailbox } = useSelectedMailbox();const [dragOver, setDragOver] = useState(false);+ const [navigationProgress, setNavigationProgress] = useState<number | null>(null);++ useEffect(() => {+ if (navigationProgress === null) return;+ setNavigationProgress(100);+ const timer = window.setTimeout(() => setNavigationProgress(null), 220);+ return () => window.clearTimeout(timer);+ }, [pathname]);if (!link.href) {return <span className="flex-1" />;@@ -65,19 +77,53 @@ export function NavItem({ link }:{ link: NavLink }) {);}+ async function navigate(event: MouseEvent<HTMLAnchorElement>) {+ if (!link.preloadMessages || active || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;+ event.preventDefault();+ setNavigationProgress(12);+ const timer = window.setInterval(() => {+ setNavigationProgress((current) => current === null ? 12 : Math.min(90, current + 8));+ }, 80);+ try {+ router.prefetch(link.href!);+ await Promise.all([+ preloadMailboxPage(link.href!, selectedMailbox?.id),+ waitForNavigationProgress(),+ ]);+ setNavigationProgress(100);+ await waitForNavigationProgress(160);+ router.push(link.href!);+ } catch {+ setNavigationProgress(null);+ } finally {+ window.clearInterval(timer);+ }+ }+return (- <Link- href={link.href}- className={cn("-ml-3 pl-6", classes)}- {...dropProps}- >- <Icon className="h-4 w-4" style={{ color: link.iconColor }} />- <span className="flex-1">{link.label}</span>- {typeof link.count === "number" && link.count > 0 && (- <span className="ml-auto mr-3 rounded-full px-2 py-0.5 text-sm font-semibold text-neutral-700">- {link.count > 99 ? "99+" : link.count}- </span>+ <>+ {navigationProgress !== null && (+ <div className="fixed inset-x-0 top-0 z-[120] h-1 bg-blue-100">+ <div+ className="h-full bg-blue-600 transition-[width] duration-100 ease-out"+ style={{ width: `${navigationProgress}%` }}+ />+ </div>)}- </Link>+ <Link+ href={link.href}+ onClick={navigate}+ className={cn("-ml-3 pl-6", classes)}+ {...dropProps}+ >+ <Icon className="h-4 w-4" style={{ color: link.iconColor }} />+ <span className="flex-1">{link.label}</span>+ {typeof link.count === "number" && link.count > 0 && (+ <span className="ml-auto mr-3 rounded-full px-2 py-0.5 text-sm font-semibold text-neutral-700">+ {link.count > 99 ? "99+" : link.count}+ </span>+ )}+ </Link>+ </>);}diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsxindex 185ffe7..800248d 100644--- a/src/components/compose/compose-form.tsx+++ b/src/components/compose/compose-form.tsx@@ -37,6 +37,10 @@ export function ComposeForm({const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const attachmentInput = useRef<HTMLInputElement | null>(null);+ useEffect(() => {+ if (!selectedMailbox && mailboxes.length === 1) setSelectedMailbox(mailboxes[0]);+ }, [mailboxes, selectedMailbox, setSelectedMailbox]);+const fromAddr = useMemo(() =>selectedMailboxdiff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsxindex 7d66bb7..0f50434 100644--- a/src/components/dashboard-nav.tsx+++ b/src/components/dashboard-nav.tsx@@ -36,18 +36,20 @@ import type { NavLink } from "./components-nav-types";import type { CustomFolder } from "./dashboard-nav-types";import { getFolderNavCount, moveMessagesToCustomFolder, moveMessagesToSystemFolder } from "./dashboard-nav-utils";import { SidebarFooter } from "./sidebar-footer";+import { useBranding } from "./branding-provider";const links = [{ href: "/compose", label: "Compose", icon: MailPlus, primary: true },- { href: "/inbox", label: "Inbox", icon: Inbox },- { href: "/sent", label: "Sent", icon: Send },- { href: "/drafts", label: "Drafts", icon: FileText },- { href: "/archived", label: "Archived", icon: Archive },- { href: "/spam", label: "Spam", icon: ShieldAlert },- { href: "/trash", label: "Trash", icon: Trash2 },+ { href: "/inbox", label: "Inbox", icon: Inbox, preloadMessages: true },+ { href: "/sent", label: "Sent", icon: Send, preloadMessages: true },+ { href: "/drafts", label: "Drafts", icon: FileText, preloadMessages: true },+ { href: "/archived", label: "Archived", icon: Archive, preloadMessages: true },+ { href: "/spam", label: "Spam", icon: ShieldAlert, preloadMessages: true },+ { href: "/trash", label: "Trash", icon: Trash2, preloadMessages: true },];export function DashboardNav({ className }: { className?: string }) {+ const branding = useBranding();const { selectedMailbox, isLoading } = useSelectedMailbox();const { counts } = useMessageCounts(selectedMailbox?.id, !isLoading);const [folders, setFolders] = useState<CustomFolder[]>([]);@@ -143,8 +145,8 @@ export function DashboardNav({ className }: { className?: string }) {href="/inbox"className="mb-3 flex h-10 items-center gap-3 px-3 text-neutral-600">- <img src="/icon-96.png" height={28} width={28} />- <span className="text-lg font-semibold text-neutral-800">Mailflare</span>+ <img src={branding.iconUrl} height={28} width={28} alt="" />+ <span className="truncate text-lg font-semibold text-neutral-800">{branding.appName}</span></Link>{linksWithCounts.map((link, i) => <NavItem link={link} key={`nav-${link.href || i}`} />)}<div className="mt-2 flex h-8 items-center justify-between px-3">@@ -218,6 +220,7 @@ export function DashboardNav({ className }: { className?: string }) {href: `/folders/${folder.id}`,label: folder.name,icon: Folder,+ preloadMessages: true,iconColor: folder.color,count: counts.customFolders[folder.id]?.unread,onMessageDrop: (messageIds: string[]) => void moveMessagesToCustomFolder(messageIds, folder.id),diff --git a/src/components/dashboard-shell.tsx b/src/components/dashboard-shell.tsxindex eefd72d..a6341f9 100644--- a/src/components/dashboard-shell.tsx+++ b/src/components/dashboard-shell.tsx@@ -4,7 +4,7 @@ import { usePathname } from "next/navigation";import { AdminNav } from "@/components/admin-nav";import { DashboardNav } from "@/components/dashboard-nav";-const adminPrefixes = ["/admin", "/mailboxes", "/domains", "/api-keys", "/activity", "/audit-logs", "/webhooks"];+const adminPrefixes = ["/admin", "/mailboxes", "/domains", "/api-keys", "/activity", "/audit-logs", "/webhooks", "/branding", "/licenses"];export function DashboardShellNav() {const pathname = usePathname();diff --git a/src/components/license-indicator-types.d.ts b/src/components/license-indicator-types.d.tsnew file mode 100644index 0000000..9d80098--- /dev/null+++ b/src/components/license-indicator-types.d.ts@@ -0,0 +1,5 @@+import type { LicenseStatus } from "@/lib/licenses/types";++export type LicenseIndicatorResponse = {+ license?: LicenseStatus;+};diff --git a/src/components/license-indicator-utils.ts b/src/components/license-indicator-utils.tsnew file mode 100644index 0000000..c3dae30--- /dev/null+++ b/src/components/license-indicator-utils.ts@@ -0,0 +1,13 @@+import { authFetch } from "@/lib/auth/client";+import type { LicenseIndicatorResponse } from "./license-indicator-types";++export async function loadLicenseIndicatorStatus() {+ try {+ const response = await authFetch("/api/licenses", { redirectOnUnauthorized: false });+ if (!response.ok) return null;+ const data = (await response.json()) as LicenseIndicatorResponse;+ return data.license ?? null;+ } catch {+ return null;+ }+}diff --git a/src/components/license-indicator.tsx b/src/components/license-indicator.tsxnew file mode 100644index 0000000..39d4584--- /dev/null+++ b/src/components/license-indicator.tsx@@ -0,0 +1,48 @@+"use client";++import Link from "next/link";+import { useEffect, useState } from "react";+import { Button } from "@/components/ui/button";+import { LICENSE_STATUS_CHANGED_EVENT } from "@/lib/licenses/constants";+import type { LicenseStatus } from "@/lib/licenses/types";+import { loadLicenseIndicatorStatus } from "./license-indicator-utils";++export function LicenseIndicator() {+ const [license, setLicense] = useState<LicenseStatus | null>(null);++ useEffect(() => {+ let cancelled = false;++ function load() {+ void loadLicenseIndicatorStatus().then((nextLicense) => {+ if (!cancelled) setLicense(nextLicense);+ });+ }++ load();+ window.addEventListener(LICENSE_STATUS_CHANGED_EVENT, load);+ return () => {+ cancelled = true;+ window.removeEventListener(LICENSE_STATUS_CHANGED_EVENT, load);+ };+ }, []);++ if (!license) return null;++ if (license.active) {+ return (+ <Link+ href="/licenses"+ className="rounded-full bg-blue-100 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-blue-800 hover:bg-blue-200"+ >+ {license.plan}+ </Link>+ );+ }++ return (+ <Button asChild size="sm">+ <Link href="/licenses">Upgrade</Link>+ </Button>+ );+}diff --git a/src/components/loading-transition-types.d.ts b/src/components/loading-transition-types.d.tsnew file mode 100644index 0000000..d1ede3a--- /dev/null+++ b/src/components/loading-transition-types.d.ts@@ -0,0 +1,10 @@+import type { ReactNode } from "react";++export type LoadingTransitionProps = {+ children?: ReactNode;+ ready: boolean;+};++export type PageLoadingContextValue = {+ reportLoading(id: string, loading: boolean): void;+};diff --git a/src/components/loading-transition.tsx b/src/components/loading-transition.tsxnew file mode 100644index 0000000..f3899dc--- /dev/null+++ b/src/components/loading-transition.tsx@@ -0,0 +1,109 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useIsFetching } from "@tanstack/react-query";+import { useBranding } from "@/components/branding-provider";+import { PageLoadingContext } from "@/components/page-loading";+import type { LoadingTransitionProps } from "./loading-transition-types";++const MINIMUM_LOADING_TIME = 600;+const COMPLETION_TIME = 220;+const MAXIMUM_DATA_WAIT = 10_000;++export function LoadingTransition({ children, ready }: LoadingTransitionProps) {+ const branding = useBranding();+ const startedAt = useRef(Date.now());+ const [progress, setProgress] = useState(8);+ const [loaderVisible, setLoaderVisible] = useState(true);+ const [contentVisible, setContentVisible] = useState(false);+ const [iconUrl, setIconUrl] = useState(branding.iconUrl);+ const [pageMounted, setPageMounted] = useState(false);+ const [pendingLoads, setPendingLoads] = useState(0);+ const [dataWaitExpired, setDataWaitExpired] = useState(false);+ const loadingIds = useRef(new Set<string>());+ const fetchingQueries = useIsFetching();++ const reportLoading = useCallback((id: string, loading: boolean) => {+ if (loading) loadingIds.current.add(id);+ else loadingIds.current.delete(id);+ setPendingLoads(loadingIds.current.size);+ }, []);+ const loadingContext = useMemo(() => ({ reportLoading }), [reportLoading]);+ const canComplete = ready && pageMounted && (dataWaitExpired || (pendingLoads === 0 && fetchingQueries === 0));++ useEffect(() => {+ setIconUrl(branding.iconUrl);+ }, [branding.iconUrl]);++ useEffect(() => {+ if (canComplete) return;+ const timer = window.setInterval(() => {+ setProgress((current) => Math.min(92, current + Math.max(1, (92 - current) * 0.08)));+ }, 90);+ return () => window.clearInterval(timer);+ }, [canComplete]);++ useEffect(() => {+ if (!ready) return;+ const timer = window.setTimeout(() => setPageMounted(true), 50);+ return () => window.clearTimeout(timer);+ }, [ready]);++ useEffect(() => {+ if (!ready) return;+ const timer = window.setTimeout(() => setDataWaitExpired(true), MAXIMUM_DATA_WAIT);+ return () => window.clearTimeout(timer);+ }, [ready]);++ useEffect(() => {+ if (!canComplete) return;+ const remaining = Math.max(0, MINIMUM_LOADING_TIME - (Date.now() - startedAt.current));+ const completeTimer = window.setTimeout(() => setProgress(100), remaining);+ const revealTimer = window.setTimeout(() => {+ setLoaderVisible(false);+ setContentVisible(true);+ }, remaining + COMPLETION_TIME);+ return () => {+ window.clearTimeout(completeTimer);+ window.clearTimeout(revealTimer);+ };+ }, [canComplete]);++ return (+ <PageLoadingContext.Provider value={loadingContext}>+ <div className="relative min-h-dvh bg-[#f6f8fc]">+ {ready && (+ <div+ className={`min-h-dvh transition-opacity duration-300 ${contentVisible ? "opacity-100" : "opacity-0"}`}+ >+ {children}+ </div>+ )}+ <div+ aria-label="Loading"+ aria-live="polite"+ className={`fixed inset-0 z-[100] flex items-center justify-center bg-[#f6f8fc] transition-opacity duration-300 ${+ loaderVisible ? "opacity-100" : "pointer-events-none opacity-0"+ }`}+ >+ <div className="flex w-64 flex-col items-center gap-6">+ <img+ src={iconUrl}+ onError={() => setIconUrl("/icon-96.png")}+ alt={`${branding.appName} icon`}+ className="h-20 w-20 rounded-2xl object-contain"+ />+ <div className="w-full">+ <div className="h-1.5 overflow-hidden rounded-full bg-blue-100">+ <div+ className="h-full rounded-full bg-blue-600 transition-[width] duration-200 ease-out"+ style={{ width: `${progress}%` }}+ />+ </div>+ </div>+ </div>+ </div>+ </div>+ </PageLoadingContext.Provider>+ );+}diff --git a/src/components/mailbox-provider-utils.ts b/src/components/mailbox-provider-utils.tsindex 75ee190..f572a49 100644--- a/src/components/mailbox-provider-utils.ts+++ b/src/components/mailbox-provider-utils.ts@@ -1,15 +1,19 @@-import { authFetch } from "@/lib/auth/client";+import { authFetch, getClientSessionToken } from "@/lib/auth/client";import type { MailboxOption } from "./mailbox-provider";let mailboxesCache: MailboxOption[] | null = null;+let mailboxesCacheSessionToken: string | null = null;let mailboxesRequest: Promise<MailboxOption[]> | null = null;+let mailboxesRequestSessionToken: string | null = null;let cacheGeneration = 0;export const SELECTED_MAILBOX_STORAGE_KEY = "selected-mailbox-id";export function clearMailboxesCache() {cacheGeneration += 1;mailboxesCache = null;+ mailboxesCacheSessionToken = null;mailboxesRequest = null;+ mailboxesRequestSessionToken = null;}export function clearMailboxClientState() {@@ -20,10 +24,12 @@ export function clearMailboxClientState() {}export async function fetchMailboxOptions(force = false): Promise<MailboxOption[]> {- if (!force && mailboxesCache) return mailboxesCache;- if (!force && mailboxesRequest) return mailboxesRequest;+ const sessionToken = getClientSessionToken();+ if (!force && mailboxesCache && mailboxesCacheSessionToken === sessionToken) return mailboxesCache;+ if (!force && mailboxesRequest && mailboxesRequestSessionToken === sessionToken) return mailboxesRequest;const requestGeneration = cacheGeneration;+ mailboxesRequestSessionToken = sessionToken;mailboxesRequest = authFetch("/api/mailboxes").then((res) => res.json()).then((data) => {@@ -37,11 +43,17 @@ export async function fetchMailboxOptions(force = false): Promise<MailboxOption[permission: m.permission,isPrimary: m.isPrimary,}));- if (requestGeneration === cacheGeneration) mailboxesCache = items;+ if (requestGeneration === cacheGeneration) {+ mailboxesCache = items;+ mailboxesCacheSessionToken = sessionToken;+ }return items;}).finally(() => {- if (requestGeneration === cacheGeneration) mailboxesRequest = null;+ if (requestGeneration === cacheGeneration) {+ mailboxesRequest = null;+ mailboxesRequestSessionToken = null;+ }});return mailboxesRequest;diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsxindex 6c4795c..1a64a03 100644--- a/src/components/messages/message-folder-page.tsx+++ b/src/components/messages/message-folder-page.tsx@@ -9,6 +9,7 @@ import { SkeletonRows } from "@/components/ui/skeleton";import { useCompose } from "@/components/compose/compose-context";import { useMailSearch } from "@/components/mail-search/mail-search-context";import { useSelectedMailbox } from "@/components/mailbox-provider";+import { usePageLoading } from "@/components/page-loading";import { useMessageCounts } from "@/hooks/use-message-counts";import { useMessages } from "@/hooks/use-messages";import type { BulkMessageAction } from "@/app/api/messages/bulk/types";@@ -179,6 +180,7 @@ export function MessageFolderPage({offset,}, !mailboxesLoading, config.folderId);const { counts } = useMessageCounts(selectedMailbox?.id, !mailboxesLoading);+ usePageLoading(mailboxesLoading || isLoading);const headerIcons = config.headerIcons ?? [];const hasActiveFilters = !!query.trim();const folderCount = config.folderIddiff --git a/src/components/page-loading.tsx b/src/components/page-loading.tsxnew file mode 100644index 0000000..490b13d--- /dev/null+++ b/src/components/page-loading.tsx@@ -0,0 +1,16 @@+"use client";++import { createContext, useContext, useEffect, useId } from "react";+import type { PageLoadingContextValue } from "./loading-transition-types";++export const PageLoadingContext = createContext<PageLoadingContextValue | null>(null);++export function usePageLoading(loading: boolean) {+ const context = useContext(PageLoadingContext);+ const id = useId();++ useEffect(() => {+ context?.reportLoading(id, loading);+ return () => context?.reportLoading(id, false);+ }, [context, id, loading]);+}diff --git a/src/components/page-skeletons.tsx b/src/components/page-skeletons.tsxindex 7abfa0f..ba3a8ba 100644--- a/src/components/page-skeletons.tsx+++ b/src/components/page-skeletons.tsx@@ -1,25 +1,8 @@import { Skeleton, SkeletonRows } from "@/components/ui/skeleton";-import { MailOpen } from "lucide-react";+import { LoadingTransition } from "@/components/loading-transition";export function PageSkeleton() {- return (- <div className="space-y-7 p-8 flex flex-row items-center justify-center h-dvh w-dvw flex-1">- <div className="space-y-2">- <MailOpen size={86} className="animate-pulse text-blue-600/10" />- <Skeleton className="h-7 w-48" />- <Skeleton className="h-4 w-80 max-w-full" />- </div>- {/* <div className="grid gap-4 md:grid-cols-2">- {Array.from({ length: 4 }, (_, index) => (- <div key={index} className="rounded-lg border border-neutral-200 p-5">- <Skeleton className="h-10 w-10 rounded-lg" />- <Skeleton className="mt-4 h-4 w-32" />- <Skeleton className="mt-2 h-3 w-4/5" />- </div>- ))}- </div> */}- </div>- );+ return <LoadingTransition ready />;}export function ListPageSkeleton() {diff --git a/src/components/providers.tsx b/src/components/providers.tsxindex 9899809..25dd115 100644--- a/src/components/providers.tsx+++ b/src/components/providers.tsx@@ -3,6 +3,7 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { useEffect, useState } from "react";import { clearMailboxClientState } from "@/components/mailbox-provider-utils";+import { BrandingProvider } from "@/components/branding-provider";import { NewMessagePopup } from "@/components/new-message-popup";import { useMessagePolling } from "@/hooks/use-message-polling";import { clearMessageClientState } from "@/hooks/utils";@@ -38,13 +39,15 @@ export function Providers({ children }: { children: React.ReactNode }) {return (<QueryClientProvider client={client}>- {children}- {realtime.notification && (- <NewMessagePopup- notification={realtime.notification}- onDismiss={realtime.dismissNotification}- />- )}+ <BrandingProvider>+ {children}+ {realtime.notification && (+ <NewMessagePopup+ notification={realtime.notification}+ onDismiss={realtime.dismissNotification}+ />+ )}+ </BrandingProvider></QueryClientProvider>);}diff --git a/src/components/settings/account-settings.tsx b/src/components/settings/account-settings.tsxnew file mode 100644index 0000000..65a2cb1--- /dev/null+++ b/src/components/settings/account-settings.tsx@@ -0,0 +1,76 @@+"use client";++import { useEffect, useState } from "react";+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import { Skeleton } from "@/components/ui/skeleton";+import { ChangePasswordForm } from "./change-password-form";+import { ProfileForm } from "./profile-form";+import type { AccountSettingsResponse } from "./types";+import { loadAccountSettings } from "./utils";++export function AccountSettings() {+ const [user, setUser] = useState<AccountSettingsResponse["user"]>();+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;++ loadAccountSettings()+ .then((nextUser) => {+ if (!cancelled) setUser(nextUser);+ })+ .catch((err) => {+ if (!cancelled) setError(err instanceof Error ? err.message : "Failed to load account");+ });++ return () => {+ cancelled = true;+ };+ }, []);++ if (error) {+ return <p className="py-8 text-sm text-red-600">{error}</p>;+ }++ if (!user) {+ return (+ <div className="space-y-6 py-4">+ <Skeleton className="h-9 w-40" />+ <Skeleton className="h-72 w-full rounded-3xl" />+ </div>+ );+ }++ return (+ <div className="space-y-8 py-4">+ <div>+ <h1 className="text-3xl font-medium text-neutral-900">Account</h1>+ <p className="mt-1 text-sm text-neutral-500">Manage your account details and sign-in password.</p>+ </div>++ <Card className="rounded-3xl border-0 bg-white px-6">+ <CardHeader>+ <CardTitle>Account details</CardTitle>+ <CardDescription>Your current email is assigned to this account and cannot be changed here.</CardDescription>+ </CardHeader>+ <CardContent className="pb-6">+ <ProfileForm+ initialName={user.name}+ initialResetEmail={user.resetEmail ?? ""}+ email={user.email}+ />+ </CardContent>+ </Card>++ <Card className="rounded-3xl border-0 bg-white px-6">+ <CardHeader>+ <CardTitle>Change password</CardTitle>+ <CardDescription>Use at least 8 characters for your new password.</CardDescription>+ </CardHeader>+ <CardContent className="pb-6">+ <ChangePasswordForm />+ </CardContent>+ </Card>+ </div>+ );+}diff --git a/src/components/settings/change-password-form.tsx b/src/components/settings/change-password-form.tsxnew file mode 100644index 0000000..415cd9e--- /dev/null+++ b/src/components/settings/change-password-form.tsx@@ -0,0 +1,84 @@+"use client";++import { useState } from "react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { updatePassword } from "./utils";++export function ChangePasswordForm() {+ const [currentPassword, setCurrentPassword] = useState("");+ const [newPassword, setNewPassword] = useState("");+ const [confirmPassword, setConfirmPassword] = useState("");+ const [status, setStatus] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);++ async function onSubmit(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault();+ setStatus(null);++ if (newPassword !== confirmPassword) {+ setStatus("New passwords do not match");+ return;+ }++ setLoading(true);+ try {+ await updatePassword(currentPassword, newPassword);+ setCurrentPassword("");+ setNewPassword("");+ setConfirmPassword("");+ setStatus("Password changed");+ } catch (err) {+ setStatus(err instanceof Error ? err.message : "Failed to change password");+ } finally {+ setLoading(false);+ }+ }++ return (+ <form onSubmit={onSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="currentPassword">Current password</Label>+ <Input+ id="currentPassword"+ type="password"+ autoComplete="current-password"+ value={currentPassword}+ onChange={(event) => setCurrentPassword(event.target.value)}+ required+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="newPassword">New password</Label>+ <Input+ id="newPassword"+ type="password"+ autoComplete="new-password"+ value={newPassword}+ onChange={(event) => setNewPassword(event.target.value)}+ minLength={8}+ required+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="confirmPassword">Confirm new password</Label>+ <Input+ id="confirmPassword"+ type="password"+ autoComplete="new-password"+ value={confirmPassword}+ onChange={(event) => setConfirmPassword(event.target.value)}+ minLength={8}+ required+ />+ </div>+ <div className="flex items-center gap-3">+ <Button type="submit" disabled={loading}>+ {loading ? "Changing..." : "Change password"}+ </Button>+ {status && <p className="text-sm text-neutral-500">{status}</p>}+ </div>+ </form>+ );+}diff --git a/src/components/settings/profile-form.tsx b/src/components/settings/profile-form.tsxindex de21772..5063ace 100644--- a/src/components/settings/profile-form.tsx+++ b/src/components/settings/profile-form.tsx@@ -21,30 +21,39 @@ export function ProfileForm({ initialName, initialResetEmail, email }: ProfileFosetLoading(true);setStatus(null);- const res = await authFetch("/api/settings/profile", {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name, resetEmail }),- });- const data = (await res.json()) as ProfileFormResponse;- setLoading(false);+ try {+ const res = await authFetch("/api/settings/profile", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name, resetEmail }),+ });+ const data = (await res.json()) as ProfileFormResponse;- if (!res.ok) {- setStatus(typeof data.error === "string" ? data.error : "Failed to update account");- return;- }+ if (!res.ok) {+ 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");+ const nextName = data.user?.name ?? name.trim();+ const nextResetEmail = data.user?.resetEmail ?? "";+ setName(nextName);+ setResetEmail(nextResetEmail);+ setSavedName(nextName);+ setSavedResetEmail(nextResetEmail);+ setStatus("Saved");+ } catch (err) {+ setStatus(err instanceof Error ? err.message : "Failed to update account");+ } finally {+ setLoading(false);+ }}return (<form onSubmit={onSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="accountEmail">Current email</Label>+ <Input id="accountEmail" value={email} type="email" readOnly aria-readonly="true" className="bg-neutral-50" />+ </div><div className="space-y-2"><Label htmlFor="name">Name</Label><Input id="name" value={name} onChange={(event) => setName(event.target.value)} required />@@ -59,10 +68,6 @@ export function ProfileForm({ initialName, initialResetEmail, email }: ProfileFoplaceholder="[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 || !hasChanges}>{loading ? "Saving..." : "Save"}diff --git a/src/components/settings/types.d.ts b/src/components/settings/types.d.tsindex be65ca4..63c087b 100644--- a/src/components/settings/types.d.ts+++ b/src/components/settings/types.d.ts@@ -12,6 +12,19 @@ export type ProfileFormResponse = {error?: unknown;};+export type AccountSettingsResponse = {+ user?: {+ email: string;+ name: string;+ resetEmail: string | null;+ };+ error?: unknown;+};++export type ChangePasswordResponse = {+ error?: unknown;+};+export type ProfileAvatarSessionResponse = {user?: {hasAvatar?: boolean;diff --git a/src/components/settings/utils.ts b/src/components/settings/utils.tsindex 8acaf96..db688bc 100644--- a/src/components/settings/utils.ts+++ b/src/components/settings/utils.ts@@ -2,6 +2,7 @@ import type { MailboxOption } from "@/components/mailbox-provider";import { clearMailboxesCache } from "@/components/mailbox-provider-utils";import { authFetch } from "@/lib/auth/client";import type { CurrentMailboxFormResponse } from "./types";+import type { AccountSettingsResponse, ChangePasswordResponse } from "./types";export function getMailboxAddress(mailbox: Pick<MailboxOption, "localPart" | "hostname">): string {return `${mailbox.localPart}@${mailbox.hostname}`;@@ -29,3 +30,27 @@ export async function updateCurrentMailboxName(id: string, displayName: string):isPrimary: data.mailbox.isPrimary,};}++export async function loadAccountSettings(): Promise<Required<AccountSettingsResponse>["user"]> {+ const res = await authFetch("/api/auth/me");+ const data = (await res.json()) as AccountSettingsResponse;++ if (!res.ok || !data.user) {+ throw new Error(typeof data.error === "string" ? data.error : "Failed to load account");+ }++ return data.user;+}++export async function updatePassword(currentPassword: string, newPassword: string): Promise<void> {+ const res = await authFetch("/api/settings/password", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ currentPassword, newPassword }),+ });+ const data = (await res.json()) as ChangePasswordResponse;++ if (!res.ok) {+ throw new Error(typeof data.error === "string" ? data.error : "Failed to change password");+ }+}diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex bf80d14..2f1eb57 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -10,6 +10,7 @@ export const users = sqliteTable("users", {avatarKey: text("avatar_key"),role: text("role", { enum: ["admin", "user"] }).notNull().default("user"),disabled: integer("disabled", { mode: "boolean" }).notNull().default(false),+ canManageMailboxes: integer("can_manage_mailboxes", { mode: "boolean" }).notNull().default(false),createdByUserId: text("created_by_user_id").references((): AnySQLiteColumn => users.id, { onDelete: "set null" }),createdAt: integer("created_at", { mode: "timestamp" }).notNull()@@ -327,6 +328,32 @@ export const backupSettings = sqliteTable("backup_settings", {.$defaultFn(() => new Date()),});+export const appSettings = sqliteTable("app_settings", {+ id: text("id").primaryKey(),+ appName: text("app_name").notNull().default("Mailflare"),+ iconKey: text("icon_key"),+ updatedAt: integer("updated_at", { mode: "timestamp" })+ .notNull()+ .$defaultFn(() => new Date()),+});++export const licenseSettings = sqliteTable("license_settings", {+ id: text("id").primaryKey(),+ instanceId: text("instance_id").notNull().unique(),+ instanceUrl: text("instance_url"),+ licenseKeyHash: text("license_key_hash"),+ plan: text("plan", { enum: ["community", "pro", "team"] }).notNull().default("community"),+ state: text("state", { enum: ["inactive", "active", "invalid", "expired", "deactivated"] })+ .notNull()+ .default("inactive"),+ features: text("features").notNull().default("[]"),+ activatedAt: integer("activated_at", { mode: "timestamp" }),+ validatedAt: integer("validated_at", { mode: "timestamp" }),+ updatedAt: integer("updated_at", { mode: "timestamp" })+ .notNull()+ .$defaultFn(() => new Date()),+});+export const backups = sqliteTable("backups",{@@ -371,4 +398,6 @@ export const schema = {auditLogs,backupSettings,backups,+ appSettings,+ licenseSettings,};diff --git a/src/lib/auth/turnstile.ts b/src/lib/auth/turnstile.tsindex 220c3d5..aedf32f 100644--- a/src/lib/auth/turnstile.ts+++ b/src/lib/auth/turnstile.ts@@ -14,16 +14,22 @@ export async function verifyTurnstileToken(if (!secret) return true;if (typeof token !== "string" || !token.trim() || token.length > 2048) return false;- const response = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- secret,- response: token,- remoteip: request.headers.get("cf-connecting-ip") ?? undefined,- idempotency_key: newId("ts"),- }),- });+ let response: Response;+ try {+ response = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ signal: AbortSignal.timeout(10_000),+ body: JSON.stringify({+ secret,+ response: token,+ remoteip: request.headers.get("cf-connecting-ip") ?? undefined,+ idempotency_key: newId("ts"),+ }),+ });+ } catch {+ return false;+ }if (!response.ok) return false;const result = (await response.json()) as TurnstileResponse;diff --git a/src/lib/auth/types.d.ts b/src/lib/auth/types.d.tsindex 0db405a..809ca1d 100644--- a/src/lib/auth/types.d.ts+++ b/src/lib/auth/types.d.ts@@ -8,6 +8,7 @@ export type SessionUser = {name: string;role: UserRole;disabled: boolean;+ canManageMailboxes: boolean;createdByUserId: string | null;createdAt: Date;};diff --git a/src/lib/branding/service.ts b/src/lib/branding/service.tsnew file mode 100644index 0000000..275a08a--- /dev/null+++ b/src/lib/branding/service.ts@@ -0,0 +1,64 @@+import { eq } from "drizzle-orm";+import { getDb } from "@/db";+import { appSettings } from "@/db/schema";+import type { Branding } from "./types";+import { getLicenseEntitlements } from "@/lib/licenses/service";++export const APP_SETTINGS_ID = "default";+export const DEFAULT_APP_NAME = "Mailflare";+export const BRANDING_ICON_KEY = "branding/app-icon";++export async function getBranding(env: CloudflareEnv): Promise<Branding> {+ const entitlements = await getLicenseEntitlements(env);+ if (!entitlements.canCustomizeBranding) {+ return { appName: DEFAULT_APP_NAME, hasCustomIcon: false, canCustomizeBranding: false };+ }++ try {+ const [settings] = await getDb(env)+ .select()+ .from(appSettings)+ .where(eq(appSettings.id, APP_SETTINGS_ID))+ .limit(1);+ return {+ appName: settings?.appName || DEFAULT_APP_NAME,+ hasCustomIcon: !!settings?.iconKey,+ canCustomizeBranding: true,+ };+ } catch {+ return { appName: DEFAULT_APP_NAME, hasCustomIcon: false, canCustomizeBranding: true };+ }+}++export async function updateBranding(+ env: CloudflareEnv,+ input: { appName: string; icon?: File | null },+): Promise<Branding> {+ if (!(await getLicenseEntitlements(env)).canCustomizeBranding) {+ throw new Error("A Pro or Team license is required to customize branding");+ }+ let iconKey: string | undefined;+ if (input.icon) {+ iconKey = BRANDING_ICON_KEY;+ await env.BUCKET.put(iconKey, await input.icon.arrayBuffer(), {+ httpMetadata: { contentType: input.icon.type },+ });+ }++ await getDb(env)+ .insert(appSettings)+ .values({+ id: APP_SETTINGS_ID,+ appName: input.appName,+ iconKey: iconKey ?? null,+ })+ .onConflictDoUpdate({+ target: appSettings.id,+ set: {+ appName: input.appName,+ ...(iconKey ? { iconKey } : {}),+ updatedAt: new Date(),+ },+ });+ return getBranding(env);+}diff --git a/src/lib/branding/types.d.ts b/src/lib/branding/types.d.tsnew file mode 100644index 0000000..e0619a7--- /dev/null+++ b/src/lib/branding/types.d.ts@@ -0,0 +1,5 @@+export type Branding = {+ appName: string;+ hasCustomIcon: boolean;+ canCustomizeBranding: boolean;+};diff --git a/src/lib/licenses/constants.ts b/src/lib/licenses/constants.tsnew file mode 100644index 0000000..6075207--- /dev/null+++ b/src/lib/licenses/constants.ts@@ -0,0 +1,8 @@+import type { LicensePlan } from "./types";++export const LICENSE_PRODUCT_IDS: Record<Exclude<LicensePlan, "community">, string> = {+ pro: "ebafa58f-af9f-4b8a-a48d-6cfd44dd2053",+ team: "6e42b54c-3221-4f8f-93a7-bab494f9e224",+};++export const LICENSE_STATUS_CHANGED_EVENT = "mailflare:license-status-changed";diff --git a/src/lib/licenses/paymug.ts b/src/lib/licenses/paymug.tsnew file mode 100644index 0000000..1f0e5f4--- /dev/null+++ b/src/lib/licenses/paymug.ts@@ -0,0 +1,46 @@+import type { LicenseActivationInput, LicenseDeactivationInput, PaymugLicenseAction, PaymugLicenseResponse } from "./types";+import { parsePaymugLicenseResponse } from "./utils";++export const PAYMUG_BASE_URL = "https://app.paymug.co";++export async function callPaymugLicenseApi(+ action: PaymugLicenseAction,+ input: LicenseActivationInput | LicenseDeactivationInput,+): Promise<PaymugLicenseResponse> {+ let response: Response;++ console.log(input);++ try {+ response = await fetch(`${PAYMUG_BASE_URL}/api/v1/licenses/${action}`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ signal: AbortSignal.timeout(15_000),+ });+ } catch {+ throw new Error("Unable to reach Paymug. Try again later.");+ }++ const rs = await response.json()+ console.log('response', rs);++ if (!response.ok) {+ if (response.status === 409) {+ throw new Error("This license is active on another installation. Deactivate it there before retrying.");+ }+ if (response.status === 401 || response.status === 403) {+ throw new Error("Paymug rejected this license key.");+ }+ if (response.status >= 500) {+ throw new Error("Paymug is temporarily unavailable. Try again later.");+ }+ throw new Error("Paymug could not process this license request.");+ }++ try {+ return parsePaymugLicenseResponse(rs);+ } catch {+ throw new Error("Paymug returned an invalid license response");+ }+}diff --git a/src/lib/licenses/service.ts b/src/lib/licenses/service.tsnew file mode 100644index 0000000..252265a--- /dev/null+++ b/src/lib/licenses/service.ts@@ -0,0 +1,158 @@+import { eq } from "drizzle-orm";+import packageJson from "../../../package.json";+import { getDb } from "@/db";+import { licenseSettings } from "@/db/schema";+import { LICENSE_PRODUCT_IDS } from "./constants";+import { callPaymugLicenseApi } from "./paymug";+import type { LicenseEntitlements, LicensePlan, LicenseStatus, PaymugLicenseAction } from "./types";+import { hashLicenseKey, normalizeLicensePlan, parseFeatures } from "./utils";++const LICENSE_SETTINGS_ID = "default";++async function getOrCreateLicenseSettings(env: CloudflareEnv) {+ const db = getDb(env);+ await db+ .insert(licenseSettings)+ .values({ id: LICENSE_SETTINGS_ID, instanceId: crypto.randomUUID() })+ .onConflictDoNothing({ target: licenseSettings.id });+ const [settings] = await db+ .select()+ .from(licenseSettings)+ .where(eq(licenseSettings.id, LICENSE_SETTINGS_ID))+ .limit(1);+ if (!settings) throw new Error("Unable to initialize license settings");+ return settings;+}++function toLicenseStatus(settings: typeof licenseSettings.$inferSelect): LicenseStatus {+ const active = settings.state === "active" && (settings.plan === "pro" || settings.plan === "team");+ return {+ plan: active ? settings.plan : "community",+ state: settings.state,+ features: parseFeatures(settings.features),+ instanceId: settings.instanceId,+ instanceUrl: settings.instanceUrl,+ active,+ activatedAt: settings.activatedAt,+ validatedAt: settings.validatedAt,+ };+}++export async function getLicenseStatus(env: CloudflareEnv): Promise<LicenseStatus> {+ return toLicenseStatus(await getOrCreateLicenseSettings(env));+}++export async function getLicenseEntitlements(env: CloudflareEnv): Promise<LicenseEntitlements> {+ try {+ const status = await getLicenseStatus(env);+ // TODO: confirm Paymug's exact feature identifiers when they are documented; plan is authoritative meanwhile.+ return {+ plan: status.plan,+ canCustomizeBranding: status.active && (status.plan === "pro" || status.plan === "team"),+ canManageAccounts: status.active && status.plan === "team",+ };+ } catch {+ return { plan: "community", canCustomizeBranding: false, canManageAccounts: false };+ }+}++async function updateLicenseFromPaymug(+ env: CloudflareEnv,+ action: PaymugLicenseAction,+ licenseKey: string,+ instanceUrl: string,+ requestedPlan?: Exclude<LicensePlan, "community">,+): Promise<LicenseStatus> {+ const settings = await getOrCreateLicenseSettings(env);+ const licenseKeyHash = licenseKey ? await hashLicenseKey(licenseKey) : null;+ if (action === "validate" && (!licenseKeyHash || settings.licenseKeyHash !== licenseKeyHash)) {+ throw new Error("This key does not match the activated license");+ }+++ const expectedPlan = action === "activate"+ ? requestedPlan+ : settings.plan === "pro" || settings.plan === "team"+ ? settings.plan+ : null;+ if (!expectedPlan) throw new Error("Choose the license product to activate");++ const result = await callPaymugLicenseApi(+ action,+ action === "deactivate"+ ? { productId: LICENSE_PRODUCT_IDS[expectedPlan], instanceId: settings.instanceId }+ : {+ licenseKey,+ productId: LICENSE_PRODUCT_IDS[expectedPlan],+ instanceId: settings.instanceId,+ instanceUrl: action === "activate" ? instanceUrl : settings.instanceUrl ?? instanceUrl,+ appVersion: packageJson.version,+ },+ );+ const now = new Date();+ const db = getDb(env);++ if (action === "deactivate") {+ if (result.state !== "deactivated") throw new Error("Paymug did not confirm deactivation");+ await db+ .update(licenseSettings)+ .set({+ licenseKeyHash: null,+ plan: "community",+ state: "deactivated",+ features: "[]",+ validatedAt: now,+ updatedAt: now,+ })+ .where(eq(licenseSettings.id, LICENSE_SETTINGS_ID));+ return getLicenseStatus(env);+ }++ const responsePlan = normalizeLicensePlan(result.productId, result.plan);+ const plan = expectedPlan;+ const responseDoesNotMatch = (!!result.productId && responsePlan === null)+ || (!!result.productId && responsePlan !== expectedPlan);+ if (!result.valid || result.state !== "active" || responseDoesNotMatch) {+ if (action === "validate") {+ await db+ .update(licenseSettings)+ .set({ state: result.state === "active" ? "invalid" : result.state, validatedAt: now, updatedAt: now })+ .where(eq(licenseSettings.id, LICENSE_SETTINGS_ID));+ }+ throw new Error(result.state === "expired" ? "This license has expired" : "This license is not valid for this installation");+ }++ await db+ .update(licenseSettings)+ .set({+ licenseKeyHash: licenseKeyHash ?? settings.licenseKeyHash,+ instanceUrl: action === "activate" ? instanceUrl : settings.instanceUrl,+ instanceId: result.instanceId ?? settings.instanceId,+ plan,+ state: "active",+ features: JSON.stringify(result.features ?? []),+ activatedAt: action === "activate" ? now : settings.activatedAt,+ validatedAt: now,+ updatedAt: now,+ })+ .where(eq(licenseSettings.id, LICENSE_SETTINGS_ID));++ return getLicenseStatus(env);+}++export function activateLicense(+ env: CloudflareEnv,+ licenseKey: string,+ instanceUrl: string,+ plan: Exclude<LicensePlan, "community">,+) {+ return updateLicenseFromPaymug(env, "activate", licenseKey, instanceUrl, plan);+}++export function validateLicense(env: CloudflareEnv, licenseKey: string, instanceUrl: string) {+ return updateLicenseFromPaymug(env, "validate", licenseKey, instanceUrl);+}++export function deactivateLicense(env: CloudflareEnv) {+ return updateLicenseFromPaymug(env, "deactivate", "", "");+}diff --git a/src/lib/licenses/types.d.ts b/src/lib/licenses/types.d.tsnew file mode 100644index 0000000..3b7aef6--- /dev/null+++ b/src/lib/licenses/types.d.ts@@ -0,0 +1,44 @@+export type LicensePlan = "community" | "pro" | "team";++export type LicenseState = "inactive" | "active" | "invalid" | "expired" | "deactivated";++export type PaymugLicenseAction = "activate" | "validate" | "deactivate";++export type PaymugLicenseResponse = {+ valid: boolean;+ state: Exclude<LicenseState, "inactive">;+ instanceId?: string;+ productId?: string;+ plan?: string;+ features?: string[];+};++export type LicenseStatus = {+ plan: LicensePlan;+ state: LicenseState;+ features: string[];+ instanceId: string;+ instanceUrl: string | null;+ active: boolean;+ activatedAt: Date | null;+ validatedAt: Date | null;+};++export type LicenseActivationInput = {+ licenseKey: string;+ productId: string;+ instanceId: string;+ instanceUrl: string;+ appVersion: string;+};++export type LicenseDeactivationInput = {+ productId: string;+ instanceId: string;+};++export type LicenseEntitlements = {+ plan: LicensePlan;+ canCustomizeBranding: boolean;+ canManageAccounts: boolean;+};diff --git a/src/lib/licenses/utils.ts b/src/lib/licenses/utils.tsnew file mode 100644index 0000000..713ebc1--- /dev/null+++ b/src/lib/licenses/utils.ts@@ -0,0 +1,50 @@+import type { LicensePlan, LicenseState, PaymugLicenseResponse } from "./types";+import { LICENSE_PRODUCT_IDS } from "./constants";++export async function hashLicenseKey(licenseKey: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(licenseKey));+ return Array.from(new Uint8Array(digest))+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+}++export function parseFeatures(value: string): string[] {+ try {+ const parsed = JSON.parse(value);+ return Array.isArray(parsed) ? parsed.filter((feature): feature is string => typeof feature === "string") : [];+ } catch {+ return [];+ }+}++export function parsePaymugLicenseResponse(value: unknown): PaymugLicenseResponse {+ if (!value || typeof value !== "object") throw new Error("Paymug returned an invalid license response");+ const response = value as Record<string, unknown>;+ const states: LicenseState[] = ["active", "invalid", "expired", "deactivated"];++ if (typeof response.valid !== "boolean" || !states.includes(response.state as LicenseState)) {+ throw new Error("Paymug returned an invalid license response");+ }++ return {+ valid: response.valid,+ state: response.state as PaymugLicenseResponse["state"],+ instanceId: typeof response.instanceId === "string" ? response.instanceId : undefined,+ productId: typeof response.productId === "string" ? response.productId : undefined,+ plan: typeof response.plan === "string" ? response.plan : undefined,+ features: Array.isArray(response.features)+ ? response.features.filter((feature): feature is string => typeof feature === "string")+ : undefined,+ };+}++export function normalizeLicensePlan(productId: string | undefined, plan: string | undefined): LicensePlan | null {+ if (productId) {+ if (productId === LICENSE_PRODUCT_IDS.pro) return "pro";+ if (productId === LICENSE_PRODUCT_IDS.team) return "team";+ return null;+ }++ const normalized = plan?.trim().toLowerCase();+ return normalized === "pro" || normalized === "team" ? normalized : null;+}diff --git a/src/lib/mailboxes/access.ts b/src/lib/mailboxes/access.tsindex 6e7d375..c6a134d 100644--- a/src/lib/mailboxes/access.ts+++ b/src/lib/mailboxes/access.ts@@ -1,7 +1,6 @@import { and, eq } from "drizzle-orm";import type { AppDatabase } from "@/db";import { domains, mailboxes } from "@/db/schema";-import { isAdmin } from "@/lib/auth/admin";import type { SessionUser } from "@/lib/auth/types";import type { MailboxAccessLevel, MailboxPermission } from "./types";@@ -24,8 +23,7 @@ export async function getMailboxAccessLevel(const [mailbox] = await db.select().from(mailboxes).where(eq(mailboxes.id, mailboxId)).limit(1);if (!mailbox || mailbox.disabled) return null;- const [domain] = await db.select().from(domains).where(eq(domains.id, mailbox.domainId)).limit(1);- const isOwner = mailbox.userId === user.id || (isAdmin(user) && domain?.userId === user.id);+ const isOwner = mailbox.userId === user.id;if (isOwner) return buildAccess(mailbox, "full_access", true);return null;@@ -44,17 +42,11 @@ export async function listAccessibleMailboxes(db: AppDatabase, user: Pick<Sessiodisabled: mailboxes.disabled,createdAt: mailboxes.createdAt,hostname: domains.hostname,- domainUserId: domains.userId,}).from(mailboxes)- .innerJoin(domains, eq(mailboxes.domainId, domains.id));+ .innerJoin(domains, eq(mailboxes.domainId, domains.id))+ .where(and(eq(mailboxes.userId, user.id), eq(mailboxes.disabled, false)));return rows- .filter((row) => {- if (row.disabled) return false;- if (row.userId === user.id) return true;- if (isAdmin(user) && row.domainUserId === user.id) return true;- return false;- }).map((row) => {const { avatarKey, ...mailbox } = row;return {diff --git a/src/lib/setup/migration.ts b/src/lib/setup/migration.tsindex e8fd888..6ba04d2 100644--- a/src/lib/setup/migration.ts+++ b/src/lib/setup/migration.ts@@ -11,10 +11,12 @@ const MIGRATION_NAMES = ["0009_add_backups.sql","0010_hard_squirrel_girl.sql","0011_add_folder_colors.sql",+ "0012_add_app_settings.sql",+ "0014_add_account_permissions.sql",];const INITIAL_SCHEMA_SQL = `-CREATE TABLE IF NOT EXISTS users (id text PRIMARY KEY NOT NULL, email text NOT NULL UNIQUE, reset_email text, password_hash text NOT NULL, name text NOT NULL, avatar_key text, role text DEFAULT 'user' NOT NULL, disabled integer DEFAULT false NOT NULL, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);+CREATE TABLE IF NOT EXISTS users (id text PRIMARY KEY NOT NULL, email text NOT NULL UNIQUE, reset_email text, password_hash text NOT NULL, name text NOT NULL, avatar_key text, role text DEFAULT 'user' NOT NULL, disabled integer DEFAULT false NOT NULL, can_manage_mailboxes integer DEFAULT false NOT NULL, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);CREATE INDEX IF NOT EXISTS users_created_by_idx ON users(created_by_user_id);CREATE TABLE IF NOT EXISTS domains (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, hostname text NOT NULL, zone_id text NOT NULL, status text DEFAULT 'pending' NOT NULL, routing_status text, sending_subdomain_tag text, sending_enabled integer DEFAULT false NOT NULL, routing_enabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);CREATE UNIQUE INDEX IF NOT EXISTS domains_hostname_idx ON domains(hostname);@@ -54,6 +56,8 @@ INSERT OR IGNORE INTO backup_settings (id, enabled, schedule_type, retention_enaCREATE TABLE IF NOT EXISTS backups (id text PRIMARY KEY NOT NULL, status text DEFAULT 'queued' NOT NULL, trigger text NOT NULL, r2_key text, filename text, size integer, error text, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL, started_at integer, completed_at integer);CREATE INDEX IF NOT EXISTS backups_created_idx ON backups(created_at);CREATE INDEX IF NOT EXISTS backups_status_idx ON backups(status);+CREATE TABLE IF NOT EXISTS app_settings (id text PRIMARY KEY NOT NULL, app_name text DEFAULT 'Mailflare' NOT NULL, icon_key text, updated_at integer NOT NULL);+INSERT OR IGNORE INTO app_settings (id, app_name, updated_at) VALUES ('default', 'Mailflare', unixepoch());CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);`;diff --git a/src/lib/validators.ts b/src/lib/validators.tsindex d5bbbe9..3ba1bec 100644--- a/src/lib/validators.ts+++ b/src/lib/validators.ts@@ -60,11 +60,19 @@ export const domainSchema = z.object({export const mailboxSchema = z.object({domainId: z.string().min(1),+ ownerUserId: z.string().min(1).optional(),localPart: z.string().min(1).max(64),displayName: z.string().optional(),type: z.enum(["personal", "shared"]).optional(),});+export const updateManagedAccountSchema = z.object({+ name: z.string().trim().min(1).max(100),+ role: z.enum(["admin", "user"]),+ disabled: z.boolean(),+ canManageMailboxes: z.boolean(),+});+export const createAccountSchema = z.object({domainId: z.string().min(1),username: z.string().min(1).max(64).regex(/^[a-zA-Z0-9._%+-]+$/),@@ -76,6 +84,13 @@ export const createAccountSchema = z.object({),});+export const createUserAccountSchema = z.object({+ username: z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._%+-]+$/),+ domainId: z.string().min(1),+ password: z.string().min(8).max(128),+ role: z.enum(["admin", "user"]).default("user"),+});+export const updateAccountSchema = z.object({email: z.string().email().optional(),name: z.string().trim().min(1).max(100),@@ -120,6 +135,11 @@ export const updateProfileSchema = z.object({),});+export const changePasswordSchema = z.object({+ currentPassword: z.string().min(1),+ newPassword: z.string().min(8).max(128),+});+export const routingRuleSchema = z.object({domainId: z.string().optional(),pattern: z.string().trim().min(1).max(200).optional(),