diff --git a/src/app/(admin)/branding/page.tsx b/src/app/(admin)/branding/page.tsx index b31774f67..797063d3d 100644 --- a/src/app/(admin)/branding/page.tsx +++ b/src/app/(admin)/branding/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import Link from "next/link"; import { ArrowRight, ExternalLink, ImagePlus, LockKeyhole, Palette } from "@/components/icons"; import { useLanguage } from "@/components/language-provider"; @@ -20,6 +20,7 @@ export default function BrandingPage() { const [status, setStatus] = useState(null); const [saving, setSaving] = useState(false); const inputRef = useRef(null); + const previewRef = useRef(null); const [syncedAppName, setSyncedAppName] = useState(branding.appName); // Reset the field whenever the saved name changes. @@ -28,6 +29,11 @@ export default function BrandingPage() { setAppName(branding.appName); } + // Free the preview's object URL when leaving the page. + useEffect(() => () => { + if (previewRef.current) URL.revokeObjectURL(previewRef.current); + }, []); + if (!branding.canCustomizeBranding) { return (
@@ -52,8 +58,13 @@ export default function BrandingPage() { function pickIcon(file: File | null) { setIcon(file); - if (preview) URL.revokeObjectURL(preview); - setPreview(file ? URL.createObjectURL(file) : null); + setPreviewUrl(file ? URL.createObjectURL(file) : null); + } + + function setPreviewUrl(url: string | null) { + if (previewRef.current) URL.revokeObjectURL(previewRef.current); + previewRef.current = url; + setPreview(url); } async function submit(event: React.FormEvent) { @@ -64,6 +75,9 @@ export default function BrandingPage() { await saveBranding(appName.trim(), icon); await branding.refreshBranding(); setIcon(null); + // Drop the preview and the file input's value so the same file can be chosen again. + setPreviewUrl(null); + if (inputRef.current) inputRef.current.value = ""; setStatus(t("branding.updated")); } catch (error) { setStatus(error instanceof Error ? error.message : t("branding.saveFailed")); diff --git a/src/app/(auth)/onboarding/onboarding-client.tsx b/src/app/(auth)/onboarding/onboarding-client.tsx index dc9e57803..8900f550c 100644 --- a/src/app/(auth)/onboarding/onboarding-client.tsx +++ b/src/app/(auth)/onboarding/onboarding-client.tsx @@ -43,43 +43,46 @@ export function OnboardingClient() { setLoading(true); setError(null); - const normalized = hostname.toLowerCase().trim(); - let checkedDomain = domainCheck; - let sendingRequested = enableSending; - if (skipDns) { - checkedDomain = { hostname: normalized, zone: { id: "manual", name: normalized } }; - } else if (checkedDomain?.hostname !== normalized) { - const result = await checkDomain(normalized); - if (!result.ok || !result.domain) { - setLoading(false); - setError(result.error ?? t("onboarding.domainCheckFailed")); + try { + const normalized = hostname.toLowerCase().trim(); + let checkedDomain = domainCheck; + let sendingRequested = enableSending; + if (skipDns) { + checkedDomain = { hostname: normalized, zone: { id: "manual", name: normalized } }; + } else if (checkedDomain?.hostname !== normalized) { + const result = await checkDomain(normalized); + if (!result.ok || !result.domain) { + setError(result.error ?? t("onboarding.domainCheckFailed")); + return; + } + checkedDomain = result.domain; + sendingRequested = false; + setDomainCheck(result.domain); + setEnableSending(sendingRequested); + } + if (!checkedDomain) { + setError(t("onboarding.domainCheckFailed")); return; } - checkedDomain = result.domain; - sendingRequested = false; - setDomainCheck(result.domain); - setEnableSending(sendingRequested); - } - if (!checkedDomain) { - setLoading(false); - setError(t("onboarding.domainCheckFailed")); - return; - } - const { ok, data } = await createDomain(checkedDomain.hostname, skipDns ? true : sendingRequested, replaceMxRecords, skipDns); - setLoading(false); - if (!ok || !data.domain) { - if (data.code === "MX_RECORDS_CONFLICT") { - setMxConflict(true); - setError(null); + const { ok, data } = await createDomain(checkedDomain.hostname, skipDns ? true : sendingRequested, replaceMxRecords, skipDns); + if (!ok || !data.domain) { + if (data.code === "MX_RECORDS_CONFLICT") { + setMxConflict(true); + setError(null); + return; + } + setError(data.error ?? t("onboarding.addDomainFailed")); return; } - setError(data.error ?? t("onboarding.addDomainFailed")); - return; + setMxConflict(false); + setDomainId(data.domain.id); + setStep(2); + } catch { + setError(t("auth.serverUnreachable")); + } finally { + setLoading(false); } - setMxConflict(false); - setDomainId(data.domain.id); - setStep(2); } async function inspectDomain() { @@ -89,30 +92,42 @@ export function OnboardingClient() { setDomainChecking(true); setError(null); setMxConflict(false); - const result = await checkDomain(normalized); - setDomainChecking(false); - if (!result.ok || !result.domain) { + try { + const result = await checkDomain(normalized); + if (!result.ok || !result.domain) { + setDomainCheck(null); + setEnableSending(false); + setError(result.error ?? t("onboarding.domainCheckFailed")); + return; + } + + setDomainCheck(result.domain); + setEnableSending(false); + } catch { setDomainCheck(null); setEnableSending(false); - setError(result.error ?? t("onboarding.domainCheckFailed")); - return; + setError(t("auth.serverUnreachable")); + } finally { + setDomainChecking(false); } - - setDomainCheck(result.domain); - setEnableSending(false); } async function addMailbox() { setLoading(true); setError(null); - const { ok, data } = await createMailbox(domainId, localPart); - setLoading(false); - if (!ok) { - setError(data.error ?? t("onboarding.createMailboxFailed")); - return; + try { + const { ok, data } = await createMailbox(domainId, localPart); + if (!ok) { + setError(data.error ?? t("onboarding.createMailboxFailed")); + return; + } + router.push("/inbox"); + } catch { + setError(t("auth.serverUnreachable")); + } finally { + setLoading(false); } - router.push("/inbox"); } return ( diff --git a/src/app/(auth)/onboarding/utils.ts b/src/app/(auth)/onboarding/utils.ts index 2c65b0405..46a194770 100644 --- a/src/app/(auth)/onboarding/utils.ts +++ b/src/app/(auth)/onboarding/utils.ts @@ -1,3 +1,4 @@ +import { readResponseJson } from "@/lib/http/response"; import { authFetch } from "@/lib/auth/client"; import type { DomainCreateResult, @@ -8,7 +9,7 @@ import type { export async function getDomains(): Promise { const res = await authFetch("/api/domains"); - return (await res.json()) as DomainListResult; + return (await readResponseJson(res)) as DomainListResult; } export async function checkDomain(hostname: string): Promise { @@ -17,7 +18,7 @@ export async function checkDomain(hostname: string): Promise; + const data = (await readResponseJson(res)) as Omit; return { ok: res.ok, ...data }; } @@ -35,7 +36,7 @@ export async function createDomain( return { ok: res.ok, - data: (await res.json()) as DomainCreateResult, + data: (await readResponseJson(res)) as DomainCreateResult, }; } @@ -51,6 +52,6 @@ export async function createMailbox( return { ok: res.ok, - data: (await res.json()) as MailboxCreateResult, + data: (await readResponseJson(res)) as MailboxCreateResult, }; } diff --git a/src/app/(auth)/register/register-client.tsx b/src/app/(auth)/register/register-client.tsx index fea648a14..3288596b4 100644 --- a/src/app/(auth)/register/register-client.tsx +++ b/src/app/(auth)/register/register-client.tsx @@ -132,36 +132,40 @@ export function RegisterClient() { setLoading(true); setError(null); - const hostname = String(new FormData(e.currentTarget).get("domain") ?? "").toLowerCase().trim(); - if (skipDns) { - const { ok, data } = await submitPrimaryDomain(hostname, true); - setLoading(false); + try { + const hostname = String(new FormData(e.currentTarget).get("domain") ?? "").toLowerCase().trim(); + if (skipDns) { + const { ok, data } = await submitPrimaryDomain(hostname, true); + if (!ok || !data.domain) { + setError(typeof data.error === "string" ? data.error : t("setup.domainFailed")); + return; + } + setSetupDomain(data.domain.hostname); + setSetupEnableSending(true); + setSetupSkipDns(true); + setStep(3); + return; + } + setSetupSkipDns(false); + const usedCachedCheck = domainCheck?.hostname === hostname; + const result: { ok: boolean; data: DomainSetupResult } = usedCachedCheck + ? { ok: true, data: { domain: domainCheck } } + : await submitPrimaryDomain(hostname); + const { ok, data } = result; if (!ok || !data.domain) { - setError(typeof data.error === "string" ? data.error : t("setup.domainFailed")); + setError( + typeof data.error === "string" ? data.error : t("setup.domainFailed"), + ); return; } setSetupDomain(data.domain.hostname); - setSetupEnableSending(true); - setSetupSkipDns(true); + setSetupEnableSending(usedCachedCheck ? enableSending : false); setStep(3); - return; - } - setSetupSkipDns(false); - const usedCachedCheck = domainCheck?.hostname === hostname; - const result: { ok: boolean; data: DomainSetupResult } = usedCachedCheck - ? { ok: true, data: { domain: domainCheck } } - : await submitPrimaryDomain(hostname); - const { ok, data } = result; - setLoading(false); - if (!ok || !data.domain) { - setError( - typeof data.error === "string" ? data.error : t("setup.domainFailed"), - ); - return; + } catch { + setError(t("auth.serverUnreachable")); + } finally { + setLoading(false); } - setSetupDomain(data.domain.hostname); - setSetupEnableSending(usedCachedCheck ? enableSending : false); - setStep(3); } async function onDomainBlur(e: React.FocusEvent) { @@ -170,17 +174,24 @@ export function RegisterClient() { setDomainChecking(true); setError(null); - const { ok, data } = await submitPrimaryDomain(hostname); - setDomainChecking(false); - if (!ok || !data.domain) { + try { + const { ok, data } = await submitPrimaryDomain(hostname); + if (!ok || !data.domain) { + setDomainCheck(null); + setEnableSending(false); + setError(typeof data.error === "string" ? data.error : t("setup.domainCheckFailed")); + return; + } + + setDomainCheck(data.domain); + setEnableSending(false); + } catch { setDomainCheck(null); setEnableSending(false); - setError(typeof data.error === "string" ? data.error : t("setup.domainCheckFailed")); - return; + setError(t("auth.serverUnreachable")); + } finally { + setDomainChecking(false); } - - setDomainCheck(data.domain); - setEnableSending(false); } async function onSubmit(e: React.FormEvent) { @@ -188,41 +199,46 @@ export function RegisterClient() { setLoading(true); setError(null); - const form = new FormData(e.currentTarget); - const domain = setupDomain ?? primaryDomain; - if (!domain) { - setLoading(false); - setError(t("setup.domainIncomplete")); - return; - } + try { + const form = new FormData(e.currentTarget); + const domain = setupDomain ?? primaryDomain; + if (!domain) { + setError(t("setup.domainIncomplete")); + return; + } - const { ok, data } = await submitRegistration(form, { - firstRun: true, - domain, - enableSending: setupDomain - ? setupEnableSending - : primaryDomainSendingRequested ?? undefined, - replaceMxRecords, - skipDns: setupDomain ? setupSkipDns : undefined, - }); - setLoading(false); - if (!ok) { - if (data.code === "MX_RECORDS_CONFLICT") { - setMxRecordsExist(true); - setReplaceMxRecords(false); - setError(null); + const { ok, data } = await submitRegistration(form, { + firstRun: true, + domain, + enableSending: setupDomain + ? setupEnableSending + : primaryDomainSendingRequested ?? undefined, + replaceMxRecords, + skipDns: setupDomain ? setupSkipDns : undefined, + }); + if (!ok) { + if (data.code === "MX_RECORDS_CONFLICT") { + setMxRecordsExist(true); + setReplaceMxRecords(false); + setError(null); + setTurnstileReset((value) => value + 1); + return; + } + setError( + data.code === "passkey_unavailable" + ? t("authError.passkeyUnavailable") + : typeof data.error === "string" ? data.error : t("setup.registrationFailed"), + ); setTurnstileReset((value) => value + 1); return; } - setError( - data.code === "passkey_unavailable" - ? t("authError.passkeyUnavailable") - : typeof data.error === "string" ? data.error : t("setup.registrationFailed"), - ); + window.location.assign(data.redirect ?? "/login"); + } catch { + setError(t("auth.serverUnreachable")); setTurnstileReset((value) => value + 1); - return; + } finally { + setLoading(false); } - window.location.assign(data.redirect ?? "/login"); } const showDomainStep = hasPrimaryDomain === false && step === 2; diff --git a/src/app/(auth)/register/utils.ts b/src/app/(auth)/register/utils.ts index ba1eb890f..b7675c377 100644 --- a/src/app/(auth)/register/utils.ts +++ b/src/app/(auth)/register/utils.ts @@ -1,3 +1,4 @@ +import { readResponseJson } from "@/lib/http/response"; import { clearClientSessionToken } from "@/lib/auth/client"; import type { DomainSetupResult, @@ -11,14 +12,14 @@ export async function prepareSetup(): Promise<{ ok: boolean; data: SetupPreparat const res = await fetch("/api/setup/prepare", { method: "POST" }); return { ok: res.ok, - data: (await res.json()) as SetupPreparationResult, + data: (await readResponseJson(res)) as SetupPreparationResult, }; } export async function getSetupStatus(): Promise { const res = await fetch("/api/setup/status"); - const data = (await res.json()) as SetupStatus; - if (!res.ok) throw new Error(data.error ?? "Could not load setup status"); + const data = (await readResponseJson(res)) as SetupStatus; + if (!res.ok || typeof data.hasAdminAccount !== "boolean") throw new Error(data.error ?? "Could not load setup status"); return data; } @@ -31,7 +32,7 @@ export async function submitPrimaryDomain(hostname: string, skipDns = false): Pr return { ok: res.ok, - data: (await res.json()) as DomainSetupResult, + data: (await readResponseJson(res)) as DomainSetupResult, }; } @@ -44,7 +45,7 @@ export async function checkExistingMx(hostname: string): Promise<{ ok: boolean; return { ok: res.ok, - data: (await res.json()) as MxCheckResult, + data: (await readResponseJson(res)) as MxCheckResult, }; } @@ -78,7 +79,7 @@ export async function submitRegistration( ), }); - const data = (await res.json()) as RegisterResult; + const data = (await readResponseJson(res)) as RegisterResult; if (res.ok) clearClientSessionToken(); return { ok: res.ok, data }; } diff --git a/src/app/(drive)/drive-cache.ts b/src/app/(drive)/drive-cache.ts index 4508e113b..0f1d29b54 100644 --- a/src/app/(drive)/drive-cache.ts +++ b/src/app/(drive)/drive-cache.ts @@ -1,3 +1,4 @@ +import { AUTH_SESSION_CHANGED_EVENT } from "@/lib/auth/client"; import type { DriveCrumb, DriveItemDto, DriveRole } from "@/lib/drive/types"; export type DriveListing = { items: DriveItemDto[]; path: DriveCrumb[]; role: DriveRole; storageUsed: number; storageLimit: number | null }; @@ -21,3 +22,8 @@ export function saveDriveListing(key: string, listing: DriveListing) { export function clearDriveListings() { listings.clear(); } + +// A listing belongs to the account that fetched it; sign-out and account switches do not reload the page. +if (typeof window !== "undefined") { + window.addEventListener(AUTH_SESSION_CHANGED_EVENT, clearDriveListings); +} diff --git a/src/app/(drive)/drive-share-dialog.tsx b/src/app/(drive)/drive-share-dialog.tsx index c37c4d3d2..e562b61a2 100644 --- a/src/app/(drive)/drive-share-dialog.tsx +++ b/src/app/(drive)/drive-share-dialog.tsx @@ -31,12 +31,21 @@ export function DriveShareDialog({ item, onClose, onChanged }: { item: DriveItem useEffect(() => { if (!id) return; + // A slow response for an earlier item must not fill in the item shown now. + let active = true; void authFetch(`/api/drive/items/${id}/shares`).then(async (response) => { - if (!response.ok) return toast.error(t("drive.shareFailed")); + if (!response.ok) { + if (active) toast.error(t("drive.shareFailed")); + return; + } const data = await response.json() as { shares: DriveShareDto[]; linkToken: string | null }; + if (!active) return; setShares(data.shares); setLinkToken(data.linkToken); + }).catch(() => { + if (active) toast.error(t("drive.shareFailed")); }); + return () => { active = false; }; }, [id, t]); async function request(input: string, init: RequestInit) { diff --git a/src/app/api/settings/profile/route.ts b/src/app/api/settings/profile/route.ts index 0e7350f42..61fa8b0a8 100644 --- a/src/app/api/settings/profile/route.ts +++ b/src/app/api/settings/profile/route.ts @@ -29,11 +29,13 @@ export async function PATCH(request: Request) { return NextResponse.json({ error: "A Pro or Team license is required for email forwarding" }, { status: 403 }); } const forwardingEmail = parsed.forwardingEmail === undefined ? user.forwardingEmail : parsed.forwardingEmail; - await syncPersonalIdentity(db, { - userId: user.id, - name: parsed.name, - avatarKey: user.avatarKey, - }); + if (parsed.name !== undefined) { + await syncPersonalIdentity(db, { + userId: user.id, + name: parsed.name, + avatarKey: user.avatarKey, + }); + } await db .update(users) .set({ resetEmail: parsed.resetEmail, forwardingEmail }) @@ -43,7 +45,7 @@ export async function PATCH(request: Request) { user: { id: user.id, email: user.email, - name: parsed.name, + name: parsed.name ?? user.name, resetEmail: parsed.resetEmail, forwardingEmail, canForwardEmail, diff --git a/src/components/auth/turnstile.tsx b/src/components/auth/turnstile.tsx index 975ea03c9..9fee61aa9 100644 --- a/src/components/auth/turnstile.tsx +++ b/src/components/auth/turnstile.tsx @@ -26,7 +26,10 @@ function loadTurnstileScript(): Promise { if (existing) { return existing.dataset.loaded === "true" ? Promise.resolve() - : new Promise((resolve) => existing.addEventListener("load", () => resolve(), { once: true })); + : new Promise((resolve, reject) => { + existing.addEventListener("load", () => resolve(), { once: true }); + existing.addEventListener("error", () => reject(new Error("Turnstile failed to load")), { once: true }); + }); } return new Promise((resolve, reject) => { @@ -39,7 +42,11 @@ function loadTurnstileScript(): Promise { script.dataset.loaded = "true"; resolve(); }); - script.addEventListener("error", () => reject(new Error("Turnstile failed to load"))); + script.addEventListener("error", () => { + // Leave no dead script behind, or later mounts would wait on it forever. + script.remove(); + reject(new Error("Turnstile failed to load")); + }); document.head.appendChild(script); }); } @@ -69,6 +76,8 @@ export function TurnstileField({ "expired-callback": () => setToken(""), "error-callback": () => setToken(""), }); + }).catch(() => { + // The widget stays empty; a later mount retries the load. }); return () => { diff --git a/src/components/contacts/contact-edit-dialog.tsx b/src/components/contacts/contact-edit-dialog.tsx index 2dbef5a0c..72e90e3fd 100644 --- a/src/components/contacts/contact-edit-dialog.tsx +++ b/src/components/contacts/contact-edit-dialog.tsx @@ -63,6 +63,8 @@ function ContactEditForm({ const editing = contact !== null; const [email, setEmail] = useState(contact?.email ?? ""); const [displayName, setDisplayName] = useState(contact?.displayName ?? ""); + // `contact` is the snapshot taken when the dialog opened, so the photo flag is tracked here. + const [hasAvatar, setHasAvatar] = useState(contact?.hasAvatar ?? false); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); @@ -97,8 +99,11 @@ function ContactEditForm({ mailboxId={mailboxId} address={contact.email} name={displayName} - hasAvatar={contact.hasAvatar} - onAvatarChange={(hasAvatar) => onSaved({ ...contact, hasAvatar })} + hasAvatar={hasAvatar} + onAvatarChange={(next) => { + setHasAvatar(next); + onSaved({ ...contact, hasAvatar: next }); + }} /> )}
diff --git a/src/components/follow-ups/due-follow-ups.tsx b/src/components/follow-ups/due-follow-ups.tsx index e95060a1b..9d3d5bc49 100644 --- a/src/components/follow-ups/due-follow-ups.tsx +++ b/src/components/follow-ups/due-follow-ups.tsx @@ -1,7 +1,7 @@ "use client"; import Link from "next/link"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { BellRing, Check } from "@/components/icons"; import { useLanguage } from "@/components/language-provider"; import { Tooltip } from "@/components/ui/tooltip"; @@ -19,8 +19,14 @@ export function DueFollowUps({ mailboxId }: { mailboxId?: string | null }) { const [items, setItems] = useState([]); const [failed, setFailed] = useState(false); + const latestRequest = useRef(0); + const load = useCallback(() => { - void fetchDueFollowUps(mailboxId).then(setItems).catch(() => undefined); + // Only the newest request may set state, so a slow response for a previous mailbox is dropped. + const request = ++latestRequest.current; + void fetchDueFollowUps(mailboxId) + .then((next) => { if (request === latestRequest.current) setItems(next); }) + .catch(() => undefined); }, [mailboxId]); useEffect(() => { diff --git a/src/components/follow-ups/message-follow-up-status.tsx b/src/components/follow-ups/message-follow-up-status.tsx index 2496640cc..b5b16a8f7 100644 --- a/src/components/follow-ups/message-follow-up-status.tsx +++ b/src/components/follow-ups/message-follow-up-status.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { BellRing, Check } from "@/components/icons"; import { useLanguage } from "@/components/language-provider"; import type { MessageFollowUp } from "@/lib/follow-ups/types"; @@ -17,8 +17,14 @@ export function MessageFollowUpStatus({ messageId }: { messageId: string }) { const [followUp, setFollowUp] = useState(undefined); const [failed, setFailed] = useState(false); + const latestRequest = useRef(0); + const load = useCallback(() => { - void fetchMessageFollowUp(messageId).then(setFollowUp).catch(() => setFollowUp(null)); + // Only the newest request may set state, so a slow response for another message is dropped. + const request = ++latestRequest.current; + void fetchMessageFollowUp(messageId) + .then((next) => { if (request === latestRequest.current) setFollowUp(next); }) + .catch(() => { if (request === latestRequest.current) setFollowUp(null); }); }, [messageId]); useEffect(() => { diff --git a/src/components/icons.tsx b/src/components/icons.tsx index daf42c1cc..c8220607f 100644 --- a/src/components/icons.tsx +++ b/src/components/icons.tsx @@ -1,4 +1,5 @@ import { createElement, forwardRef, type ComponentType, type SVGProps } from "react"; +import { cn } from "@/lib/utils"; import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react"; import { ActivityIcon as HugeActivityIcon, @@ -244,9 +245,10 @@ export const FileWarning = createIcon(HugeFileExclamationPointIcon, "FileWarning export const Folder = createIcon(HugeFolderIcon, "Folder"); export const FolderInput = createIcon(HugeFolderInputIcon, "FolderInput"); export const FolderPlus = createIcon(HugeFolderPlusIcon, "FolderPlus"); -export const Forward = function (props) { - return createElement(createIcon(HugeReplyIcon, "Forward"), {...props, className: `${props.className} scale-x-[-1]`}); -} +// Created once: building the icon component inside render gives React a new type every time and remounts the SVG. +const ForwardBase = createIcon(HugeReplyIcon, "Forward"); +export const Forward: LucideIcon = (props) => + createElement(ForwardBase, { ...props, className: cn(props.className, "scale-x-[-1]") }); export const Globe2 = createIcon(HugeGlobeIcon, "Globe2"); export const HardDrive = createIcon(HugeHardDriveIcon, "HardDrive"); export const HelpCircle = createIcon(HugeHelpCircleIcon, "HelpCircle"); diff --git a/src/components/mailbox-provider.tsx b/src/components/mailbox-provider.tsx index 8a16d0e86..b7e866ee5 100644 --- a/src/components/mailbox-provider.tsx +++ b/src/components/mailbox-provider.tsx @@ -5,6 +5,7 @@ import { useCallback, useContext, useEffect, + useRef, useState, } from "react"; import type { ReactNode } from "react"; @@ -20,6 +21,7 @@ import { } from "@/lib/auth/client"; import { PROFILE_NAME_CHANGED_EVENT } from "@/lib/profile/name-client"; import { PROFILE_AVATAR_CHANGED_EVENT } from "@/lib/profile/avatar-client"; +import type { AuthSessionChangedDetail } from "@/lib/auth/client-types"; import type { ProfileNameChangedDetail } from "@/lib/profile/types"; export type MailboxOption = { @@ -59,13 +61,16 @@ export function MailboxProvider({ children }: { children: ReactNode }) { const [selectedMailbox, setSelectedMailboxState] = useState(null); const [isLoading, setIsLoading] = useState(true); - useEffect(() => { - let cancelled = false; + const loadId = useRef(0); + + const loadMailboxes = useCallback(() => { + const id = ++loadId.current; const sessionToken = getClientSessionToken(); + const isCurrent = () => id === loadId.current && sessionToken === getClientSessionToken(); fetchMailboxOptions() .then((items) => { - if (cancelled || sessionToken !== getClientSessionToken()) return; + if (!isCurrent()) return; setMailboxes(items); const storedId = localStorage.getItem(SELECTED_MAILBOX_STORAGE_KEY); @@ -85,24 +90,32 @@ export function MailboxProvider({ children }: { children: ReactNode }) { }) .catch(() => {}) .finally(() => { - if (!cancelled && sessionToken === getClientSessionToken()) setIsLoading(false); + if (isCurrent()) setIsLoading(false); }); + }, []); + useEffect(() => { + loadMailboxes(); return () => { - cancelled = true; + // Invalidate any request still in flight. + loadId.current += 1; }; - }, []); + }, [loadMailboxes]); useEffect(() => { - function resetMailboxState() { + function resetMailboxState(event: Event) { setMailboxes([]); setSelectedMailboxState(null); setIsLoading(true); + // Signing out has no mailboxes to load. + if ((event as CustomEvent).detail?.authenticated === false) return; + // The provider outlives an account switch, so load the new account's mailboxes. + loadMailboxes(); } window.addEventListener(AUTH_SESSION_CHANGED_EVENT, resetMailboxState); return () => window.removeEventListener(AUTH_SESSION_CHANGED_EVENT, resetMailboxState); - }, []); + }, [loadMailboxes]); useEffect(() => { function updatePersonalMailboxNames(event: Event) { diff --git a/src/components/settings/account-settings.tsx b/src/components/settings/account-settings.tsx index c0840aec5..c71470481 100644 --- a/src/components/settings/account-settings.tsx +++ b/src/components/settings/account-settings.tsx @@ -59,7 +59,6 @@ export function AccountSettings() {
diff --git a/src/components/settings/import-messages-utils.ts b/src/components/settings/import-messages-utils.ts index 727519367..3b1955274 100644 --- a/src/components/settings/import-messages-utils.ts +++ b/src/components/settings/import-messages-utils.ts @@ -23,8 +23,11 @@ export async function importMessageFiles( if (event.lengthComputable) onProgress?.(Math.round((event.loaded / event.total) * 100)); }; request.onerror = () => reject(new Error("Import upload failed")); + request.onabort = () => reject(new Error("Import upload cancelled")); + request.ontimeout = () => reject(new Error("Import upload timed out")); request.onload = () => { - const data = JSON.parse(request.responseText || "{}") as ImportMessagesResult; + // A proxy can answer with an HTML error page; fall through to the status check. + const data = parseImportResponse(request.responseText); if (request.status < 200 || request.status >= 300) { reject(new Error(data.error ?? "Import failed")); return; @@ -34,3 +37,12 @@ export async function importMessageFiles( request.send(form); }); } + +function parseImportResponse(text: string): ImportMessagesResult { + try { + const data: unknown = JSON.parse(text || "{}"); + return data && typeof data === "object" ? (data as ImportMessagesResult) : {}; + } catch { + return {}; + } +} diff --git a/src/components/settings/profile-form.tsx b/src/components/settings/profile-form.tsx index a4dce6616..95243e95d 100644 --- a/src/components/settings/profile-form.tsx +++ b/src/components/settings/profile-form.tsx @@ -14,7 +14,6 @@ import type { ProfileFormProps, ProfileFormResponse } from "./types"; import { getMailboxAddress, updateCurrentMailboxName } from "./utils"; export function ProfileForm({ - accountName, initialResetEmail, }: ProfileFormProps) { const { t } = useLanguage(); @@ -42,12 +41,12 @@ export function ProfileForm({ // account itself, so the recovery email applies to it alone. const isPrimary = !!selectedMailbox?.isPrimary && selectedMailbox.type === "personal"; - async function saveProfile(nextName: string, nextResetEmail: string) { + async function saveProfile(nextResetEmail: string) { try { const res = await authFetch("/api/settings/profile", { method: "PATCH", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ name: nextName, resetEmail: nextResetEmail }), + body: JSON.stringify({ resetEmail: nextResetEmail }), }); const data = (await res.json()) as ProfileFormResponse; @@ -96,7 +95,7 @@ export function ProfileForm({ setSavingRecovery(true); setRecoveryStatus(null); try { - await saveProfile(accountName, resetEmail); + await saveProfile(resetEmail); setRecoveryStatus(t("common.saved")); } catch (error) { setRecoveryStatus( diff --git a/src/components/settings/takeout-import.tsx b/src/components/settings/takeout-import.tsx index 979a290e1..87915e8af 100644 --- a/src/components/settings/takeout-import.tsx +++ b/src/components/settings/takeout-import.tsx @@ -71,6 +71,9 @@ export function TakeoutImport() { }; }, [running]); + // Leaving the page must stop the upload loop; progress is saved, so the import can be resumed later. + useEffect(() => () => controllerRef.current?.abort(), []); + function destinationLabel(key: string): string { const [type, ...rest] = key.split(":"); const value = rest.join(":"); diff --git a/src/components/settings/types.d.ts b/src/components/settings/types.d.ts index 5bd54ead3..df783c5f6 100644 --- a/src/components/settings/types.d.ts +++ b/src/components/settings/types.d.ts @@ -1,5 +1,4 @@ export type ProfileFormProps = { - accountName: string; initialResetEmail: string; }; diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.ts index c40b83520..445721b63 100644 --- a/src/hooks/use-messages.ts +++ b/src/hooks/use-messages.ts @@ -79,6 +79,8 @@ export function useMessages( setLimit(data.limit ?? filters?.limit ?? 25); setOffset(data.offset ?? filters?.offset ?? 0); } + } catch { + // Keep the list already on screen when a refresh fails. } finally { if (!cancelled && currentRequest === requestNumber) setIsLoading(false); } diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts index 5cb113ec3..c9562f282 100644 --- a/src/hooks/utils.ts +++ b/src/hooks/utils.ts @@ -272,8 +272,12 @@ export async function fetchMessageList(params: URLSearchParams, force = false): if (!force && messageListRequests.has(key)) return messageListRequests.get(key) ?? {}; const requestGeneration = messageCacheGeneration; const request = authFetch(`/api/messages?${key}`) - .then((res) => { - if (!res.ok) throw new Error(`Message list request failed (${res.status})`); + .then(async (res) => { + // An error body is not a message list; do not cache it or paint it as an empty folder. + if (!res.ok) { + const body = (await res.json().catch(() => null)) as { error?: string } | null; + throw new Error(body?.error ?? `Message list request failed (${res.status})`); + } return res.json(); }) .then((data) => { diff --git a/src/lib/http/response.ts b/src/lib/http/response.ts new file mode 100644 index 000000000..38f27d2ce --- /dev/null +++ b/src/lib/http/response.ts @@ -0,0 +1,13 @@ +/** + * Parse a response body as a JSON object, or `{}` when it is not JSON (for + * example an HTML 502 page from a proxy). Callers then fall through to their + * own `res.ok` handling and fallback message. + */ +export async function readResponseJson(res: Response): Promise { + try { + const data: unknown = await res.json(); + return (data && typeof data === "object" ? data : {}) as T; + } catch { + return {} as T; + } +} diff --git a/src/lib/validators.ts b/src/lib/validators.ts index e7d53ff59..eebd3d466 100644 --- a/src/lib/validators.ts +++ b/src/lib/validators.ts @@ -321,7 +321,8 @@ export const folderSchema = z.object({ }); export const updateProfileSchema = z.object({ - name: z.string().trim().min(1).max(100), + // Optional so a recovery-email-only save leaves the name alone instead of writing back a stale one. + name: z.string().trim().min(1).max(100).optional(), resetEmail: z.preprocess( (value) => (typeof value === "string" ? value.trim() : value), z.string().email().or(z.literal("")).transform((value) => value || null), diff --git a/tests/drive-cache.test.mjs b/tests/drive-cache.test.mjs new file mode 100644 index 000000000..625615a30 --- /dev/null +++ b/tests/drive-cache.test.mjs @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import test, { after } from "node:test"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; + +const project = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(project, "node_modules", "drive-cache-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(project, "src/app/(drive)/drive-cache.ts")], + outfile: join(directory, "drive-cache.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", + plugins: [{ name: "mock-auth", setup(builder) { + builder.onResolve({ filter: /^@\/lib\/auth\/client$/ }, () => ({ path: "auth", namespace: "mock" })); + builder.onLoad({ filter: /.*/, namespace: "mock" }, () => ({ + contents: `export const AUTH_SESSION_CHANGED_EVENT = "auth-changed";`, + loader: "js", + })); + } }], +}); +const cacheUrl = pathToFileURL(join(directory, "drive-cache.mjs")).href; + +test("drive listings are dropped when the session changes", async () => { + const dom = new JSDOM(""); + globalThis.window = dom.window; + try { + const cache = await import(`${cacheUrl}?run=${Math.random()}`); + const listing = { items: [{ id: "a" }], path: [], role: "owner", storageUsed: 1, storageLimit: null }; + cache.saveDriveListing("my|||", listing); + assert.equal(cache.readDriveListing("my|||"), listing); + window.dispatchEvent(new window.Event("auth-changed")); + assert.equal(cache.readDriveListing("my|||"), undefined); + } finally { + dom.window.close(); + delete globalThis.window; + } +}); diff --git a/tests/import-upload-response.test.mjs b/tests/import-upload-response.test.mjs new file mode 100644 index 000000000..a5df94f1b --- /dev/null +++ b/tests/import-upload-response.test.mjs @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import test, { after } from "node:test"; +import { build } from "esbuild"; + +const project = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(project, "node_modules", "import-upload-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(project, "src/components/settings/import-messages-utils.ts")], + outfile: join(directory, "utils.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", + plugins: [{ name: "mock-auth", setup(builder) { + builder.onResolve({ filter: /^@\/lib\/auth\/client$/ }, () => ({ path: "auth", namespace: "mock" })); + builder.onLoad({ filter: /.*/, namespace: "mock" }, () => ({ contents: `export function getAuthHeaders(){return new Headers();}`, loader: "js" })); + } }], +}); +const utils = await import(pathToFileURL(join(directory, "utils.mjs")).href); + +function stubXhr(finish) { + globalThis.FormData = class { set() {} append() {} }; + globalThis.XMLHttpRequest = class { + upload = {}; + open() {} + setRequestHeader() {} + send() { queueMicrotask(() => finish(this)); } + }; +} + +test("a non-JSON error page rejects instead of hanging", async () => { + stubXhr((x) => { x.status = 502; x.responseText = "Bad gateway"; x.onload(); }); + await assert.rejects(utils.importMessageFiles("mb", [], "inbox"), /Import failed/); +}); + +test("abort and timeout reject", async () => { + stubXhr((x) => x.onabort()); + await assert.rejects(utils.importMessageFiles("mb", [], "inbox"), /cancelled/); + stubXhr((x) => x.ontimeout()); + await assert.rejects(utils.importMessageFiles("mb", [], "inbox"), /timed out/); +}); + +test("a JSON success still resolves", async () => { + stubXhr((x) => { x.status = 202; x.responseText = JSON.stringify({ job: { id: "j1" } }); x.onload(); }); + assert.deepEqual(await utils.importMessageFiles("mb", [], "inbox"), { job: { id: "j1" } }); +}); diff --git a/tests/message-list-cache.test.mjs b/tests/message-list-cache.test.mjs new file mode 100644 index 000000000..79a5ca105 --- /dev/null +++ b/tests/message-list-cache.test.mjs @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import test, { after } from "node:test"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; + +const project = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(project, "node_modules", "message-list-cache-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(project, "src/hooks/utils.ts")], + outfile: join(directory, "utils.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", + plugins: [{ name: "mock-auth", setup(builder) { + builder.onResolve({ filter: /^@\/lib\/auth\/client$/ }, () => ({ path: "auth", namespace: "mock" })); + builder.onLoad({ filter: /.*/, namespace: "mock" }, () => ({ + contents: `export const AUTH_SESSION_CHANGED_EVENT = "auth-changed"; export function getClientSessionToken(){return null;} export function authFetch(...args){return globalThis.listFetch(...args);}`, + loader: "js", + })); + } }], +}); +const utilsUrl = pathToFileURL(join(directory, "utils.mjs")).href; + +async function setup() { + const dom = new JSDOM(""); + globalThis.window = dom.window; + return { dom, utils: await import(`${utilsUrl}?run=${Math.random()}`) }; +} +function cleanup(dom) { + dom.window.close(); + delete globalThis.window; + delete globalThis.listFetch; +} + +test("an error response is rejected and not cached as a message list", async () => { + const { dom, utils } = await setup(); + try { + const params = new URLSearchParams("folder=inbox"); + globalThis.listFetch = async () => ({ ok: false, status: 404, json: async () => ({ error: "Mailbox not found" }) }); + await assert.rejects(utils.fetchMessageList(params), /Mailbox not found/); + assert.equal(utils.peekMessageList(params), undefined); + globalThis.listFetch = async () => ({ ok: true, status: 200, json: async () => ({ messages: [{ id: "m1" }], total: 1 }) }); + assert.equal((await utils.fetchMessageList(params)).total, 1); + assert.equal(utils.peekMessageList(params).total, 1); + } finally { cleanup(dom); } +}); diff --git a/tests/profile-schema.test.mjs b/tests/profile-schema.test.mjs new file mode 100644 index 000000000..9f06af456 --- /dev/null +++ b/tests/profile-schema.test.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-profile-schema-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + stdin: { contents: `export { updateProfileSchema } from "./src/lib/validators.ts";`, resolveDir: root, sourcefile: "profile-schema-entry.ts" }, + outfile: join(directory, "entry.mjs"), + bundle: true, platform: "node", format: "esm", target: "node24", + tsconfig: join(root, "tsconfig.json"), packages: "external", logLevel: "silent", +}); +const { updateProfileSchema } = await import(pathToFileURL(join(directory, "entry.mjs")).href); + +test("a recovery-email-only save carries no name", () => { + const parsed = updateProfileSchema.parse({ resetEmail: "me@example.com" }); + assert.equal(parsed.name, undefined); + assert.equal(parsed.resetEmail, "me@example.com"); +}); + +test("a supplied name is still trimmed and validated", () => { + assert.equal(updateProfileSchema.parse({ name: " Alex ", resetEmail: "" }).name, "Alex"); + assert.throws(() => updateProfileSchema.parse({ name: " ", resetEmail: "" })); +}); diff --git a/tests/response-json.test.mjs b/tests/response-json.test.mjs new file mode 100644 index 000000000..2e4b9422e --- /dev/null +++ b/tests/response-json.test.mjs @@ -0,0 +1,25 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-response-json-test-")); +after(() => rmSync(directory, { recursive: true, force: true })); +await build({ + entryPoints: [join(root, "src/lib/http/response.ts")], + outfile: join(directory, "response.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", +}); +const { readResponseJson } = await import(pathToFileURL(join(directory, "response.mjs")).href); + +test("JSON objects pass through", async () => { + assert.deepEqual(await readResponseJson(new Response('{"error":"x"}')), { error: "x" }); +}); + +test("an HTML error page or empty body becomes an empty object", async () => { + assert.deepEqual(await readResponseJson(new Response("502", { status: 502 })), {}); + assert.deepEqual(await readResponseJson(new Response("")), {}); + assert.deepEqual(await readResponseJson(new Response("null")), {}); +});