Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(llm-parse): a MIME walker that keeps a booking mail's body and attachments

Maurice57d0b427268b
diff --git a/server/src/nest/llm-parse/mime-email.ts b/server/src/nest/llm-parse/mime-email.ts
index 99fc54e7e..04d9127e8 100644
--- a/server/src/nest/llm-parse/mime-email.ts
+++ b/server/src/nest/llm-parse/mime-email.ts
@@ -11,16 +11,21 @@
*/
/** Guards against a hand-crafted mail nesting multiparts without end. */
-const MAX_DEPTH = 10;
+export const MAX_DEPTH = 10;
-type Headers = Map<string, string>;
+/*
+ * The part-level readers below are exported for mime-walker.ts, which walks
+ * the same tree for the mail import and keeps the attachments this reader skips.
+ */
+
+export type Headers = Map<string, string>;
-interface MessagePart {
+export interface MessagePart {
headers: Headers;
body: string;
}
-interface ContentType {
+export interface ContentType {
type: string;
params: Record<string, string>;
}
@@ -82,7 +87,7 @@ export function parseEmail(buffer: Buffer): ParsedMail | null {
* envelope headers; a bare HTML or text file saved as `.eml` does neither and
* is better served by the caller's raw handling.
*/
-function looksLikeMail(raw: string, headers: Headers): boolean {
+export function looksLikeMail(raw: string, headers: Headers): boolean {
return /^[!-9;-~]+:/.test(raw) && MAIL_HEADERS.some((name) => headers.has(name));
}
@@ -124,12 +129,12 @@ function walkPart(part: MessagePart, bodies: { html: string | null; text: string
}
}
-function isAttachment(headers: Headers): boolean {
+export function isAttachment(headers: Headers): boolean {
return parseContentType(headers.get('content-disposition')).type === 'attachment';
}
/** Split a message (or a part) into its unfolded headers and its still-encoded body. */
-function splitMessage(raw: string): MessagePart {
+export function splitMessage(raw: string): MessagePart {
const separator = /\r?\n\r?\n/.exec(raw);
const headerBlock = separator ? raw.slice(0, separator.index) : raw;
const body = separator ? raw.slice(separator.index + separator[0].length) : '';
@@ -160,7 +165,7 @@ function parseHeaders(block: string): Headers {
return headers;
}
-function parseContentType(value: string | undefined): ContentType {
+export function parseContentType(value: string | undefined): ContentType {
const params: Record<string, string> = {};
if (!value) return { type: '', params };
const semicolon = value.indexOf(';');
@@ -178,7 +183,7 @@ function parseContentType(value: string | undefined): ContentType {
* delimiter belongs to it, so it is matched (not captured) and stripped from
* the part that follows.
*/
-function splitParts(body: string, boundary: string): string[] {
+export function splitParts(body: string, boundary: string): string[] {
const delimiter = new RegExp(`(?:\\r?\\n|^)--${escapeRegExp(boundary)}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
const parts: string[] = [];
let start = -1;
@@ -196,14 +201,14 @@ function escapeRegExp(s: string): string {
}
/** Undo the transfer encoding of a part, yielding its raw bytes. */
-function decodeToBuffer(part: MessagePart): Buffer {
+export function decodeToBuffer(part: MessagePart): Buffer {
const encoding = (part.headers.get('content-transfer-encoding') ?? '').trim().toLowerCase();
if (encoding === 'base64') return decodeBase64(part.body);
if (encoding === 'quoted-printable') return decodeQuotedPrintable(part.body);
return Buffer.from(part.body, 'latin1');
}
-function decodePartText(part: MessagePart, contentType: ContentType): string {
+export function decodePartText(part: MessagePart, contentType: ContentType): string {
return decodeCharset(decodeToBuffer(part), contentType.params.charset).replace(/\r\n?/g, '\n');
}
@@ -244,7 +249,7 @@ function decodeCharset(bytes: Buffer, charset: string | undefined): string {
}
/** Resolve RFC 2047 encoded-words (`=?utf-8?B?…?=`), as used in subject lines. */
-function decodeEncodedWords(value: string): string {
+export function decodeEncodedWords(value: string): string {
return value
.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g, (whole, charset: string, encoding: string, payload: string) => {
const bytes =
diff --git a/server/src/nest/llm-parse/mime-walker.ts b/server/src/nest/llm-parse/mime-walker.ts
new file mode 100644
index 000000000..a9c5dcec7
--- /dev/null
+++ b/server/src/nest/llm-parse/mime-walker.ts
@@ -0,0 +1,433 @@
+import {
+ type ContentType,
+ decodeEncodedWords,
+ decodePartText,
+ decodeToBuffer,
+ type Headers,
+ isAttachment,
+ looksLikeMail,
+ MAX_DEPTH,
+ type MessagePart,
+ parseContentType,
+ splitMessage,
+ splitParts,
+} from './mime-email';
+import { collapseWhitespace, stripMarkup } from './text-extract';
+import type { MailAttachmentKind } from '@trek/shared';
+
+/**
+ * The mail import's reading of a forwarded booking mail: the readable body,
+ * the envelope apart from it, and the attachments a booking travels in.
+ *
+ * A mail is hostile input. Nothing here renders HTML or follows a link: the
+ * markup is stripped to text, an `<img src>` or a remote stylesheet stays a
+ * string that is never fetched, and only attachments whose bytes are what
+ * their type claims are kept. The body leaves out From, To, Cc and every
+ * forwarding header block, so what goes on to a model carries the booking
+ * and not the addresses of the people who passed it on.
+ */
+
+interface MailAttachment {
+ /** The name the sender gave it, without any path, or one made up from its kind. */
+ fileName: string;
+ kind: MailAttachmentKind;
+ mimeType: string;
+ data: Buffer;
+}
+
+/** The headers the import routes and filters a mail by, decoded; null where the mail has none. */
+interface MailEnvelope {
+ from: string | null;
+ to: string | null;
+ cc: string | null;
+ subject: string | null;
+ date: string | null;
+ messageId: string | null;
+ deliveredTo: string | null;
+ xOriginalTo: string | null;
+ listUnsubscribe: string | null;
+ precedence: string | null;
+ autoSubmitted: string | null;
+ /** The receiving server's verdict: the first header is the one it added last, on top. */
+ authenticationResults: string | null;
+}
+
+export interface WalkedMail {
+ envelope: MailEnvelope;
+ /** The subject without the `Fwd:`/`WG:`/`Re:` prefixes forwarding adds. */
+ subject: string | null;
+ /** The readable text of the mail and every message forwarded in it, headers and quote marks removed. */
+ body: string;
+ attachments: MailAttachment[];
+ /** Attachments of a kept kind that were left out: over the count or size limit, or not what they claimed. */
+ skippedAttachments: number;
+ /** How many forwarding layers were unwrapped, embedded or quoted. */
+ forwardLayers: number;
+}
+
+/** At most this many attachments are kept, in the order the mail carries them. */
+export const MAX_MAIL_ATTACHMENTS = 5;
+/** A single attachment past this size is left out. */
+export const MAX_MAIL_ATTACHMENT_BYTES = 10 * 1024 * 1024;
+/** Forwarding layers unwrapped inside the text; deeper ones stay as they are. */
+const MAX_FORWARD_DEPTH = 10;
+/** A file name is cut here; the kind, not the name, decides how the file is read. */
+const MAX_FILE_NAME = 120;
+
+const ENVELOPE_HEADERS: [keyof MailEnvelope, string][] = [
+ ['from', 'from'],
+ ['to', 'to'],
+ ['cc', 'cc'],
+ ['subject', 'subject'],
+ ['date', 'date'],
+ ['messageId', 'message-id'],
+ ['deliveredTo', 'delivered-to'],
+ ['xOriginalTo', 'x-original-to'],
+ ['listUnsubscribe', 'list-unsubscribe'],
+ ['precedence', 'precedence'],
+ ['autoSubmitted', 'auto-submitted'],
+ ['authenticationResults', 'authentication-results'],
+];
+
+/** The kind a part declares, by its media type or else its file extension. */
+const KIND_BY_TYPE: Record<string, MailAttachmentKind> = {
+ 'application/pdf': 'pdf',
+ 'application/vnd.apple.pkpass': 'pkpass',
+ 'text/calendar': 'ics',
+ 'application/ics': 'ics',
+ 'image/jpeg': 'jpeg',
+ 'image/jpg': 'jpeg',
+ 'image/pjpeg': 'jpeg',
+ 'image/png': 'png',
+ 'image/webp': 'webp',
+};
+const KIND_BY_EXTENSION: Record<string, MailAttachmentKind> = {
+ pdf: 'pdf',
+ pkpass: 'pkpass',
+ ics: 'ics',
+ jpg: 'jpeg',
+ jpeg: 'jpeg',
+ png: 'png',
+ webp: 'webp',
+};
+const MIME_BY_KIND: Record<MailAttachmentKind, string> = {
+ pdf: 'application/pdf',
+ pkpass: 'application/vnd.apple.pkpass',
+ ics: 'text/calendar',
+ jpeg: 'image/jpeg',
+ png: 'image/png',
+ webp: 'image/webp',
+};
+const EXTENSION_BY_KIND: Record<MailAttachmentKind, string> = {
+ pdf: 'pdf',
+ pkpass: 'pkpass',
+ ics: 'ics',
+ jpeg: 'jpg',
+ png: 'png',
+ webp: 'webp',
+};
+
+/** One message in the tree: the outer mail, or one forwarded inside it as `message/rfc822`. */
+interface Section {
+ html: string | null;
+ text: string | null;
+}
+
+interface WalkState {
+ sections: Section[];
+ attachments: MailAttachment[];
+ skipped: number;
+}
+
+/**
+ * Walk a raw mail. Returns null when the bytes are not a mail, so the caller
+ * can refuse them instead of reading a stray file as one.
+ */
+export function walkMail(buffer: Buffer): WalkedMail | null {
+ const raw = buffer.toString('latin1').replace(/^\u00ef\u00bb\u00bf/, '');
+ const message = splitMessage(raw);
+ if (!looksLikeMail(raw, message.headers)) return null;
+
+ const outer: Section = { html: null, text: null };
+ const state: WalkState = { sections: [outer], attachments: [], skipped: 0 };
+ walkPart(message, state, outer, 0);
+
+ let forwardLayers = state.sections.length - 1;
+ const bodies: string[] = [];
+ for (const section of state.sections) {
+ const unwrapped = unwrapForwards(sectionText(section));
+ forwardLayers += unwrapped.layers;
+ if (unwrapped.text) bodies.push(unwrapped.text);
+ }
+
+ const envelope = readEnvelope(message.headers);
+ return {
+ envelope,
+ subject: envelope.subject === null ? null : stripForwardPrefixes(envelope.subject),
+ body: bodies.join('\n\n'),
+ attachments: state.attachments,
+ skippedAttachments: state.skipped,
+ forwardLayers: Math.min(forwardLayers, MAX_FORWARD_DEPTH),
+ };
+}
+
+function readEnvelope(headers: Headers): MailEnvelope {
+ const envelope = {} as MailEnvelope;
+ for (const [key, name] of ENVELOPE_HEADERS) {
+ const value = headers.get(name);
+ envelope[key] = value ? decodeEncodedWords(value) : null;
+ }
+ return envelope;
+}
+
+function walkPart(part: MessagePart, state: WalkState, section: Section, depth: number): void {
+ if (depth > MAX_DEPTH) return;
+ const contentType = parseContentType(part.headers.get('content-type'));
+ const type = contentType.type || 'text/plain';
+
+ if (type.startsWith('multipart/')) {
+ const boundary = contentType.params.boundary;
+ if (!boundary) return;
+ for (const raw of splitParts(part.body, boundary)) walkPart(splitMessage(raw), state, section, depth + 1);
+ return;
+ }
+
+ // A mail forwarded as an attachment is a message of its own: its text is a section of its own.
+ if (type === 'message/rfc822') {
+ const embedded: Section = { html: null, text: null };
+ state.sections.push(embedded);
+ walkPart(splitMessage(decodeToBuffer(part).toString('latin1')), state, embedded, depth + 1);
+ return;
+ }
+
+ const kind = attachmentKind(part.headers, contentType);
+ if (kind) {
+ keepAttachment(part, contentType, kind, state);
+ return;
+ }
+ if (isAttachment(part.headers)) return;
+ if (type === 'text/html' && section.html === null) section.html = decodePartText(part, contentType);
+ else if (type === 'text/plain' && section.text === null) section.text = decodePartText(part, contentType);
+}
+
+/** The name a part carries, from its disposition or, as older mailers put it, its content type. */
+function partFileName(headers: Headers, contentType: ContentType): string {
+ const disposition = parseContentType(headers.get('content-disposition'));
+ const name = disposition.params.filename ?? contentType.params.name ?? '';
+ return decodeEncodedWords(name);
+}
+
+/**
+ * The kind of a part worth keeping, or null. An image referenced from the
+ * HTML (a logo, a spacer) carries a Content-ID and no attachment disposition:
+ * it belongs to the layout, not to the booking, and is left behind.
+ */
+function attachmentKind(headers: Headers, contentType: ContentType): MailAttachmentKind | null {
+ const extension = partFileName(headers, contentType).split('.').pop()?.toLowerCase() ?? '';
+ const kind = KIND_BY_TYPE[contentType.type] ?? KIND_BY_EXTENSION[extension] ?? null;
+ if (!kind) return null;
+ const image = kind === 'jpeg' || kind === 'png' || kind === 'webp';
+ if (image && headers.has('content-id') && !isAttachment(headers)) return null;
+ return kind;
+}
+
+function keepAttachment(part: MessagePart, contentType: ContentType, kind: MailAttachmentKind, state: WalkState): void {
+ // Encoded, a part takes at most about twice its bytes (base64 with its line breaks
+ // a third more): one longer than that is over the limit and is not decoded at all.
+ const oversized = part.body.length > MAX_MAIL_ATTACHMENT_BYTES * 2;
+ if (state.attachments.length >= MAX_MAIL_ATTACHMENTS || oversized) {
+ state.skipped++;
+ return;
+ }
+ const data = decodeToBuffer(part);
+ if (data.length === 0 || data.length > MAX_MAIL_ATTACHMENT_BYTES || !hasSignature(kind, data)) {
+ state.skipped++;
+ return;
+ }
+ state.attachments.push({
+ fileName: safeFileName(partFileName(part.headers, contentType), kind, state.attachments.length + 1),
+ kind,
+ mimeType: MIME_BY_KIND[kind],
+ data,
+ });
+}
+
+/** Whether the bytes are what the part claims: a renamed executable is not a PDF. */
+function hasSignature(kind: MailAttachmentKind, data: Buffer): boolean {
+ switch (kind) {
+ case 'pdf':
+ // The header may follow a little junk; readers look within the first kilobyte.
+ return data.subarray(0, 1024).includes('%PDF-');
+ case 'pkpass':
+ return data.subarray(0, 4).equals(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
+ case 'png':
+ return data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
+ case 'jpeg':
+ return data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff;
+ case 'webp':
+ return data.toString('latin1', 0, 4) === 'RIFF' && data.toString('latin1', 8, 12) === 'WEBP';
+ case 'ics':
+ return /BEGIN:VCALENDAR/i.test(data.subarray(0, 1024).toString('utf8'));
+ }
+}
+
+/** The sender's file name without a path or control characters, or one made up from the kind. */
+function safeFileName(name: string, kind: MailAttachmentKind, position: number): string {
+ const base = [...(name.split(/[\\/]/).pop() ?? '')]
+ .filter((char) => char >= ' ' && char !== '\u007f')
+ .join('')
+ .trim();
+ const cut = base.slice(0, MAX_FILE_NAME);
+ return cut && cut !== '.' && cut !== '..' ? cut : `attachment-${position}.${EXTENSION_BY_KIND[kind]}`;
+}
+
+/** Line breaks and block ends, so the header lines of a forwarded HTML mail stay lines without their tags. */
+const HTML_LINE_BREAK = /<(?:br|hr)\b[^>]*>|<\/(?:p|div|tr|li|h[1-6]|blockquote|table)\s*>/gi;
+
+/** A section as text: its HTML stripped when it has a readable one, else its plain text. */
+function sectionText(section: Section): string {
+ const html = section.html === null ? '' : stripMarkup(section.html.replace(HTML_LINE_BREAK, '\n'));
+ return html || (section.text === null ? '' : collapseWhitespace(section.text));
+}
+
+/** `Fwd:`, `WG:`, `TR:`, `RV:`, `Re:` and their kin, as many as forwarding and replying stacked up. */
+const SUBJECT_PREFIX = /^\s*(?:(?:fwd?|wg|tr|rv|enc|re|aw|sv|vs|doorst)\s*(?:\[\d+\]\s*)?:\s*)+/i;
+
+function stripForwardPrefixes(subject: string): string {
+ return subject.replace(SUBJECT_PREFIX, '').trim();
+}
+
+/** The words a mail client puts between dashes above a forwarded or quoted message, lower case. */
+const FORWARD_MARKER_WORDS = [
+ 'forwarded message',
+ 'original message',
+ 'weitergeleitete nachricht',
+ 'urspr[üu]ngliche nachricht',
+ 'message transf[ée]r[ée]',
+ "message d'origine",
+ 'mensaje reenviado',
+ 'mensaje original',
+ 'messaggio inoltrato',
+ 'messaggio originale',
+ 'doorgestuurd bericht',
+ 'oorspronkelijk bericht',
+];
+/** Apple Mail's intro line, which ends in a colon instead of dashes. */
+const FORWARD_INTRO_WORDS = [
+ 'begin forwarded message',
+ 'anfang der weitergeleiteten nachricht',
+ 'd[ée]but du message r[ée]exp[ée]di[ée]',
+];
+/** The field names of a forwarded header block, in the languages the clients write them in. */
+const SENDER_FIELDS = ['from', 'von', 'de', 'da', 'van'];
+const OTHER_FIELDS = [
+ 'sent',
+ 'gesendet',
+ 'envoy[ée]',
+ 'enviado',
+ 'inviato',
+ 'verzonden',
+ 'date',
+ 'datum',
+ 'fecha',
+ 'data',
+ 'to',
+ 'an',
+ '[àa]',
+ 'para',
+ 'aan',
+ 'cc',
+ 'bcc',
+ 'reply-to',
+ 'antwort an',
+];
+const SUBJECT_FIELDS = ['subject', 'betreff', 'objet', 'asunto', 'oggetto', 'onderwerp'];
+/** A field line as clients write it, bold in a plain-text rendering of HTML included (`*From:*`). */
+const fieldLine = (names: string[]) => new RegExp(String.raw`^\s*\*?(?:${names.join('|')})\*?\s*:`, 'i');
+
+const FORWARD_MARKER = new RegExp(String.raw`^\s*[-_]{2,}\s*(?:${FORWARD_MARKER_WORDS.join('|')})\s*[-_]{2,}\s*$`, 'i');
+const FORWARD_INTRO = new RegExp(String.raw`^\s*(?:${FORWARD_INTRO_WORDS.join('|')})\s*:\s*$`, 'i');
+/** Outlook's rule above the header block of a forwarded message. */
+const OUTLOOK_RULE = /^\s*_{10,}\s*$/;
+/** "On 1 May, Ana wrote:", the line above a quoted reply, which names the sender. */
+const ATTRIBUTION = /^\s*(?:on\s.+\swrote|am\s.+\sschrieb\s.+|le\s.+\sa\s[ée]crit)\s*:\s*$/i;
+const HEADER_LINE = fieldLine([...SENDER_FIELDS, ...OTHER_FIELDS, ...SUBJECT_FIELDS]);
+const FROM_LINE = fieldLine(SENDER_FIELDS);
+const SUBJECT_LINE = fieldLine(SUBJECT_FIELDS);
+/** A header block without a marker above it (Outlook) is believed from this many header lines on. */
+const MIN_BARE_HEADER_BLOCK = 3;
+
+/**
+ * Remove what forwarding wraps around a message: the marker line, the header
+ * block under it (who sent it to whom), the reply attribution, and the `>`
+ * quoting some clients put in front of a forwarded text. Each pass unwraps one
+ * layer, so a mail forwarded on and on comes back to the booking it started as.
+ */
+function unwrapForwards(text: string): { text: string; layers: number } {
+ let lines = text.split('\n');
+ let layers = 0;
+ for (let pass = 0; pass < MAX_FORWARD_DEPTH; pass++) {
+ const next = unwrapLayer(lines);
+ if (!next.changed) break;
+ layers++;
+ lines = next.lines;
+ }
+ return { text: collapseWhitespace(lines.map((line) => line.trim()).join('\n')), layers };
+}
+
+function unwrapLayer(lines: string[]): { lines: string[]; changed: boolean } {
+ const out: string[] = [];
+ let changed = false;
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i];
+ const opensBlock =
+ FORWARD_MARKER.test(line) ||
+ FORWARD_INTRO.test(line) ||
+ (OUTLOOK_RULE.test(line) && HEADER_LINE.test(lines[i + 1] ?? ''));
+ if (opensBlock) {
+ i = skipHeaderBlock(lines, i + 1);
+ changed = true;
+ } else if (isBareHeaderBlock(lines, i)) {
+ i = skipHeaderBlock(lines, i);
+ changed = true;
+ } else if (ATTRIBUTION.test(line)) {
+ i++;
+ changed = true;
+ } else if (/^\s*>/.test(line)) {
+ out.push(line.replace(/^\s*>\s?/, ''));
+ changed = true;
+ i++;
+ } else {
+ out.push(line);
+ i++;
+ }
+ }
+ return { lines: out, changed };
+}
+
+/**
+ * A header block with no marker above it, as Outlook forwards: a sender line
+ * and at least two more header lines, one of them the subject. The subject is
+ * what tells it from a booking's own lines: a French ticket reads
+ * "De : Paris / À : Lyon / Date : 12/05" and must stay.
+ */
+function isBareHeaderBlock(lines: string[], start: number): boolean {
+ if (!FROM_LINE.test(lines[start])) return false;
+ let end = start;
+ while (end < lines.length && HEADER_LINE.test(lines[end])) end++;
+ return end - start >= MIN_BARE_HEADER_BLOCK && lines.slice(start, end).some((line) => SUBJECT_LINE.test(line));
+}
+
+/** The index after a header block starting at `start`: its header lines, their folded continuations, one blank line. */
+function skipHeaderBlock(lines: string[], start: number): number {
+ let i = start;
+ while (i < lines.length && lines[i].trim() === '') i++;
+ let inBlock = false;
+ while (i < lines.length && (HEADER_LINE.test(lines[i]) || (inBlock && /^[ \t]+\S/.test(lines[i])))) {
+ inBlock = true;
+ i++;
+ }
+ if (i < lines.length && lines[i].trim() === '') i++;
+ return i;
+}
diff --git a/server/src/nest/llm-parse/text-extract.ts b/server/src/nest/llm-parse/text-extract.ts
index 891f724c0..53b0688bb 100644
--- a/server/src/nest/llm-parse/text-extract.ts
+++ b/server/src/nest/llm-parse/text-extract.ts
@@ -96,7 +96,7 @@ function decodeEntities(s: string): string {
* an uploaded .eml or .html is free to carry one — makes the engine rescan the
* tail once per bracket.
*/
-function stripMarkup(s: string): string {
+export function stripMarkup(s: string): string {
const withoutTags = stripHtmlTags(
s.replace(/<script[\s\S]*?<\/script>/gi, ' ').replace(/<style[\s\S]*?<\/style>/gi, ' '),
' ',
@@ -110,7 +110,7 @@ function stripMarkup(s: string): string {
}
/** Whitespace cleanup for text that is already plain — no tags to strip out. */
-function collapseWhitespace(s: string): string {
+export function collapseWhitespace(s: string): string {
return s
.replace(/[ \t\u00a0]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
diff --git a/server/tests/unit/nest/llm-parse/mime-walker.test.ts b/server/tests/unit/nest/llm-parse/mime-walker.test.ts
new file mode 100644
index 000000000..983cfc7d2
--- /dev/null
+++ b/server/tests/unit/nest/llm-parse/mime-walker.test.ts
@@ -0,0 +1,331 @@
+import {
+ MAX_MAIL_ATTACHMENTS,
+ MAX_MAIL_ATTACHMENT_BYTES,
+ walkMail,
+ type WalkedMail,
+} from '../../../../src/nest/llm-parse/mime-walker';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+/** Mail is CRLF-delimited on the wire: the fixtures are built the same way. */
+const mail = (...lines: string[]) => Buffer.from(lines.join('\r\n'), 'latin1');
+
+/** Base64 in 76-character lines, as mailers write it. */
+const b64 = (data: Buffer | string) =>
+ (typeof data === 'string' ? Buffer.from(data, 'utf8') : data).toString('base64').replace(/.{76}/g, '$&\r\n');
+
+const PDF = Buffer.from('%PDF-1.4\n1 0 obj << >> endobj\n%%EOF\n', 'latin1');
+const PKPASS = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.from('pass.json')]);
+const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.from('IHDR')]);
+const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]);
+const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0, 0, 0, 0]), Buffer.from('WEBPVP8 ')]);
+const ICS = 'BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nSUMMARY:LH 716\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n';
+
+/** One attachment part of a multipart/mixed body. */
+const part = (type: string, name: string | null, data: Buffer | string, extra: string[] = []) => [
+ '--mix',
+ `Content-Type: ${type}${name ? `; name="${name}"` : ''}`,
+ 'Content-Transfer-Encoding: base64',
+ ...(name ? [`Content-Disposition: attachment; filename="${name}"`] : []),
+ ...extra,
+ '',
+ b64(data),
+];
+
+/** A forwarded booking with the given parts after its text. */
+const mixed = (text: string, ...parts: string[][]) =>
+ mail(
+ 'From: Ana <[email protected]>',
+ 'Subject: Fwd: Your booking',
+ 'MIME-Version: 1.0',
+ 'Content-Type: multipart/mixed; boundary="mix"',
+ '',
+ '--mix',
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ text,
+ ...parts.flat(),
+ '--mix--',
+ '',
+ );
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('walkMail: the envelope and the body', () => {
+ it('MIME-WALK-001: refuses bytes that are not a mail', () => {
+ expect(walkMail(Buffer.from('<html><body>Flight AB123</body></html>'))).toBeNull();
+ expect(walkMail(Buffer.from(''))).toBeNull();
+ });
+
+ it('MIME-WALK-002: keeps the envelope apart, decoded, and the body free of it', () => {
+ const walked: WalkedMail = walkMail(
+ mail(
+ 'Authentication-Results: mx.trek.example; dkim=pass header.d=example.org',
+ 'Authentication-Results: relay.example; dkim=fail',
+ 'Delivered-To: [email protected]',
+ 'X-Original-To: [email protected]',
+ 'From: =?utf-8?B?QW5hIE3DvGxsZXI=?= <[email protected]>',
+ 'Subject: Fwd: WG: =?utf-8?Q?Ihre_Buchung_f=C3=BCr_Tokio?=',
+ 'Date: Mon, 12 May 2025 09:00:00 +0200',
+ 'Message-ID: <[email protected]>',
+ 'List-Unsubscribe: <https://airline.example/unsubscribe>',
+ 'Precedence: bulk',
+ 'Auto-Submitted: auto-generated',
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ 'Flight LH 716, booking ABC123',
+ '',
+ ),
+ )!;
+ expect(walked.envelope).toEqual({
+ from: 'Ana Müller <[email protected]>',
+ subject: 'Fwd: WG: Ihre Buchung für Tokio',
+ date: 'Mon, 12 May 2025 09:00:00 +0200',
+ messageId: '<[email protected]>',
+ deliveredTo: '[email protected]',
+ xOriginalTo: '[email protected]',
+ listUnsubscribe: '<https://airline.example/unsubscribe>',
+ precedence: 'bulk',
+ autoSubmitted: 'auto-generated',
+ // The receiving server's own verdict is the topmost header.
+ authenticationResults: 'mx.trek.example; dkim=pass header.d=example.org',
+ });
+ expect(walked.subject).toBe('Ihre Buchung für Tokio');
+ expect(walked.body).toBe('Flight LH 716, booking ABC123');
+ expect(walked.body).not.toContain('example.org');
+ expect(walked.forwardLayers).toBe(0);
+ });
+
+ it('MIME-WALK-003: a missing header is null and a mail without a subject has none', () => {
+ const walked = walkMail(mail('From: [email protected]', 'Content-Type: text/plain', '', 'Hotel', ''))!;
+ expect(walked.subject).toBeNull();
+ expect(walked.envelope.to).toBeNull();
+ expect(walked.envelope.authenticationResults).toBeNull();
+ });
+});
+
+describe('walkMail: forwarded and quoted messages', () => {
+ it('MIME-WALK-010: a Gmail forward loses its marker and the header block under it', () => {
+ const walked = walkMail(
+ mail(
+ 'Subject: Fwd: Booking',
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ 'See below',
+ '',
+ '---------- Forwarded message ---------',
+ 'From: Airline <[email protected]>',
+ 'Date: Mon, 12 May 2025 at 09:00',
+ 'Subject: Your booking ABC123',
+ '',
+ 'Flight LH 716 Frankfurt to Tokyo, booking ABC123',
+ '',
+ ),
+ )!;
+ expect(walked.body).toBe('See below\n\nFlight LH 716 Frankfurt to Tokyo, booking ABC123');
+ expect(walked.body).not.toContain('airline.example');
+ expect(walked.forwardLayers).toBe(1);
+ });
+
+ it('MIME-WALK-011: an Outlook forward in HTML, its rule and bold fields on their own lines', () => {
+ const html = [
+ '<div>FYI</div>',
+ '<hr><div><b>From:</b> Hotel &lt;[email protected]&gt;<br><b>Sent:</b> Monday<br>',
+ '<b>To:</b> Ana<br><b>Subject:</b> Reservation H-77</div>',
+ '<p>Check-in 2 September, reservation H-77</p>',
+ '<img src="https://tracker.example/open.png">',
+ ].join('');
+ const walked = walkMail(
+ mail('From: [email protected]', 'Subject: WG: Reservation', 'Content-Type: text/html; charset=utf-8', '', html, ''),
+ )!;
+ expect(walked.body).toContain('Check-in 2 September, reservation H-77');
+ expect(walked.body).not.toContain('hotel.example');
+ expect(walked.body).not.toContain('Subject:');
+ });
+
+ it('MIME-WALK-012: a bare Outlook block goes, a French ticket that reads like one stays', () => {
+ const walked = walkMail(
+ mail(
+ // The fixture is written byte for byte in latin1, so the "À" is declared as such.
+ 'Content-Type: text/plain; charset=iso-8859-1',
+ '',
+ 'From: Rail <[email protected]>',
+ 'Sent: Monday',
+ 'To: Ana',
+ 'Subject: Votre billet',
+ '',
+ 'De : Paris',
+ 'À : Lyon',
+ 'Date : 12/05/2026',
+ '',
+ ),
+ )!;
+ expect(walked.body).toBe('De : Paris\nÀ : Lyon\nDate : 12/05/2026');
+ });
+
+ it('MIME-WALK-013: quoted lines are unquoted level by level, the attribution goes', () => {
+ const walked = walkMail(
+ mail(
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ 'On Mon, 12 May 2025, Ben <[email protected]> wrote:',
+ '> Begin forwarded message:',
+ '>',
+ '> From: Ferry <[email protected]>',
+ '> Subject: Ticket',
+ '>',
+ '>> Ferry Piraeus to Naxos, ticket F-12',
+ '',
+ ),
+ )!;
+ expect(walked.body).toBe('Ferry Piraeus to Naxos, ticket F-12');
+ expect(walked.body).not.toMatch(/example\.org|ferry\.example/);
+ expect(walked.forwardLayers).toBeGreaterThanOrEqual(2);
+ });
+
+ it('MIME-WALK-014: a mail forwarded as an attachment is read as a message of its own', () => {
+ const inner = [
+ 'From: Airline <[email protected]>',
+ 'Subject: Your booking',
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ 'Flight LH 716, booking ABC123',
+ ].join('\r\n');
+ const walked = walkMail(
+ mail(
+ 'Subject: Fwd: Your booking',
+ 'Content-Type: multipart/mixed; boundary="mix"',
+ '',
+ '--mix',
+ 'Content-Type: text/plain',
+ '',
+ 'Forwarding this',
+ '--mix',
+ 'Content-Type: message/rfc822',
+ 'Content-Disposition: attachment; filename="booking.eml"',
+ '',
+ inner,
+ '--mix--',
+ '',
+ ),
+ )!;
+ expect(walked.body).toBe('Forwarding this\n\nFlight LH 716, booking ABC123');
+ expect(walked.body).not.toContain('airline.example');
+ expect(walked.forwardLayers).toBe(1);
+ });
+
+ it('MIME-WALK-015: a message nested past the depth limit stops there instead of recursing on', () => {
+ let message = ['From: [email protected]', 'Content-Type: text/plain', '', 'Hotel H-77'].join('\r\n');
+ for (let level = 0; level < 15; level++) {
+ message = ['From: [email protected]', 'Content-Type: message/rfc822', '', message].join('\r\n');
+ }
+ const walked = walkMail(Buffer.from(message, 'latin1'))!;
+ expect(walked.body).toBe('');
+ expect(walked.forwardLayers).toBe(10);
+ });
+});
+
+describe('walkMail: attachments', () => {
+ it('MIME-WALK-020: keeps a PDF, a pass, a calendar and the three photo types, by type or by name', () => {
+ const walked = walkMail(
+ mixed(
+ 'Booking ABC123',
+ part('application/pdf', 'ticket.pdf', PDF),
+ part('application/octet-stream', 'boarding.pkpass', PKPASS),
+ part('text/calendar', null, ICS),
+ part('image/jpeg', 'scan.JPG', JPEG),
+ part('image/png', 'pass.png', PNG),
+ ),
+ )!;
+ expect(walked.attachments.map(({ fileName, kind, mimeType }) => ({ fileName, kind, mimeType }))).toEqual([
+ { fileName: 'ticket.pdf', kind: 'pdf', mimeType: 'application/pdf' },
+ { fileName: 'boarding.pkpass', kind: 'pkpass', mimeType: 'application/vnd.apple.pkpass' },
+ { fileName: 'attachment-3.ics', kind: 'ics', mimeType: 'text/calendar' },
+ { fileName: 'scan.JPG', kind: 'jpeg', mimeType: 'image/jpeg' },
+ { fileName: 'pass.png', kind: 'png', mimeType: 'image/png' },
+ ]);
+ expect(walked.attachments[0].data.equals(PDF)).toBe(true);
+ expect(walked.attachments[2].data.toString('utf8')).toBe(ICS);
+ expect(walked.skippedAttachments).toBe(0);
+ // The calendar is an attachment, not body text.
+ expect(walked.body).toBe('Booking ABC123');
+ });
+
+ it('MIME-WALK-021: a layout image goes, a WebP the person attached stays', () => {
+ const walked = walkMail(
+ mixed(
+ 'Booking',
+ part('image/png', null, PNG, ['Content-ID: <logo@airline>', 'Content-Disposition: inline']),
+ part('image/webp', 'photo.webp', WEBP),
+ ),
+ )!;
+ expect(walked.attachments.map((a) => a.kind)).toEqual(['webp']);
+ expect(walked.skippedAttachments).toBe(0);
+ });
+
+ it('MIME-WALK-022: a file that is not what it claims is skipped, a type no booking travels in ignored', () => {
+ const walked = walkMail(
+ mixed(
+ 'Booking',
+ part('application/pdf', 'ticket.pdf', Buffer.from('MZ not a pdf')),
+ part('image/png', 'pass.png', JPEG),
+ part('text/calendar', 'invite.ics', 'just text'),
+ part('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'terms.docx', 'PK'),
+ ),
+ )!;
+ expect(walked.attachments).toEqual([]);
+ expect(walked.skippedAttachments).toBe(3);
+ });
+
+ it('MIME-WALK-023: past the count limit the rest are skipped and counted', () => {
+ const pdfs = Array.from({ length: MAX_MAIL_ATTACHMENTS + 2 }, (_, i) => part('application/pdf', `t${i}.pdf`, PDF));
+ const walked = walkMail(mixed('Booking', ...pdfs))!;
+ expect(walked.attachments).toHaveLength(MAX_MAIL_ATTACHMENTS);
+ expect(walked.skippedAttachments).toBe(2);
+ });
+
+ it('MIME-WALK-024: an attachment past the size limit is left out', () => {
+ const big = Buffer.concat([PDF, Buffer.alloc(MAX_MAIL_ATTACHMENT_BYTES)]);
+ const walked = walkMail(mixed('Booking', part('application/pdf', 'big.pdf', big)))!;
+ expect(walked.attachments).toEqual([]);
+ expect(walked.skippedAttachments).toBe(1);
+ });
+
+ it('MIME-WALK-025: a file name loses its path and control characters, an empty one is made up', () => {
+ const walked = walkMail(
+ mixed(
+ 'Booking',
+ part('application/pdf', '../../etc/ticket\u0007.pdf', PDF),
+ part('application/pdf', '..', PDF),
+ ),
+ )!;
+ expect(walked.attachments.map((a) => a.fileName)).toEqual(['ticket.pdf', 'attachment-2.pdf']);
+ });
+
+ it('MIME-WALK-026: nothing is fetched, a remote image stays a string in the markup that is dropped', () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ const walked = walkMail(
+ mail(
+ 'Content-Type: text/html; charset=utf-8',
+ '',
+ '<p>Booking ABC123</p><img src="https://tracker.example/pixel.gif">',
+ '<link rel="stylesheet" href="https://x.example/a.css">',
+ '',
+ ),
+ )!;
+ expect(walked.body).toBe('Booking ABC123');
+ expect(walked.attachments).toEqual([]);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});