A full-featured CRM built with React, shadcn/ui, and Supabase.
add detectForwarded function to detect forwarded mail, original sende and message
ThieryMichel39cc1167bfad
diff --git a/supabase/functions/postmark/detectForwarded.spec.ts b/supabase/functions/postmark/detectForwarded.spec.tsnew file mode 100644index 00000000..1ed13e21--- /dev/null+++ b/supabase/functions/postmark/detectForwarded.spec.ts@@ -0,0 +1,104 @@+import { detectForwarded } from "./detectForwarded.ts";+import { describe, expect, it } from "vitest";++describe("detectForwarded", () => {+ it("detects Gmail forwarded block", () => {+ const subject = "Fwd: Project update";+ const textBody = `Hello team,++----- Forwarded message -----+From: John Doe <[email protected]>+Date: Mon, 1 Jan 2024 10:00:00 +0000+Subject: Re: Project update+To: [email protected]++This is the original message body.`;+ const result = detectForwarded(subject, textBody);+ expect(result.isForwarded).toBe(true);+ expect(result.originalFrom!).toEqual({+ name: "John Doe",+ email: "[email protected]",+ });+ expect(result.originalBody).toContain("This is the original message body.");+ });++ it("detects Apple Mail forwarded block", () => {+ const subject = "FW: Meeting notes";+ const textBody = `Begin forwarded message:+From: Jane Smith <[email protected]>+Date: Tue, 2 Feb 2024 09:00:00 +0000+Subject: Meeting notes+To: [email protected]++Here are the meeting notes.`;+ const result = detectForwarded(subject, textBody);+ expect(result.isForwarded).toBe(true);+ expect(result.originalFrom).toEqual({+ name: "Jane Smith",+ email: "[email protected]",+ });+ expect(result.originalBody).toContain("Here are the meeting notes.");+ });++ it("detects Outlook forwarded block", () => {+ const subject = "Fwd: Budget";+ const textBody = `-----Original Message-----+From: Bob Brown <[email protected]>+Sent: Wednesday, March 3, 2024 8:00 AM+To: [email protected]+Subject: Budget++Budget details attached.`;+ const result = detectForwarded(subject, textBody);+ expect(result.isForwarded).toBe(true);+ expect(result.originalFrom).toEqual({+ name: "Bob Brown",+ email: "[email protected]",+ });+ expect(result.originalBody).toContain("Budget details attached.");+ });++ it("detects Resent-From header", () => {+ const subject = "Fwd: Invoice";+ const textBody = "See attached invoice.";+ const headers = [+ { Name: "Resent-From", Value: "Alice <[email protected]>" },+ ];+ const result = detectForwarded(subject, textBody, headers);+ expect(result.isForwarded).toBe(true);+ expect(result.originalFrom).toEqual({+ name: "Alice",+ email: "[email protected]",+ });+ });++ it("flags subject prefix only", () => {+ const subject = "Fwd: No body separator";+ const textBody = "Just a forwarded message, no separator.";+ const result = detectForwarded(subject, textBody);+ expect(result.isForwarded).toBe(true);+ expect(result.originalFrom).toBeUndefined();+ });++ it("does not flag replies", () => {+ const subject = "Re: Follow up";+ const textBody = "This is a reply, not a forward.";+ const result = detectForwarded(subject, textBody);+ expect(result.isForwarded).toBe(false);+ });++ it("handles malformed From line", () => {+ const subject = "Fwd: Weird format";+ const textBody = `----- Forwarded message -----+From: not-an-email+Date: Mon, 1 Jan 2024 10:00:00 +0000+Subject: Re: Project update+To: [email protected]++Body text.`;+ const result = detectForwarded(subject, textBody);+ expect(result.isForwarded).toBe(true);+ expect(result.originalFrom).toBeUndefined();+ expect(result.originalBody).toContain("Body text.");+ });+});diff --git a/supabase/functions/postmark/detectForwarded.ts b/supabase/functions/postmark/detectForwarded.tsnew file mode 100644index 00000000..4e5cbeb8--- /dev/null+++ b/supabase/functions/postmark/detectForwarded.ts@@ -0,0 +1,134 @@+/**+ * Detects whether an inbound email is a forwarded message, and if so,+ * extracts the original sender and body.+ *+ * Detection strategy (in order of preference):+ * 1. RFC 5321 `Resent-From` header — most reliable, set by some clients.+ * 2. Known body separator patterns injected by Gmail, Outlook, Apple Mail, etc.+ *+ * Returns:+ * - isForwarded: true when a forwarding signal was detected+ * - originalFrom: parsed { name, email } of the original sender (may be undefined if parsing failed)+ * - originalBody: the body of the original message, minus the forwarding header block+ */++export type ForwardedInfo = {+ isForwarded: boolean;+ originalFrom?: { name: string; email: string };+ originalBody?: string;+};++/** Patterns that mark the beginning of a forwarded block in the email body. */+const FORWARD_SEPARATOR_PATTERNS = [+ // Gmail+ /^-{5,}\s*Forwarded message\s*-{5,}/im,+ // Apple Mail+ /^Begin forwarded message:/im,+ // Outlook / Exchange+ /^-{5,}\s*Original Message\s*-{5,}/im,+ // Outlook horizontal line separator+ /^_{10,}/m,+ // French clients (Transféré / Message transféré)+ /^-{5,}\s*Message transf[eé]r[eé]\s*-{5,}/im,+ /^-{5,}\s*Transf[eé]r[eé]\s*-{5,}/im,+ // German (Weitergeleitet)+ /^-{5,}\s*Weitergeleitete Nachricht\s*-{5,}/im,+];++/**+ * Parses a raw "From" header value such as:+ * "John Doe" <[email protected]>+ * John Doe <[email protected]>+ */+const parseFromLine = (+ raw: string,+): { name: string; email: string } | undefined => {+ // Format: "Name" <email> or Name <email>+ const angleMatch = raw.match(/^"?([^"<]*?)"?\s*<([^>]+)>\s*$/);+ if (angleMatch) {+ return { name: angleMatch[1].trim(), email: angleMatch[2].trim() };+ }+ // Bare email address+ const emailMatch = raw.match(/^[\w.+%-]+@[\w.-]+\.[a-zA-Z]{2,}$/);+ if (emailMatch) {+ return { name: "", email: raw.trim() };+ }+ return undefined;+};++/**+ * Given the text that follows a forwarding separator, extracts the original+ * sender's From line and the body that comes after the header block.+ *+ * The header block is a sequence of lines that look like "Key: value"+ * (From, Date, Subject, To, Cc, …), potentially followed by a blank line.+ */+const parseForwardedBlock = (+ blockText: string,+): {+ originalFrom?: { name: string; email: string };+ originalBody?: string;+} => {+ const lines = blockText.split("\n");+ let originalFrom: { name: string; email: string } | undefined;+ let bodyStartIndex = 0;++ // Walk through the header-like lines at the top of the block+ let i = 0;+ while (i < lines.length) {+ const line = lines[i];+ // Blank line signals end of the forwarded header block+ if (line.trim() === "") {+ bodyStartIndex = i + 1;+ break;+ }+ // Try to capture the From: line+ const fromMatch = line.match(/^From:\s*(.+)$/i);+ if (fromMatch) {+ originalFrom = parseFromLine(fromMatch[1].trim());+ }+ i++;+ }++ const originalBody = lines.slice(bodyStartIndex).join("\n").trim();+ return { originalFrom, originalBody };+};++export const detectForwarded = (+ subject: string,+ textBody: string,+ headers: { Name: string; Value: string }[] = [],+): ForwardedInfo => {+ // ── Strategy 1: Resent-From header ──────────────────────────────────────────+ const resentFrom = headers.find(+ (h) => h.Name.toLowerCase() === "resent-from",+ );+ if (resentFrom) {+ const originalFrom = parseFromLine(resentFrom.Value);+ return { isForwarded: true, originalFrom };+ }++ // ── Strategy 2: Body separator patterns ─────────────────────────────────────+ for (const pattern of FORWARD_SEPARATOR_PATTERNS) {+ const match = textBody.match(pattern);+ if (match && match.index !== undefined) {+ const blockText = textBody+ .slice(match.index + match[0].length)+ .trimStart();+ const { originalFrom, originalBody } = parseForwardedBlock(blockText);+ return { isForwarded: true, originalFrom, originalBody };+ }+ }++ // ── Strategy 3: Subject prefix ───────────────────────────────────────────────+ const subjectHasForwardPrefix = /^(fwd?|tr|wg|ts)\s*:/i.test(subject.trim());++ // still flag as forwarded+ // but we cannot parse the original sender, so return without originalFrom.+ if (subjectHasForwardPrefix) {+ return { isForwarded: true };+ }++ return { isForwarded: false };+};diff --git a/supabase/functions/postmark/index.ts b/supabase/functions/postmark/index.tsindex cf7f97a9..b3060f42 100644--- a/supabase/functions/postmark/index.ts+++ b/supabase/functions/postmark/index.ts@@ -5,6 +5,7 @@// Setup type definitions for built-in Supabase Runtime APIsimport "jsr:@supabase/functions-js/edge-runtime.d.ts";import { addNoteToContact } from "./addNoteToContact.ts";+import { detectForwarded } from "./detectForwarded.ts";import { extractMailContactData } from "./extractMailContactData.ts";import { getExpectedAuthorization } from "./getExpectedAuthorization.ts";import { getNoteContent } from "./getNoteContent.ts";@@ -33,9 +34,8 @@ Deno.serve(async (req) => {response = checkBody(json);if (response) return response;- const { ToFull, FromFull, Subject, TextBody, Attachments } = json;-- const noteContent = getNoteContent(Subject, TextBody);+ const { FromFull, Subject, Attachments, Headers } = json;+ let { ToFull, TextBody } = json;const { Email: salesEmail } = FromFull;if (!salesEmail) {@@ -47,6 +47,28 @@ Deno.serve(async (req) => {);}+ // Detect forwarded emails and reroute the note to the original sender+ const forwarded = detectForwarded(Subject, TextBody, Headers ?? []);+ if (forwarded.isForwarded) {+ if (!forwarded.originalFrom) {+ // Could not parse the original sender — log and fall through to default+ // behavior so the email is not silently lost.+ console.warn(+ "Detected a forwarded email but could not extract the original sender. " ++ "Falling back to default contact resolution.",+ );+ } else {+ // Swap the recipient with the original sender so the note is attached to+ // the right contact, and trim the note to only the original message body.+ ToFull = [{ Email: forwarded.originalFrom.email, Name: forwarded.originalFrom.name }];+ if (forwarded.originalBody) {+ TextBody = forwarded.originalBody;+ }+ }+ }++ const noteContent = getNoteContent(Subject, TextBody);+const contacts = extractMailContactData(ToFull);const attachments = await extractAndUploadAttachments(Attachments);