src/mime.js
// RFC 5322 / MIME parsing helpers for email-organizer. Pure functions, no I/O, Node >= 20 built-ins only.
// All message content is treated as untrusted data: nothing here evaluates, renders or follows it.
import { createHash } from "node:crypto";
const MAX_DEPTH = 8;
const MAX_PARTS = 200;
// ---------------------------------------------------------------------------------------------
// Byte / charset helpers
// ---------------------------------------------------------------------------------------------
const CHARSET_ALIASES = { utf8: "utf-8", "us-ascii": "utf-8", ascii: "utf-8", latin1: "iso-8859-1", "x-unknown": "utf-8", "unicode-1-1-utf-8": "utf-8" };
export function decodeBytes(bytes, charset, warnings) {
const cs = String(charset || "utf-8").trim().replace(/^"|"$/g, "").toLowerCase();
const label = CHARSET_ALIASES[cs] ?? cs;
try {
return new TextDecoder(label, { fatal: false }).decode(bytes);
} catch {
warnings?.push(`Unknown charset "${cs}"; decoded as latin1`);
return Buffer.from(bytes).toString("latin1");
}
}
// Converts a JS string into bytes: ASCII stays as-is, anything else becomes UTF-8. Used for
// quoted-printable bodies whose literal (non-escaped) characters were already decoded by the reader.
function pushStringBytes(bytes, s) {
for (const ch of s) {
const cp = ch.codePointAt(0);
if (cp < 0x80) bytes.push(cp);
else for (const b of Buffer.from(ch, "utf8")) bytes.push(b);
}
}
export function decodeQuotedPrintable(text) {
const s = text.replace(/[ \t]+$/gm, "").replace(/=\n/g, "");
const bytes = [];
let literal = "";
for (let i = 0; i < s.length; i++) {
if (s[i] === "=" && /^[0-9A-Fa-f]{2}$/.test(s.slice(i + 1, i + 3))) {
if (literal) { pushStringBytes(bytes, literal); literal = ""; }
bytes.push(parseInt(s.slice(i + 1, i + 3), 16));
i += 2;
} else {
literal += s[i];
}
}
if (literal) pushStringBytes(bytes, literal);
return Uint8Array.from(bytes);
}
export function decodeBase64(text, warnings) {
const compact = text.replace(/\s+/g, "");
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) warnings?.push("Invalid characters in base64 content were ignored");
else if (compact.length % 4 === 1) warnings?.push("Truncated base64 content");
return new Uint8Array(Buffer.from(compact.replace(/[^A-Za-z0-9+/]/g, ""), "base64"));
}
// ---------------------------------------------------------------------------------------------
// Headers
// ---------------------------------------------------------------------------------------------
// Splits an entity into raw header block and body at the first empty line.
export function splitEntity(text) {
// An entity that starts with an empty line has no headers (allowed for MIME body parts).
if (/^[ \t]*\n/.test(text)) return { headerText: "", body: text.replace(/^[ \t]*\n/, "") };
const m = /\n[ \t]*\n/.exec(text);
if (!m) return { headerText: text, body: "" };
return { headerText: text.slice(0, m.index), body: text.slice(m.index + m[0].length) };
}
// Returns [{name (lower-case), value (unfolded, raw)}] in order. Folded lines are joined (RFC 5322 §2.2.3).
export function parseHeaders(headerText, warnings) {
const headers = [];
for (const line of headerText.split("\n")) {
if (/^[ \t]/.test(line)) {
if (headers.length) headers[headers.length - 1].value += line.replace(/^[ \t]+/, " ");
else warnings?.push("Continuation line before any header was ignored");
continue;
}
if (line.trim() === "") continue;
const idx = line.indexOf(":");
if (idx <= 0 || !/^[\x21-\x39\x3b-\x7e]+$/.test(line.slice(0, idx))) {
warnings?.push(`Malformed header line ignored: ${truncate(line, 60)}`);
continue;
}
headers.push({ name: line.slice(0, idx).toLowerCase(), value: line.slice(idx + 1).trim() });
}
return headers;
}
export function headerValue(headers, name) {
const h = headers.find((x) => x.name === name);
return h ? h.value : null;
}
// RFC 2047 encoded-words: =?charset?B?...?= and =?charset?Q?...?=
const ENCODED_WORD = /=\?([^?\s]+)\?([BbQq])\?([^?\s]*)\?=/g;
export function decodeEncodedWords(value, warnings) {
if (!value || !value.includes("=?")) return value ?? "";
// Whitespace between adjacent encoded-words is not displayed (RFC 2047 §6.2).
const joined = value.replace(/(=\?[^?\s]+\?[BbQq]\?[^?\s]*\?=)\s+(?==\?[^?\s]+\?[BbQq]\?[^?\s]*\?=)/g, "$1");
return joined.replace(ENCODED_WORD, (whole, charset, enc, data) => {
const cs = charset.split("*")[0];
let bytes;
if (enc.toUpperCase() === "B") {
bytes = decodeBase64(data, warnings);
} else {
const raw = [];
const d = data.replace(/_/g, " ");
for (let i = 0; i < d.length; i++) {
if (d[i] === "=" && /^[0-9A-Fa-f]{2}$/.test(d.slice(i + 1, i + 3))) { raw.push(parseInt(d.slice(i + 1, i + 3), 16)); i += 2; }
else raw.push(d.charCodeAt(i) & 0xff);
}
bytes = Uint8Array.from(raw);
}
return decodeBytes(bytes, cs, warnings);
});
}
// Parses `type/subtype; a=b; c="quoted"` (also RFC 2231 `name*=utf-8''%E2%82%AC` and `name*0=` continuations).
export function parseParamHeader(value) {
const parts = [];
let cur = "";
let inQuote = false;
for (let i = 0; i < (value ?? "").length; i++) {
const c = value[i];
if (c === "\\" && inQuote) { cur += value[i + 1] ?? ""; i++; continue; }
if (c === '"') { inQuote = !inQuote; cur += c; continue; }
if (c === ";" && !inQuote) { parts.push(cur); cur = ""; continue; }
cur += c;
}
parts.push(cur);
const main = (parts.shift() ?? "").trim().toLowerCase();
const params = {};
const continued = {};
for (const p of parts) {
const eq = p.indexOf("=");
if (eq < 0) continue;
let key = p.slice(0, eq).trim().toLowerCase();
let val = p.slice(eq + 1).trim();
if (val.startsWith('"') && val.endsWith('"') && val.length >= 2) val = val.slice(1, -1);
const cont = /^([^*]+)\*(\d+)(\*)?$/.exec(key);
if (cont) {
(continued[cont[1]] ??= []).push({ n: Number(cont[2]), val, encoded: Boolean(cont[3]) });
continue;
}
if (key.endsWith("*")) {
key = key.slice(0, -1);
val = decode2231(val, true);
}
params[key] = val;
}
for (const [k, segs] of Object.entries(continued)) {
segs.sort((a, b) => a.n - b.n);
const first = segs[0];
let charset = null;
let out = "";
for (const s of segs) {
let v = s.val;
if (s.encoded) {
if (s === first) {
const m = /^([^']*)'[^']*'(.*)$/.exec(v);
if (m) { charset = m[1] || "utf-8"; v = m[2]; }
}
out += pctDecode(v, charset ?? "utf-8");
} else out += v;
}
params[k] = out;
}
return { value: main, params };
}
function pctDecode(v, charset) {
const bytes = [];
for (let i = 0; i < v.length; i++) {
if (v[i] === "%" && /^[0-9A-Fa-f]{2}$/.test(v.slice(i + 1, i + 3))) { bytes.push(parseInt(v.slice(i + 1, i + 3), 16)); i += 2; }
else pushStringBytes(bytes, v[i]);
}
return decodeBytes(Uint8Array.from(bytes), charset);
}
function decode2231(val, hasCharset) {
if (!hasCharset) return val;
const m = /^([^']*)'[^']*'(.*)$/.exec(val);
if (!m) return val;
return pctDecode(m[2], m[1] || "utf-8");
}
// ---------------------------------------------------------------------------------------------
// Addresses and dates
// ---------------------------------------------------------------------------------------------
export function splitAddressList(value) {
const out = [];
let cur = "";
let depthAngle = 0;
let inQuote = false;
let depthParen = 0;
for (let i = 0; i < (value ?? "").length; i++) {
const c = value[i];
if (c === "\\" && inQuote) { cur += c + (value[i + 1] ?? ""); i++; continue; }
if (c === '"' && depthParen === 0) inQuote = !inQuote;
else if (!inQuote && c === "(") depthParen++;
else if (!inQuote && c === ")" && depthParen > 0) depthParen--;
else if (!inQuote && depthParen === 0 && c === "<") depthAngle++;
else if (!inQuote && depthParen === 0 && c === ">" && depthAngle > 0) depthAngle--;
if ((c === "," || c === ";") && !inQuote && depthAngle === 0 && depthParen === 0) {
if (cur.trim()) out.push(cur.trim());
cur = "";
continue;
}
cur += c;
}
if (cur.trim()) out.push(cur.trim());
return out;
}
const ADDR_RE = /[^\s<>()",;:@]+@[^\s<>()",;:@]+/;
// Returns {name, address} where address is lower-cased (or null if none could be found).
export function parseAddress(raw, warnings) {
const s = decodeEncodedWords(raw ?? "", warnings).trim();
// Group syntax "Undisclosed recipients:;" carries no address.
const angle = /<([^<>]*)>/.exec(s);
let address = null;
let name = "";
if (angle) {
const m = ADDR_RE.exec(angle[1]);
address = m ? m[0].toLowerCase() : null;
name = s.slice(0, angle.index).trim();
} else {
const m = ADDR_RE.exec(s);
address = m ? m[0].toLowerCase() : null;
const comment = /\(([^)]*)\)/.exec(s);
name = comment ? comment[1].trim() : "";
}
name = name.replace(/^"(.*)"$/s, "$1").replace(/\\(.)/g, "$1").trim();
return { name, address };
}
export function formatAddress({ name, address }) {
if (address && name && name.toLowerCase() !== address) return `${name} <${address}>`;
return address ?? name ?? "";
}
const MONTHS = { jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11 };
const ZONES = { ut: 0, utc: 0, gmt: 0, z: 0, est: -300, edt: -240, cst: -360, cdt: -300, mst: -420, mdt: -360, pst: -480, pdt: -420 };
// Strict RFC 5322 date parser (independent of the machine's local timezone). Returns ISO string or null.
export function parseRfc5322Date(value, warnings) {
if (!value) return null;
const s = value.replace(/\([^)]*\)/g, " ").replace(/\s+/g, " ").trim();
const m = /^(?:[A-Za-z]{3},?\s*)?(\d{1,2})\s+([A-Za-z]{3})[a-z]*\s+(\d{2,4})\s+(\d{1,2}):(\d{2})(?::(\d{2}))?\s*([+-]\d{4}|[A-Za-z]{1,5})?$/.exec(s);
if (!m) {
// Accept ISO 8601 with an explicit zone (some exporters emit it); never guess a local zone.
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/i.test(s) && !Number.isNaN(Date.parse(s))) return new Date(Date.parse(s)).toISOString();
warnings?.push(`Unparseable Date header: ${truncate(value, 60)}`);
return null;
}
let year = Number(m[3]);
if (m[3].length === 2) year += year < 50 ? 2000 : 1900;
else if (m[3].length === 3) year += 1900;
const month = MONTHS[m[2].toLowerCase().slice(0, 3)];
if (month === undefined) { warnings?.push(`Unparseable Date header: ${truncate(value, 60)}`); return null; }
let offsetMin = 0;
const zone = m[7];
if (!zone) warnings?.push("Date header has no timezone; assumed UTC");
else if (/^[+-]\d{4}$/.test(zone)) {
const sign = zone[0] === "-" ? -1 : 1;
offsetMin = sign * (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(3, 5)));
if (zone === "-0000") warnings?.push("Date header timezone is -0000 (unknown); assumed UTC");
} else if (ZONES[zone.toLowerCase()] !== undefined) offsetMin = ZONES[zone.toLowerCase()];
else warnings?.push(`Unknown timezone "${zone}" in Date header; assumed UTC`);
const day = Number(m[1]);
const hh = Number(m[4]);
const mm = Number(m[5]);
const ss = Number(m[6] ?? 0);
if (day < 1 || day > 31 || hh > 23 || mm > 59 || ss > 60) { warnings?.push(`Out-of-range Date header: ${truncate(value, 60)}`); return null; }
const ms = Date.UTC(year, month, day, hh, mm, Math.min(ss, 59)) - offsetMin * 60000;
return new Date(ms).toISOString();
}
// ---------------------------------------------------------------------------------------------
// HTML fallback (only used when a message has no text/plain part). Tags are stripped, never rendered.
// ---------------------------------------------------------------------------------------------
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", hellip: "…", mdash: "—", ndash: "–", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“", copy: "©", reg: "®", trade: "™", euro: "€", pound: "£" };
export function decodeEntities(s) {
return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, e) => {
if (e[0] === "#") {
const cp = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : whole;
}
return ENTITIES[e.toLowerCase()] ?? whole;
});
}
export function htmlToText(html) {
return decodeEntities(
html
.replace(/<!--[\s\S]*?-->/g, "")
.replace(/<(script|style|head|title)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "")
.replace(/<br\s*\/?>/gi, "\n")
.replace(/<\/(p|div|li|tr|h[1-6]|blockquote|table|ul|ol)\s*>/gi, "\n")
.replace(/<li\b[^>]*>/gi, "- ")
.replace(/<[^>]+>/g, ""),
)
.replace(/[ \t\u00A0]+/g, " ")
.replace(/ *\n */g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
}
// ---------------------------------------------------------------------------------------------
// MIME entity parsing
// ---------------------------------------------------------------------------------------------
function decodeTransfer(body, cte, charset, warnings) {
const enc = (cte ?? "7bit").trim().toLowerCase();
if (enc === "quoted-printable") return decodeBytes(decodeQuotedPrintable(body), charset, warnings);
if (enc === "base64") return decodeBytes(decodeBase64(body, warnings), charset, warnings);
if (!["7bit", "8bit", "binary", ""].includes(enc)) warnings.push(`Unknown Content-Transfer-Encoding "${enc}"; content left as-is`);
return body;
}
function transferSize(body, cte) {
const enc = (cte ?? "").trim().toLowerCase();
if (enc === "base64") return Math.floor((body.replace(/\s+/g, "").replace(/=+$/, "").length * 3) / 4);
if (enc === "quoted-printable") return decodeQuotedPrintable(body).length;
return Buffer.byteLength(body, "utf8");
}
function splitMultipart(body, boundary, warnings) {
const lines = body.split("\n");
const delim = `--${boundary}`;
const parts = [];
let cur = null;
let closed = false;
for (const line of lines) {
const t = line.replace(/[ \t]+$/, "");
if (t === `${delim}--`) {
if (cur) parts.push(cur.join("\n"));
cur = null;
closed = true;
break;
}
if (t === delim) {
if (cur) parts.push(cur.join("\n"));
cur = [];
continue;
}
if (cur) cur.push(line);
}
if (cur) parts.push(cur.join("\n"));
if (!parts.length && !closed) return null;
if (!closed) warnings.push(`Multipart body is missing its closing boundary "${truncate(boundary, 40)}"`);
return parts;
}
// Parses one MIME entity into a tree: {contentType, params, disposition, filename, headers, body?, parts?}
function parseEntity(text, warnings, depth, counter) {
const { headerText, body } = splitEntity(text);
const headers = parseHeaders(headerText, warnings);
const ct = parseParamHeader(headerValue(headers, "content-type") ?? "text/plain; charset=us-ascii");
let contentType = ct.value || "text/plain";
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) {
warnings.push(`Malformed Content-Type "${truncate(contentType, 40)}"; treated as text/plain`);
contentType = "text/plain";
}
const disp = parseParamHeader(headerValue(headers, "content-disposition") ?? "");
const filename = decodeEncodedWords(disp.params.filename ?? ct.params.name ?? "", warnings);
const node = {
headers,
contentType,
charset: ct.params.charset ?? null,
disposition: disp.value || null,
filename: filename || null,
cte: headerValue(headers, "content-transfer-encoding"),
body,
parts: null,
};
counter.n++;
if (contentType.startsWith("multipart/")) {
if (depth >= MAX_DEPTH) { warnings.push("MIME nesting too deep; inner parts skipped"); return node; }
const boundary = ct.params.boundary;
if (!boundary) {
warnings.push(`${contentType} without a boundary parameter; body treated as plain text`);
node.contentType = "text/plain";
return node;
}
const raw = splitMultipart(body, boundary, warnings);
if (!raw) {
warnings.push(`Boundary "${truncate(boundary, 40)}" not found in multipart body; body treated as plain text`);
node.contentType = "text/plain";
return node;
}
node.parts = [];
for (const p of raw) {
if (counter.n >= MAX_PARTS) { warnings.push(`More than ${MAX_PARTS} MIME parts; remaining parts skipped`); break; }
node.parts.push(parseEntity(p, warnings, depth + 1, counter));
}
}
return node;
}
function isAttachment(node) {
return node.disposition === "attachment" || (Boolean(node.filename) && node.disposition !== "inline");
}
// Walks the tree collecting text/plain, text/html fallbacks and attachment metadata.
function collect(node, out, warnings) {
if (node.parts) {
if (node.contentType === "multipart/alternative") {
const plain = node.parts.find((p) => p.contentType === "text/plain" && !isAttachment(p));
const nestedWithPlain = node.parts.find((p) => p.parts && hasPlain(p));
if (plain) out.text.push(decodeTransfer(plain.body, plain.cte, plain.charset, warnings));
else if (nestedWithPlain) collect(nestedWithPlain, out, warnings);
else {
const html = [...node.parts].reverse().find((p) => p.contentType === "text/html") ?? node.parts.find((p) => p.parts);
if (html?.parts) collect(html, out, warnings);
else if (html) out.html.push(decodeTransfer(html.body, html.cte, html.charset, warnings));
}
// Attachments occasionally hide inside alternatives; still record their metadata.
for (const p of node.parts) if (!p.parts && isAttachment(p)) out.attachments.push(attachmentMeta(p));
return;
}
for (const p of node.parts) collect(p, out, warnings);
return;
}
if (isAttachment(node) || !node.contentType.startsWith("text/")) {
out.attachments.push(attachmentMeta(node));
return;
}
const decoded = decodeTransfer(node.body, node.cte, node.charset, warnings);
if (node.contentType === "text/html") out.html.push(decoded);
else out.text.push(decoded);
}
function hasPlain(node) {
if (!node.parts) return node.contentType === "text/plain" && !isAttachment(node);
return node.parts.some(hasPlain);
}
function attachmentMeta(node) {
return { filename: node.filename ?? "", content_type: node.contentType, size_bytes: transferSize(node.body, node.cte) };
}
// ---------------------------------------------------------------------------------------------
// Message + mailbox parsing
// ---------------------------------------------------------------------------------------------
export function normalizeNewlines(s) {
return s.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
}
export function looksLikeMbox(text) {
return /^From [^\n]*\n/.test(text.replace(/^\s+/, ""));
}
// Splits mbox text into raw messages (mboxrd/mboxo; ">From " lines are unescaped).
export function splitMbox(text) {
const lines = text.replace(/^\s+/, "").split("\n");
const messages = [];
let cur = null;
let prevBlank = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Envelope line: "From " at a message boundary (start or after a blank line), followed by a header line.
const isEnvelope = line.startsWith("From ") && prevBlank && (i === 0 || /^[\x21-\x39\x3b-\x7e]+:/.test(lines[i + 1] ?? ""));
if (isEnvelope) {
if (cur) messages.push(cur.join("\n"));
cur = [];
} else if (cur) {
cur.push(line.replace(/^>(>*From )/, "$1"));
}
prevBlank = line.trim() === "";
}
if (cur) messages.push(cur.join("\n"));
return messages.map((m) => m.replace(/\n+$/, "\n")).filter((m) => m.trim() !== "");
}
export function truncate(s, n) {
const str = String(s);
return str.length > n ? `${str.slice(0, n - 1)}…` : str;
}
export function parseMessage(raw, { maxBodyChars = 20000 } = {}) {
const warnings = [];
const text = normalizeNewlines(raw);
const counter = { n: 0 };
const root = parseEntity(text, warnings, 0, counter);
const h = root.headers;
if (!h.length) warnings.push("No headers found");
const out = { text: [], html: [], attachments: [] };
collect(root, out, warnings);
let body = out.text.join("\n\n").trim();
let source = "text/plain";
if (!body && out.html.length) {
body = htmlToText(out.html.join("\n"));
source = "text/html";
}
if (!body) source = "none";
if (body.length > maxBodyChars) {
body = body.slice(0, maxBodyChars);
warnings.push(`Body truncated to ${maxBodyChars} characters`);
}
const from = parseAddress(headerValue(h, "from") ?? "", warnings);
const list = (name) => h.filter((x) => x.name === name).flatMap((x) => splitAddressList(x.value)).map((a) => formatAddress(parseAddress(a, warnings))).filter(Boolean);
const msgId = (headerValue(h, "message-id") ?? "").trim().replace(/^<|>$/g, "") || null;
const dateRaw = headerValue(h, "date");
const subject = decodeEncodedWords(headerValue(h, "subject") ?? "", warnings).replace(/\s+/g, " ").trim();
const id = msgId ?? `sha256:${createHash("sha256").update(text).digest("hex").slice(0, 16)}`;
return {
id,
message_id: msgId,
from: formatAddress(from),
from_address: from.address,
from_name: from.name,
to: list("to"),
cc: list("cc"),
reply_to: list("reply-to"),
subject,
date: parseRfc5322Date(dateRaw, warnings),
date_raw: dateRaw,
body_text: body,
body_source: source,
list_unsubscribe: headerValue(h, "list-unsubscribe"),
list_id: headerValue(h, "list-id"),
precedence: headerValue(h, "precedence"),
auto_submitted: headerValue(h, "auto-submitted"),
in_reply_to: headerValue(h, "in-reply-to"),
attachments: out.attachments,
warnings,
};
}