Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -3,28 +3,38 @@
// EmailTemplate table (M098 — NOT rebuilt); attachments upload as multipart
// form files (≤10 MB v1). Send errors surface as Klartext (M002 keys).
import * as React from "react";
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, Form, Link } from "react-router";
import { useTranslation } from "react-i18next";
import {
buildComposePrefill,
buildEmailComposeVM,
parseRecipients,
type EmailComposeVM,
} from "@hivegrid/view-models";
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 {
canReadAllMailboxes,
loadEmailInboxContext,
requireEmailRead,
requireEmailWrite,
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
import { EMAIL_INBOX_MODULE_KEY, emailInboxPath, emailMessagePath, emailSettingsPath, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
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 { renderPlainTextAsHtml, sanitizeEmailHtml } from "~/modules/emailInbox/services/emailHtmlSanitizer";
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;
@@ -56,9 +66,10 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
? await getMessageForMailboxes(
ctx.tenantId,
visibleMailboxes.map((m) => m.id),
originalId,
originalId
)
: null;
const sanitizedOriginalBody = originalRow?.bodyHtml ? (await sanitizeEmailHtml(originalRow.bodyHtml)).html : null;
const original = originalRow
? {
id: originalRow.id,
@@ -66,15 +77,14 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
fromAddress: originalRow.fromAddress,
fromName: originalRow.fromName,
toSummary: Array.isArray(originalRow.toAddresses)
? (originalRow.toAddresses as Array<{ address?: string }>).map((a) => a.address ?? "").filter(Boolean).join(", ")
? (originalRow.toAddresses as Array<{ address?: string }>)
.map((a) => a.address ?? "")
.filter(Boolean)
.join(", ")
: "",
subject: originalRow.subject,
sentAtIso: originalRow.sentAt.toISOString(),
safeBodyHtml: originalRow.bodyHtml
? sanitizeEmailHtml(originalRow.bodyHtml).html
: originalRow.bodyText
? renderPlainTextAsHtml(originalRow.bodyText)
: "",
safeBodyHtml: originalRow.bodyHtml ? (sanitizedOriginalBody ?? "") : originalRow.bodyText ? renderPlainTextAsHtml(originalRow.bodyText) : "",
}
: null;
@@ -113,9 +123,11 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
}
// Body: user plain-text (escaped) + the sanitized quoted original below it.
const bodyHtml = `${renderPlainTextAsHtml(bodyText)}${quotedHtml ? sanitizeEmailHtml(quotedHtml).html : ""}`;
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;
@@ -123,14 +135,30 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
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: Buffer.from(await file.arrayBuffer()).toString("base64"),
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,
@@ -153,127 +181,44 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
}
};
/** AK-UI-03: the route only wires loader/action — the interim screen renders the UI (AD-28). */
export default function EmailComposeRoute() {
const { t } = useTranslation();
const rootData = useRootData();
const { vm } = useLoaderData<LoaderData>();
const actionData = useActionData<{ error?: string }>();
const [subject, setSubject] = React.useState<string | null>(null);
const [templateBody, setTemplateBody] = React.useState<string>("");
const navigation = useNavigation();
const submit = useSubmit();
const navigate = useNavigate();
const params = useParams();
if (vm.status !== "ready" || !vm.data) {
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose" />;
}
const { mailboxes, defaultMailboxId, templates, prefill, backHref, noMailboxKey } = vm.data;
if (mailboxes.length === 0) {
return (
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose">
<p className="text-foreground font-medium">{t(noMailboxKey)}</p>
<Link to={backHref.replace(/\/emails.*$/, "/settings/integrations/email")} className="text-theme-600 mt-2 inline-block text-sm underline">
{t("emailInbox.list.connectCta")}
</Link>
</main>
);
}
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 (
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose">
<Link to={backHref} className="text-muted-foreground text-sm underline">
← {t("emailInbox.compose.back")}
</Link>
<h1 className="text-foreground mt-2 text-xl font-semibold">{t("emailInbox.compose.title")}</h1>
{actionData?.error && (
<p className="text-destructive border-border mt-3 rounded-md border px-3 py-2 text-sm" data-ui-id="ui.email.compose.error">
{t(actionData.error)}
</p>
)}
<Form method="post" encType="multipart/form-data" className="mt-4 space-y-3">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<input type="hidden" name="replyToMessageId" value={prefill.replyToMessageId ?? ""} />
<input type="hidden" name="quotedHtml" value={prefill.quotedHtml} />
<label className="block text-sm">
{t("emailInbox.compose.mailbox")}
<select name="mailboxId" defaultValue={defaultMailboxId ?? ""} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" data-ui-id="ui.email.compose.mailbox">
{mailboxes.map((mailbox) => (
<option key={mailbox.id} value={mailbox.id}>
{mailbox.emailAddress}
</option>
))}
</select>
</label>
<label className="block text-sm">
{t("emailInbox.compose.to")}
<input name="to" defaultValue={prefill.to} required placeholder={t("emailInbox.compose.recipientsPlaceholder")} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" data-ui-id="ui.email.compose.to" />
</label>
<label className="block text-sm">
{t("emailInbox.compose.cc")}
<input name="cc" placeholder={t("emailInbox.compose.recipientsPlaceholder")} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" />
</label>
{templates.length > 0 && (
<label className="block text-sm">
{t("emailInbox.compose.template")}
<select
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
data-ui-id="ui.email.compose.template"
defaultValue=""
onChange={(event) => {
const template = templates.find((candidate) => candidate.id === event.target.value);
if (template) {
setSubject(template.subject);
setTemplateBody(template.htmlBody.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim());
}
}}
>
<option value="">{t("emailInbox.compose.noTemplate")}</option>
{templates.map((template) => (
<option key={template.id} value={template.id}>
{template.name}
</option>
))}
</select>
</label>
)}
<label className="block text-sm">
{t("emailInbox.compose.subject")}
<input
name="subject"
value={subject ?? prefill.subject}
onChange={(event) => setSubject(event.target.value)}
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
data-ui-id="ui.email.compose.subject"
/>
</label>
<label className="block text-sm">
{t("emailInbox.compose.body")}
<textarea
name="body"
rows={10}
value={templateBody || undefined}
onChange={(event) => setTemplateBody(event.target.value)}
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
data-ui-id="ui.email.compose.body"
/>
</label>
{prefill.quotedHtml && <p className="text-muted-foreground text-xs">{t("emailInbox.compose.quotedHint")}</p>}
<label className="block text-sm">
{t("emailInbox.compose.attachments")}
<input type="file" name="attachments" multiple className="mt-1 block text-sm" data-ui-id="ui.email.compose.attachments" />
</label>
<button type="submit" className="bg-theme-600 rounded-md px-4 py-2 text-sm font-medium text-white" data-ui-id="ui.email.compose.send">
{t("emailInbox.compose.send")}
</button>
</Form>
</main>
<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 ?? "")),
}}
/>
);
}