230 lines
9.0 KiB
TypeScript
230 lines
9.0 KiB
TypeScript
// VA-P23 · compose route (M09 Block G): new mail / reply (?replyTo=) / forward
|
|
// (?forward=) over the user's OWN mailbox. Templates come from the v1
|
|
// EmailTemplate table (M098 — NOT rebuilt); attachments upload as multipart
|
|
// form files (≤10 MB v1). Send errors surface as Klartext (M002 keys).
|
|
|
|
import {
|
|
type ActionFunctionArgs,
|
|
type LoaderFunctionArgs,
|
|
redirect,
|
|
useActionData,
|
|
useLoaderData,
|
|
useNavigate,
|
|
useNavigation,
|
|
useParams,
|
|
useSubmit,
|
|
} from "react-router";
|
|
import { buildComposePrefill, buildEmailComposeVM, parseRecipients, type EmailComposeVM } from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { canReadAllMailboxes, loadEmailInboxContext, requireEmailRead, requireEmailWrite } from "~/modules/emailInbox/routes/emailInboxAccess.server";
|
|
import {
|
|
EMAIL_INBOX_MODULE_KEY,
|
|
emailInboxPath,
|
|
emailMessagePath,
|
|
emailSettingsPath,
|
|
notFoundResponse,
|
|
} from "~/modules/emailInbox/routes/emailInboxRoutePaths";
|
|
import { getMessageForMailboxes, listMailboxesForTenant, listMailboxesForUser } from "~/modules/emailInbox/db/emailInbox.db.server";
|
|
import { EmailSendError, listEmailTemplates, sendEmail } from "~/modules/emailInbox/services/EmailSendService.server";
|
|
import {
|
|
ComposeAttachmentScanError,
|
|
scanComposeAttachments,
|
|
type ComposeAttachmentScanTarget,
|
|
} from "~/modules/emailInbox/services/EmailAttachmentScan.server";
|
|
import { renderPlainTextAsHtml, sanitizeEmailHtml } from "~/modules/emailInbox/services/emailHtmlSanitizer.server";
|
|
import { EmailComposePage, type EmailComposePayload } from "~/components/screens/email-inbox/EmailComposePage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
|
|
const COMPOSE_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
|
|
|
|
type LoaderData = { title: string; vm: EmailComposeVM };
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t } = await getTranslations(request);
|
|
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
|
try {
|
|
requireEmailRead(ctx);
|
|
requireEmailWrite(ctx);
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const tenantSlug = params.tenant ?? "";
|
|
const url = new URL(request.url);
|
|
const replyToId = url.searchParams.get("replyTo");
|
|
const forwardId = url.searchParams.get("forward");
|
|
|
|
// Sending always runs over the user's OWN mailbox (M09 Block G).
|
|
const ownMailboxes = await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
|
const templates = await listEmailTemplates(ctx.tenantId);
|
|
|
|
// Reply/forward context may live in a foreign mailbox for read_all users.
|
|
const visibleMailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : ownMailboxes;
|
|
const originalId = replyToId ?? forwardId;
|
|
const originalRow = originalId
|
|
? await getMessageForMailboxes(
|
|
ctx.tenantId,
|
|
visibleMailboxes.map((m) => m.id),
|
|
originalId
|
|
)
|
|
: null;
|
|
const sanitizedOriginalBody = originalRow?.bodyHtml ? (await sanitizeEmailHtml(originalRow.bodyHtml)).html : null;
|
|
const original = originalRow
|
|
? {
|
|
id: originalRow.id,
|
|
direction: originalRow.direction,
|
|
fromAddress: originalRow.fromAddress,
|
|
fromName: originalRow.fromName,
|
|
toSummary: Array.isArray(originalRow.toAddresses)
|
|
? (originalRow.toAddresses as Array<{ address?: string }>)
|
|
.map((a) => a.address ?? "")
|
|
.filter(Boolean)
|
|
.join(", ")
|
|
: "",
|
|
subject: originalRow.subject,
|
|
sentAtIso: originalRow.sentAt.toISOString(),
|
|
safeBodyHtml: originalRow.bodyHtml ? (sanitizedOriginalBody ?? "") : originalRow.bodyText ? renderPlainTextAsHtml(originalRow.bodyText) : "",
|
|
}
|
|
: null;
|
|
|
|
const vm = buildEmailComposeVM({
|
|
mailboxes: ownMailboxes.map((m) => ({ id: m.id, emailAddress: m.emailAddress, provider: m.provider, isDefaultForUser: m.isDefaultForUser })),
|
|
defaultMailboxId: ownMailboxes.find((m) => m.isDefaultForUser)?.id ?? ownMailboxes[0]?.id ?? null,
|
|
templates,
|
|
prefill: buildComposePrefill({ mode: replyToId ? "reply" : forwardId ? "forward" : "blank", original }),
|
|
backHref: originalId ? emailMessagePath(tenantSlug, originalId) : emailInboxPath(tenantSlug),
|
|
});
|
|
return Response.json({ title: `${t("emailInbox.compose.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
|
try {
|
|
requireEmailRead(ctx);
|
|
requireEmailWrite(ctx);
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
await validateCSRFToken(request);
|
|
const tenantSlug = params.tenant ?? "";
|
|
const form = await request.formData();
|
|
|
|
const to = parseRecipients(String(form.get("to") ?? ""));
|
|
const cc = parseRecipients(String(form.get("cc") ?? ""));
|
|
const bcc = parseRecipients(String(form.get("bcc") ?? ""));
|
|
const subject = String(form.get("subject") ?? "").trim();
|
|
const bodyText = String(form.get("body") ?? "");
|
|
const mailboxId = String(form.get("mailboxId") ?? "");
|
|
const replyToMessageId = String(form.get("replyToMessageId") ?? "").trim() || null;
|
|
const quotedHtml = String(form.get("quotedHtml") ?? "");
|
|
if (to.length === 0) {
|
|
return Response.json({ error: "emailInbox.compose.error.no_recipients" }, { status: 400 });
|
|
}
|
|
|
|
// Body: user plain-text (escaped) + the sanitized quoted original below it.
|
|
const sanitizedQuotedHtml = quotedHtml ? (await sanitizeEmailHtml(quotedHtml)).html : "";
|
|
const bodyHtml = `${renderPlainTextAsHtml(bodyText)}${sanitizedQuotedHtml}`;
|
|
|
|
const attachments: Array<{ filename: string; mimeType: string; contentBase64: string }> = [];
|
|
const scanTargets: ComposeAttachmentScanTarget[] = [];
|
|
for (const entry of form.getAll("attachments")) {
|
|
if (typeof entry === "object" && entry && "arrayBuffer" in entry) {
|
|
const file = entry as File;
|
|
if (!file.name || file.size === 0) continue;
|
|
if (file.size > COMPOSE_ATTACHMENT_MAX_BYTES) {
|
|
return Response.json({ error: "emailInbox.compose.error.attachment_too_large" }, { status: 400 });
|
|
}
|
|
const bytes = Buffer.from(await file.arrayBuffer());
|
|
scanTargets.push({ filename: file.name, bytes });
|
|
attachments.push({
|
|
filename: file.name,
|
|
mimeType: file.type || "application/octet-stream",
|
|
contentBase64: bytes.toString("base64"),
|
|
});
|
|
}
|
|
}
|
|
|
|
// Fail-closed AV gate (AK-UI-03): the mail never leaves the tenant with an
|
|
// unscanned attachment — a scanner outage rejects the send. No attachments =
|
|
// no scanner call, so plain mails stay independent of ClamAV.
|
|
if (scanTargets.length > 0) {
|
|
try {
|
|
await scanComposeAttachments({ request, tenantId: ctx.tenantId, files: scanTargets });
|
|
} catch (error) {
|
|
if (error instanceof ComposeAttachmentScanError) {
|
|
return Response.json({ error: `emailInbox.compose.error.${error.code}` }, { status: 400 });
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
try {
|
|
const { messageId } = await sendEmail({
|
|
tenantId: ctx.tenantId,
|
|
userId: ctx.userId,
|
|
mailboxId,
|
|
to,
|
|
cc,
|
|
bcc,
|
|
subject,
|
|
bodyHtml,
|
|
replyToMessageId,
|
|
attachments,
|
|
});
|
|
return redirect(`${emailMessagePath(tenantSlug, messageId)}?sent=1`);
|
|
} catch (error) {
|
|
if (error instanceof EmailSendError) {
|
|
return Response.json({ error: `emailInbox.compose.error.${error.code}` }, { status: 400 });
|
|
}
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
/** AK-UI-03: the route only wires loader/action — the interim screen renders the UI (AD-28). */
|
|
export default function EmailComposeRoute() {
|
|
const rootData = useRootData();
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ error?: string }>();
|
|
const navigation = useNavigation();
|
|
const submit = useSubmit();
|
|
const navigate = useNavigate();
|
|
const params = useParams();
|
|
|
|
const send = (payload: EmailComposePayload): void => {
|
|
const form = new FormData();
|
|
if (rootData.csrf) form.set("csrf", rootData.csrf);
|
|
form.set("mailboxId", payload.mailboxId);
|
|
form.set("to", payload.to);
|
|
form.set("cc", payload.cc);
|
|
form.set("bcc", payload.bcc);
|
|
form.set("subject", payload.subject);
|
|
form.set("body", payload.body);
|
|
form.set("replyToMessageId", payload.replyToMessageId ?? "");
|
|
form.set("quotedHtml", payload.quotedHtml);
|
|
for (const file of payload.attachments) {
|
|
form.append("attachments", file);
|
|
}
|
|
void submit(form, { method: "post", encType: "multipart/form-data" });
|
|
};
|
|
|
|
return (
|
|
<EmailComposePage
|
|
vm={vm}
|
|
actionErrorKey={actionData?.error}
|
|
submitting={navigation.state !== "idle"}
|
|
actions={{
|
|
onSend: send,
|
|
onBack: () => void navigate(vm.data?.backHref ?? "."),
|
|
onOpenSettings: () => void navigate(emailSettingsPath(params.tenant ?? "")),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
|