Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/integrations/src/email-message-mapping.test.ts
T

246 lines
9.4 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
buildRfc2822Message,
mapGmailMessage,
mapGraphMessage,
normalizeInternetMessageId,
parseAddressList,
toBase64Url,
} from "./email-message-mapping.js";
import type { GmailMessage } from "./google/gmailApi.js";
import type { GraphMessage } from "./microsoft/graphMailApi.js";
// VA-P23 — the provider → neutral mapping is shared by web adapters and the
// worker sync engine; these tests pin header parsing, MIME walking, direction,
// newsletter detection, and the RFC-2822 builder (threading headers).
function b64url(value: string): string {
return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
describe("parseAddressList", () => {
it("parses named, bare, and quoted addresses", () => {
expect(parseAddressList('Alice Example <A@X.de>, b@y.de, "Meier, Hans" <hans@meier.de>')).toEqual([
{ address: "a@x.de", name: "Alice Example" },
{ address: "b@y.de" },
{ address: "hans@meier.de", name: "Meier, Hans" },
]);
});
it("returns empty for null/garbage", () => {
expect(parseAddressList(null)).toEqual([]);
expect(parseAddressList("no-address-here")).toEqual([]);
});
});
describe("normalizeInternetMessageId", () => {
it("strips angle brackets and whitespace", () => {
expect(normalizeInternetMessageId(" <abc@mail.example> ")).toBe("abc@mail.example");
expect(normalizeInternetMessageId(null)).toBeNull();
});
});
describe("mapGmailMessage", () => {
const gmailFixture: GmailMessage = {
id: "gm1",
threadId: "gt1",
labelIds: ["INBOX", "UNREAD"],
snippet: "Hallo, kurze Frage zur Wartung",
internalDate: "1751400000000",
payload: {
mimeType: "multipart/mixed",
headers: [
{ name: "From", value: "Max Mustermann <max@kunde.de>" },
{ name: "To", value: "info@handwerk.de" },
{ name: "Subject", value: "Anfrage Wartung" },
{ name: "Message-ID", value: "<msg-1@kunde.de>" },
],
parts: [
{
mimeType: "multipart/alternative",
parts: [
{ mimeType: "text/plain", body: { data: b64url("Hallo, kurze Frage zur Wartung.") } },
{ mimeType: "text/html", body: { data: b64url("<p>Hallo, kurze Frage zur Wartung.</p>") } },
],
},
{ mimeType: "application/pdf", filename: "angebot.pdf", body: { attachmentId: "att1", size: 12345 } },
],
},
};
it("maps headers, bodies, attachments, and read/direction state", () => {
const mapped = mapGmailMessage(gmailFixture);
expect(mapped.providerMessageId).toBe("gm1");
expect(mapped.providerThreadId).toBe("gt1");
expect(mapped.internetMessageId).toBe("msg-1@kunde.de");
expect(mapped.direction).toBe("inbound");
expect(mapped.from).toEqual({ address: "max@kunde.de", name: "Max Mustermann" });
expect(mapped.to).toEqual([{ address: "info@handwerk.de" }]);
expect(mapped.subject).toBe("Anfrage Wartung");
expect(mapped.bodyHtml).toBe("<p>Hallo, kurze Frage zur Wartung.</p>");
expect(mapped.bodyText).toBe("Hallo, kurze Frage zur Wartung.");
expect(mapped.isRead).toBe(false);
expect(mapped.hasAttachments).toBe(true);
expect(mapped.attachments).toEqual([{ attachmentId: "att1", filename: "angebot.pdf", mimeType: "application/pdf", sizeBytes: 12345 }]);
expect(mapped.sentAt).toEqual(new Date(1751400000000));
expect(mapped.isNewsletter).toBe(false);
});
it("marks SENT-labelled messages outbound and read", () => {
const mapped = mapGmailMessage({ ...gmailFixture, labelIds: ["SENT"] });
expect(mapped.direction).toBe("outbound");
expect(mapped.isRead).toBe(true);
expect(mapped.receivedAt).toBeNull();
});
it("flags a List-Unsubscribe header as newsletter", () => {
const withHeader: GmailMessage = {
...gmailFixture,
payload: {
...gmailFixture.payload!,
headers: [...(gmailFixture.payload!.headers ?? []), { name: "List-Unsubscribe", value: "<mailto:unsub@news.de>" }],
},
};
expect(mapGmailMessage(withHeader).isNewsletter).toBe(true);
});
});
describe("mapGraphMessage", () => {
const graphFixture: GraphMessage = {
id: "ms1",
conversationId: "conv1",
internetMessageId: "<msg-2@kunde.de>",
subject: "Re: Anfrage Wartung",
bodyPreview: "Danke, passt!",
body: { contentType: "html", content: "<p>Danke, passt!</p>" },
from: { emailAddress: { address: "Max@Kunde.de", name: "Max Mustermann" } },
toRecipients: [{ emailAddress: { address: "info@handwerk.de" } }],
sentDateTime: "2026-07-01T10:00:00Z",
receivedDateTime: "2026-07-01T10:00:05Z",
isRead: true,
hasAttachments: false,
};
it("maps a Graph inbox message", () => {
const mapped = mapGraphMessage(graphFixture, "inbox");
expect(mapped.providerMessageId).toBe("ms1");
expect(mapped.providerThreadId).toBe("conv1");
expect(mapped.internetMessageId).toBe("msg-2@kunde.de");
expect(mapped.direction).toBe("inbound");
expect(mapped.from).toEqual({ address: "max@kunde.de", name: "Max Mustermann" });
expect(mapped.bodyHtml).toBe("<p>Danke, passt!</p>");
expect(mapped.bodyText).toBeNull();
expect(mapped.isRead).toBe(true);
expect(mapped.receivedAt).toEqual(new Date("2026-07-01T10:00:05Z"));
});
it("derives outbound direction from the sentitems folder", () => {
expect(mapGraphMessage(graphFixture, "sentitems").direction).toBe("outbound");
});
it("detects a newsletter only when internetMessageHeaders carry List-Unsubscribe", () => {
expect(mapGraphMessage(graphFixture, "inbox").isNewsletter).toBe(false);
const withHeaders: GraphMessage = {
...graphFixture,
internetMessageHeaders: [{ name: "List-Unsubscribe", value: "<https://news.de/unsub>" }],
};
expect(mapGraphMessage(withHeaders, "inbox").isNewsletter).toBe(true);
});
});
describe("buildRfc2822Message", () => {
it("builds threading headers and encodes the html body", () => {
const raw = buildRfc2822Message({
fromAddress: "info@handwerk.de",
to: [{ address: "max@kunde.de", name: "Max" }],
subject: "Re: Anfrage",
bodyHtml: "<p>Gern!</p>",
inReplyToInternetMessageId: "msg-1@kunde.de",
referencesInternetMessageIds: ["msg-0@kunde.de", "msg-1@kunde.de"],
});
expect(raw).toContain("From: info@handwerk.de");
expect(raw).toContain("To: Max <max@kunde.de>");
expect(raw).toContain("In-Reply-To: <msg-1@kunde.de>");
expect(raw).toContain("References: <msg-0@kunde.de> <msg-1@kunde.de>");
expect(raw).toContain(Buffer.from("<p>Gern!</p>", "utf8").toString("base64"));
});
it("wraps attachments in a multipart/mixed envelope", () => {
const raw = buildRfc2822Message({
fromAddress: "info@handwerk.de",
to: [{ address: "max@kunde.de" }],
subject: "Angebot",
bodyHtml: "<p>Anbei</p>",
attachments: [{ filename: "angebot.pdf", mimeType: "application/pdf", contentBase64: "QUJD" }],
});
expect(raw).toContain("multipart/mixed");
expect(raw).toContain('filename="angebot.pdf"');
expect(raw).toContain("QUJD");
});
it("mime-encodes non-ascii subjects and names", () => {
const raw = buildRfc2822Message({
fromAddress: "info@handwerk.de",
to: [{ address: "max@kunde.de", name: "Müller GmbH" }],
subject: "Rückfrage Wärmepumpe",
bodyHtml: "<p>x</p>",
});
expect(raw).toContain(`Subject: =?UTF-8?B?${Buffer.from("Rückfrage Wärmepumpe", "utf8").toString("base64")}?=`);
expect(raw).toContain("=?UTF-8?B?");
});
it.each([
{ field: "subject", input: { subject: "Hello\r\nBcc: victim@example.test" } },
{ field: "from address", input: { fromAddress: "sender@example.test\r\nBcc: victim@example.test" } },
{ field: "display name", input: { to: [{ address: "max@kunde.de", name: "Max\r\nBcc: victim@example.test" }] } },
{ field: "message id", input: { inReplyToInternetMessageId: "id@example.test\r\nBcc: victim@example.test" } },
])("rejects RFC-2822 header injection through $field", ({ input }) => {
expect(() =>
buildRfc2822Message({
fromAddress: "info@handwerk.de",
to: [{ address: "max@kunde.de" }],
subject: "Safe subject",
bodyHtml: "<p>x</p>",
...input,
}),
).toThrow(TypeError);
});
it("rejects attachment headers and bodies that can escape the MIME part", () => {
const base = {
fromAddress: "info@handwerk.de",
to: [{ address: "max@kunde.de" }],
subject: "Safe subject",
bodyHtml: "<p>x</p>",
};
expect(() =>
buildRfc2822Message({
...base,
attachments: [{ filename: "safe.pdf\r\nBcc: victim@example.test", mimeType: "application/pdf", contentBase64: "QUJD" }],
}),
).toThrow(TypeError);
expect(() =>
buildRfc2822Message({
...base,
attachments: [{ filename: "safe.pdf", mimeType: "application/pdf\r\nBcc: victim@example.test", contentBase64: "QUJD" }],
}),
).toThrow(TypeError);
expect(() =>
buildRfc2822Message({
...base,
attachments: [{ filename: "safe.pdf", mimeType: "application/pdf", contentBase64: "QUJD\r\n--forged-boundary" }],
}),
).toThrow(TypeError);
});
});
describe("toBase64Url", () => {
it("produces url-safe base64 without padding", () => {
const encoded = toBase64Url("a?b>c");
expect(encoded).not.toMatch(/[+/=]/);
expect(Buffer.from(encoded.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8")).toBe("a?b>c");
});
});