Email for professionals and teams
Improve message original view
Hieu Nguyen (Jack)76711e9682a0
diff --git a/src/components/messages/message-source-dialog.tsx b/src/components/messages/message-source-dialog.tsxindex d7cacbb..3ad50b4 100644--- a/src/components/messages/message-source-dialog.tsx+++ b/src/components/messages/message-source-dialog.tsx@@ -1,21 +1,27 @@"use client";-import { useEffect, useState } from "react";-import { LoaderCircle } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { CheckCircle2, Copy, Download, LoaderCircle } from "lucide-react";import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";import type { MessageSourceDialogProps } from "./message-source-dialog-types";-import { fetchMessageSource } from "./message-source-utils";+import { copyMessageSource, downloadMessageSource, fetchMessageSource, summarizeMessageSource } from "./message-source-utils";export function MessageSourceDialog({ messageId, open, onOpenChange }: MessageSourceDialogProps) {const [source, setSource] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [loading, setLoading] = useState(false);+ const [copied, setCopied] = useState(false);+ const [copyError, setCopyError] = useState(false);+ const summary = useMemo(() => source === null ? null : summarizeMessageSource(source), [source]);useEffect(() => {if (!open) return;const controller = new AbortController();setSource(null);setError(null);+ setCopied(false);+ setCopyError(false);setLoading(true);fetchMessageSource(messageId, controller.signal).then((value) => {@@ -32,15 +38,50 @@ export function MessageSourceDialog({ messageId, open, onOpenChange }: MessageSoreturn (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="flex max-h-[90vh] w-[min(960px,calc(100vw-32px))] flex-col">+ <DialogContent className="max-h-[90vh] w-[min(960px,calc(100vw-32px))] overflow-y-auto"><DialogHeader>- <DialogTitle>Show original</DialogTitle>- <DialogDescription>Full message source, including headers and MIME body.</DialogDescription>+ <DialogTitle>Original Message</DialogTitle>+ <DialogDescription>Message details and full source, including headers and MIME body.</DialogDescription></DialogHeader>{loading && <div className="flex items-center gap-2 text-sm text-neutral-500"><LoaderCircle className="h-4 w-4 animate-spin" />Loading source…</div>}{error && <p className="text-sm text-neutral-600">{error}</p>}- {source !== null && (- <pre className="min-h-0 overflow-auto rounded-lg border border-neutral-200 bg-neutral-50 p-4 font-mono text-xs leading-relaxed text-neutral-900 whitespace-pre">{source}</pre>+ {source !== null && summary && (+ <div className="space-y-5">+ <div className="overflow-hidden rounded-lg border border-neutral-200 text-sm">+ {([+ ["Message ID", summary.messageId],+ ["Created at", summary.createdAt],+ ["From", summary.from],+ ["To", summary.to],+ ["Subject", summary.subject],+ ] as const).map(([label, value]) => (+ <div key={label} className="grid gap-1 border-b border-neutral-200 px-4 py-3 last:border-b-0 sm:grid-cols-[140px_minmax(0,1fr)] sm:gap-4">+ <span className="font-medium text-neutral-700">{label}</span>+ <span className={label === "Message ID" && value ? "break-all text-green-700" : "break-words text-neutral-900"}>{value || "Unavailable"}</span>+ </div>+ ))}+ {(["spf", "dkim", "dmarc"] as const).map((method) => {+ const result = summary[method];+ return (+ <div key={method} className="grid gap-1 border-b border-neutral-200 px-4 py-3 last:border-b-0 sm:grid-cols-[140px_minmax(0,1fr)] sm:gap-4">+ <span className="font-medium uppercase text-neutral-700">{method}</span>+ <span className="flex min-w-0 items-center gap-1.5 break-all text-neutral-900">+ {result?.status === "PASS" && <CheckCircle2 className="h-4 w-4 shrink-0 text-green-600" aria-label={`${method.toUpperCase()} passed`} />}+ {result ? `${result.status}${result.detail ? ` ${result.detail}` : ""}` : "No result in message headers"}+ </span>+ </div>+ );+ })}+ </div>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <Button type="button" variant="ghost" size="sm" className="text-blue-600 hover:text-blue-700" onClick={() => downloadMessageSource(source, messageId)}><Download className="h-4 w-4" />Download Original</Button>+ <div className="flex items-center gap-2">+ {copyError && <span role="alert" className="text-xs text-red-600">Could not copy</span>}+ <Button type="button" size="sm" onClick={() => { void copyMessageSource(source).then(() => { setCopied(true); setCopyError(false); }).catch(() => { setCopied(false); setCopyError(true); }); }}><Copy className="h-4 w-4" />{copied ? "Copied" : "Copy to clipboard"}</Button>+ </div>+ </div>+ <pre className="max-h-[40vh] overflow-auto rounded-lg border border-neutral-200 bg-neutral-50 p-4 font-mono text-xs leading-relaxed text-neutral-700 whitespace-pre">{source}</pre>+ </div>)}</DialogContent></Dialog>diff --git a/src/components/messages/message-source-types.d.ts b/src/components/messages/message-source-types.d.tsnew file mode 100644index 0000000..82b9046--- /dev/null+++ b/src/components/messages/message-source-types.d.ts@@ -0,0 +1,15 @@+export type AuthenticationSummary = {+ status: string;+ detail: string | null;+};++export type MessageSourceSummary = {+ messageId: string | null;+ createdAt: string | null;+ from: string | null;+ to: string | null;+ subject: string | null;+ spf: AuthenticationSummary | null;+ dkim: AuthenticationSummary | null;+ dmarc: AuthenticationSummary | null;+};diff --git a/src/components/messages/message-source-utils.ts b/src/components/messages/message-source-utils.tsindex 263e661..1aa6887 100644--- a/src/components/messages/message-source-utils.ts+++ b/src/components/messages/message-source-utils.ts@@ -1,4 +1,5 @@import { authFetch } from "@/lib/auth/client";+import type { AuthenticationSummary, MessageSourceSummary } from "./message-source-types";export async function fetchMessageSource(messageId: string, signal: AbortSignal): Promise<string> {const response = await authFetch(`/api/messages/${encodeURIComponent(messageId)}/original`, {@@ -9,3 +10,101 @@ export async function fetchMessageSource(messageId: string, signal: AbortSignal)if (!response.ok) throw new Error(source || "Unable to load original message");return source;}++function readHeaders(source: string): Map<string, string[]> {+ const boundary = source.match(/\r?\n\r?\n/);+ const headerText = boundary?.index === undefined ? source : source.slice(0, boundary.index);+ const headers = new Map<string, string[]>();+ let currentName: string | null = null;+ for (const line of headerText.split(/\r?\n/)) {+ if (/^[ \t]/.test(line) && currentName) {+ const values = headers.get(currentName);+ if (values?.length) values[values.length - 1] += ` ${line.trim()}`;+ continue;+ }+ const separator = line.indexOf(":");+ if (separator < 1) {+ currentName = null;+ continue;+ }+ currentName = line.slice(0, separator).toLowerCase();+ const values = headers.get(currentName) ?? [];+ values.push(line.slice(separator + 1).trim());+ headers.set(currentName, values);+ }+ return headers;+}++function firstHeader(headers: Map<string, string[]>, name: string): string | null {+ return headers.get(name)?.[0] ?? null;+}++function deliveryDuration(headers: Map<string, string[]>, sentAt: Date): string | null {+ const received = firstHeader(headers, "received");+ const receivedDate = received?.slice(received.lastIndexOf(";") + 1).trim();+ if (!received || !receivedDate || !received.includes(";")) return null;+ const deliveredAt = new Date(receivedDate);+ const seconds = Math.round((deliveredAt.getTime() - sentAt.getTime()) / 1000);+ if (!Number.isFinite(seconds) || seconds < 0) return null;+ if (seconds < 60) return `Delivered after ${seconds} ${seconds === 1 ? "second" : "seconds"}`;+ const minutes = Math.round(seconds / 60);+ if (minutes < 60) return `Delivered after ${minutes} ${minutes === 1 ? "minute" : "minutes"}`;+ const hours = Math.round(minutes / 60);+ if (hours < 48) return `Delivered after ${hours} ${hours === 1 ? "hour" : "hours"}`;+ const days = Math.round(hours / 24);+ return `Delivered after ${days} ${days === 1 ? "day" : "days"}`;+}++function authResult(headers: Map<string, string[]>, method: "spf" | "dkim" | "dmarc"): AuthenticationSummary | null {+ const resultHeader = headers.get("authentication-results")?.find((value) => new RegExp(`(?:^|[;\\s])${method}\\s*=`, "i").test(value));+ const result = resultHeader?.match(new RegExp(`(?:^|[;\\s])${method}\\s*=\\s*([a-z]+)`, "i"))?.[1]+ ?? (method === "spf" ? firstHeader(headers, "received-spf")?.match(/^\s*([a-z]+)/i)?.[1] : null);+ if (!result) return null;+ const status = result.toUpperCase();+ if (status !== "PASS") return { status, detail: null };+ const section = resultHeader?.split(";").find((value) => new RegExp(`(?:^|\\s)${method}\\s*=`, "i").test(value)) ?? "";+ if (method === "spf") {+ const ip = section.match(/\bclient-ip\s*=\s*([^\s;)]+)/i)?.[1]+ ?? firstHeader(headers, "received-spf")?.match(/\bclient-ip\s*=\s*([^\s;)]+)/i)?.[1];+ return { status, detail: ip ? `with IP ${ip}` : null };+ }+ if (method === "dkim") {+ const domain = section.match(/\bheader\.d\s*=\s*([^\s;)]+)/i)?.[1]+ ?? firstHeader(headers, "dkim-signature")?.match(/(?:^|;)\s*d\s*=\s*([^\s;)]+)/i)?.[1];+ return { status, detail: domain ? `with domain ${domain}` : null };+ }+ return { status, detail: null };+}++export function summarizeMessageSource(source: string): MessageSourceSummary {+ const headers = readHeaders(source);+ const date = firstHeader(headers, "date");+ const parsedDate = date ? new Date(date) : null;+ const validDate = parsedDate && !Number.isNaN(parsedDate.getTime()) ? parsedDate : null;+ const duration = validDate ? deliveryDuration(headers, validDate) : null;+ return {+ messageId: firstHeader(headers, "message-id"),+ createdAt: validDate ? `${validDate.toLocaleString(undefined, { weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" })}${duration ? ` (${duration})` : ""}` : date,+ from: firstHeader(headers, "from"),+ to: firstHeader(headers, "to"),+ subject: firstHeader(headers, "subject"),+ spf: authResult(headers, "spf"),+ dkim: authResult(headers, "dkim"),+ dmarc: authResult(headers, "dmarc"),+ };+}++export function downloadMessageSource(source: string, messageId: string): void {+ const url = URL.createObjectURL(new Blob([source], { type: "message/rfc822" }));+ const link = document.createElement("a");+ link.href = url;+ link.download = `original-${messageId}.eml`;+ document.body.appendChild(link);+ link.click();+ link.remove();+ setTimeout(() => URL.revokeObjectURL(url), 0);+}++export async function copyMessageSource(source: string): Promise<void> {+ await navigator.clipboard.writeText(source);+}