/** * Isomorphic helper functions for email parsing, validation, and MIME string formatting. */ import { extractErrorMsg, getSaferSubstring } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { Ib } from '@ibgib/ts-gib/dist/types.mjs'; import { DEFAULT_EMAIL_CHARSET, EMAIL_ATOM } from './email-constants.mjs'; import { EmailAddress, EmailData_V1, EmailIb_V1, OutboundEmail } from './email-types.mjs'; const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; /** * Validates whether an email string matches standard email formatting. */ export function validateEmail(email: string): boolean { if (!email || typeof email !== 'string') { return false; } return EMAIL_REGEX.test(email.trim()); } /** Alias for validateEmail for email address format checking. */ export function validateEmailAddress(email: string): boolean { return validateEmail(email); } /** * Sanitizes header values by stripping carriage return (\r) and newline (\n) characters * to prevent MIME header injection. */ export function sanitizeHeaderValue(val: string): string { if (!val || typeof val !== 'string') { return ''; } return val.replace(/[\r\n]/g, '').trim(); } /** * Parses a string or EmailAddress object into a normalized EmailAddress object. * Examples: * - "Alice " -> { name: "Alice", address: "alice@example.com" } * - "alice@example.com" -> { address: "alice@example.com" } */ export function parseEmailAddress(addr: EmailAddress | string): EmailAddress { if (typeof addr === 'object' && addr !== null) { return { address: sanitizeHeaderValue(addr.address).toLowerCase(), name: addr.name ? sanitizeHeaderValue(addr.name) : undefined, }; } const str = sanitizeHeaderValue(addr || ''); const match = str.match(/^(?:"?([^"]*)"?\s+)?<([^>]+)>$/); if (match) { const name = match[1]?.trim(); const address = match[2]?.trim().toLowerCase(); return { address, name: name || undefined, }; } return { address: str.toLowerCase() }; } /** * Formats an EmailAddress or string into RFC 2822 format (e.g. `"Alice" `). */ export function formatEmailAddress(addr: EmailAddress | string): string { const parsed = parseEmailAddress(addr); if (parsed.name) { return `"${parsed.name}" <${parsed.address}>`; } return parsed.address; } /** * Parses raw MIME headers string or header record into a key-value record with normalized header names. */ export function parseRawMimeHeaders(raw: string | Record): Record { if (typeof raw === 'object' && raw !== null) { return { ...raw }; } const headers: Record = {}; if (!raw || typeof raw !== 'string') { return headers; } // Header block ends at double newline const headerBlock = raw.split(/\r?\n\r?\n/)[0] || raw; // Unfold multi-line headers const unfolded = headerBlock.replace(/\r?\n[ \t]+/g, ' '); const lines = unfolded.split(/\r?\n/); for (const line of lines) { const colonIdx = line.indexOf(':'); if (colonIdx > 0) { const key = line.slice(0, colonIdx).trim(); const value = line.slice(colonIdx + 1).trim(); headers[key] = value; } } return headers; } /** * Formats an OutboundEmail object into a raw MIME string (RFC 2822). */ export function formatRawMimeString(email: OutboundEmail, charset: string = DEFAULT_EMAIL_CHARSET): string { const fromStr = formatEmailAddress(email.from); const toStrs = email.to.map(t => formatEmailAddress(t)).join(', '); const lines: string[] = [ `From: ${fromStr}`, `To: ${toStrs}`, ]; if (email.cc && email.cc.length > 0) { lines.push(`Cc: ${email.cc.map(c => formatEmailAddress(c)).join(', ')}`); } if (email.replyTo) { lines.push(`Reply-To: ${formatEmailAddress(email.replyTo)}`); } lines.push(`Subject: ${sanitizeHeaderValue(email.subject)}`); if (email.headers) { for (const [key, val] of Object.entries(email.headers)) { lines.push(`${sanitizeHeaderValue(key)}: ${sanitizeHeaderValue(val)}`); } } const hasText = Boolean(email.textBody); const hasHtml = Boolean(email.htmlBody); if (hasText && hasHtml) { const boundary = `----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`; lines.push(`Content-Type: multipart/alternative; boundary="${boundary}"`); lines.push(''); lines.push(`--${boundary}`); lines.push(`Content-Type: text/plain; charset=${charset}`); lines.push('Content-Transfer-Encoding: 7bit'); lines.push(''); lines.push(email.textBody || ''); lines.push(`--${boundary}`); lines.push(`Content-Type: text/html; charset=${charset}`); lines.push('Content-Transfer-Encoding: 7bit'); lines.push(''); lines.push(email.htmlBody || ''); lines.push(`--${boundary}--`); } else if (hasHtml) { lines.push(`Content-Type: text/html; charset=${charset}`); lines.push('Content-Transfer-Encoding: 7bit'); lines.push(''); lines.push(email.htmlBody || ''); } else { lines.push(`Content-Type: text/plain; charset=${charset}`); lines.push('Content-Transfer-Encoding: 7bit'); lines.push(''); lines.push(email.textBody || ''); } return lines.join('\r\n'); } /** * Decodes a quoted-printable encoded string. */ export function decodeQuotedPrintable(str: string): string { if (!str || typeof str !== 'string') { return ''; } return str .replace(/=\r?\n/g, '') // remove soft line breaks .replace(/=([0-9A-Fa-f]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16))); } /** * Constructs the standard 'ib' string for an Email stone. * Format: `email ` * * Subject and body content are deliberately excluded to ensure the `ib` remains * a compact, space-delimited metadata locator. MessageId is sanitized via getSaferSubstring. */ export async function getEmailIb({ data, timestampInTicks, messageId, }: { data?: Partial; timestampInTicks?: string | number; messageId?: string; }): Promise { const lc = `[${getEmailIb.name}]`; try { const rawMsgId = messageId || data?.messageId || ''; if (!rawMsgId) { throw new Error(`messageId required for EmailIb (E: b65c19284fa943ba8741b659c8120349)`); } let ticks = timestampInTicks; if (!ticks && data?.receivedAtIso) { const parsedDate = new Date(data.receivedAtIso); ticks = isNaN(parsedDate.getTime()) ? Date.now().toString() : parsedDate.getTime().toString(); } else if (!ticks) { ticks = Date.now().toString(); } else { ticks = ticks.toString(); } // Sanitize messageId using getSaferSubstring to guarantee no spaces or forbidden characters in space-delimited ib const cleanMsgId = getSaferSubstring({ text: rawMsgId, length: 64, replaceMap: { ' ': '_', '<': '', '>': '' }, }) || 'noid'; return [ EMAIL_ATOM, ticks, cleanMsgId, ].join(' '); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Parses a standard Email 'ib' string into its constituent parts. * Expected format: `email ` */ export async function parseEmailIb({ ib, }: { ib: Ib; }): Promise { const lc = `[${parseEmailIb.name}]`; try { const parts = ib.split(' '); if (parts.length < 3) { throw new Error(`Invalid email ib. Expected at least 3 parts [${EMAIL_ATOM} timestampInTicks messageId]. Got ${parts.length}. (E: c791f42a983b49ab89e13467b415a782)`); } const [ atom, timestampInTicks, ...messageIdParts ] = parts; if (atom !== EMAIL_ATOM) { throw new Error(`Atom mismatch. Expected ${EMAIL_ATOM}. Got ${atom}. (E: 8194cf219ab34689ab45e032bfa12850)`); } const messageId = messageIdParts.join(' '); return { atom, timestampInTicks, messageId, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } }