From 327539df14494db3cbb3213f624fba4a0707846f Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 23 Nov 2026 14:59:02 +0100 Subject: [PATCH] fix(mail-ingest): read forwarded attributions and HTML tags in linear time A long line of reply verbs, or HTML with line break, script or style tags that never close, made the mail walk backtrack once per word and block the server. Attribution lines past 500 characters are no longer tested. --- server/src/nest/llm-parse/mime-walker.ts | 13 +++++-- server/src/nest/llm-parse/text-extract.ts | 28 +++++++++++-- .../unit/nest/llm-parse/mime-walker.test.ts | 39 +++++++++++++++++++ .../unit/nest/llm-parse/text-extract.test.ts | 9 +++++ 4 files changed, 81 insertions(+), 8 deletions(-) diff --git a/server/src/nest/llm-parse/mime-walker.ts b/server/src/nest/llm-parse/mime-walker.ts index 2a68b85ee..dbdebebb5 100644 --- a/server/src/nest/llm-parse/mime-walker.ts +++ b/server/src/nest/llm-parse/mime-walker.ts @@ -73,6 +73,8 @@ export const MAX_MAIL_ATTACHMENT_BYTES = 10 * 1024 * 1024; 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; +/** A reply attribution is a short line; a longer one is never tested as one. */ +const MAX_ATTRIBUTION_LINE = 500; const ENVELOPE_HEADERS: [keyof MailEnvelope, string][] = [ ['from', 'from'], @@ -282,7 +284,7 @@ function safeFileName(name: string, kind: MailAttachmentKind, position: number): } /** 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; +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. @@ -360,8 +362,11 @@ const FORWARD_MARKER = new RegExp(String.raw`^\s*[-_]{2,}\s*(?:${FORWARD_MARKER_ 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; +/** + * "On 1 May, Ana wrote:", the line above a quoted reply, which names the sender. + * The lookahead checks the closing colon first, which keeps a long line without one linear. + */ +const ATTRIBUTION = /^(?=.*:\s*$)\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); @@ -403,7 +408,7 @@ function unwrapLayer(lines: string[]): { lines: string[]; changed: boolean } { } else if (bareBlockStarts[i]) { i = skipHeaderBlock(lines, i); changed = true; - } else if (ATTRIBUTION.test(line)) { + } else if (line.length <= MAX_ATTRIBUTION_LINE && ATTRIBUTION.test(line)) { i++; changed = true; } else if (/^\s*>/.test(line)) { diff --git a/server/src/nest/llm-parse/text-extract.ts b/server/src/nest/llm-parse/text-extract.ts index 53b0688bb..61f3d3454 100644 --- a/server/src/nest/llm-parse/text-extract.ts +++ b/server/src/nest/llm-parse/text-extract.ts @@ -97,10 +97,7 @@ function decodeEntities(s: string): string { * tail once per bracket. */ export function stripMarkup(s: string): string { - const withoutTags = stripHtmlTags( - s.replace(//gi, ' ').replace(//gi, ' '), - ' ', - ); + const withoutTags = stripHtmlTags(dropElement(dropElement(s, 'script'), 'style'), ' '); // Entities come last so that a decoded `<` cannot turn into a tag the // stripper would then eat. return decodeEntities(withoutTags) @@ -109,6 +106,29 @@ export function stripMarkup(s: string): string { .trim(); } +/** + * Replace each `...` with a space, as `//gi` + * did. Written as a scan because that pattern rescans the tail from every + * opening tag when no closing one follows. + */ +function dropElement(s: string, name: string): string { + const open = new RegExp(`<${name}`, 'gi'); + const close = new RegExp(``, 'gi'); + let out = ''; + let cursor = 0; + for (;;) { + open.lastIndex = cursor; + const start = open.exec(s); + if (!start) break; + close.lastIndex = start.index + start[0].length; + const end = close.exec(s); + if (!end) break; + out += `${s.slice(cursor, start.index)} `; + cursor = end.index + end[0].length; + } + return out + s.slice(cursor); +} + /** Whitespace cleanup for text that is already plain — no tags to strip out. */ export function collapseWhitespace(s: string): string { return s diff --git a/server/tests/unit/nest/llm-parse/mime-walker.test.ts b/server/tests/unit/nest/llm-parse/mime-walker.test.ts index 0c1cadfe7..469fd8d7f 100644 --- a/server/tests/unit/nest/llm-parse/mime-walker.test.ts +++ b/server/tests/unit/nest/llm-parse/mime-walker.test.ts @@ -275,6 +275,45 @@ describe('walkMail: forwarded and quoted messages', () => { expect(walked.forwardLayers).toBe(0); }, ); + + it('MIME-WALK-018: an attribution goes in all three languages, a long line of the verbs is read in linear time', () => { + const attributions = [ + 'Am 12.05.2025 um 10:15 schrieb Ben :', + 'Le 12 mai 2025 à 10:15, Ben a écrit :', + 'On Mon, 12 May 2025 at 10:15, Ben wrote:', + ]; + const quoted = walk( + mail( + 'From: ana@example.org', + 'Content-Type: text/plain; charset=iso-8859-1', + '', + ...attributions, + 'Ferry F-12', + '', + ), + ); + expect(quoted.body).toBe('Ferry F-12'); + + const lines = [ + `am ${' schrieb '.repeat(25_000)}`, + `am ${' schrieb :'.repeat(25_000)}x`, + `on ${' wrote x'.repeat(25_000)}`, + `le ${' a écrit x'.repeat(25_000)}`, + ]; + const started = Date.now(); + const walked = walk(mail('From: ana@example.org', 'Content-Type: text/plain', '', ...lines, '')); + expect(Date.now() - started).toBeLessThan(1000); + expect(walked.body.split('\n')).toHaveLength(lines.length); + }); + + it('MIME-WALK-019: an HTML body of line break tags that never close is read in linear time', () => { + const started = Date.now(); + const walked = walk( + mail('From: ana@example.org', 'Content-Type: text/html', '', `Ferry F-12${' { diff --git a/server/tests/unit/nest/llm-parse/text-extract.test.ts b/server/tests/unit/nest/llm-parse/text-extract.test.ts index 5ebfc407d..8b15d4165 100644 --- a/server/tests/unit/nest/llm-parse/text-extract.test.ts +++ b/server/tests/unit/nest/llm-parse/text-extract.test.ts @@ -296,5 +296,14 @@ describe('text-extract', () => { // first `<` behind — a different sanitiser output on malformed markup. expect(await extractText(Buffer.from('3 < 4 and 5'), 'a.html')).toBe('3 5'); }); + + it('drops script and style elements whatever the case, and stays linear on ones that never close', async () => { + const html = 'abcd'; + expect(await extractText(Buffer.from(html), 'a.html')).toBe('a b c d'); + const started = Date.now(); + const open = await extractText(Buffer.from(`e${'