diff options
Diffstat (limited to 'services/docker/mail-server/relay/mail.ts')
-rw-r--r-- | services/docker/mail-server/relay/mail.ts | 240 |
1 files changed, 240 insertions, 0 deletions
diff --git a/services/docker/mail-server/relay/mail.ts b/services/docker/mail-server/relay/mail.ts new file mode 100644 index 0000000..a16bdfa --- /dev/null +++ b/services/docker/mail-server/relay/mail.ts @@ -0,0 +1,240 @@ +import { encodeBase64 } from "@std/encoding/base64"; +import emailAddresses from "email-addresses"; + +import { getLogger } from "./logger.ts"; + +class MailParseError extends Error { + constructor( + message: string, + public readonly mail: Mail, + public readonly lineNumber?: number, + options?: ErrorOptions, + ) { + if (lineNumber != null) message += `(at line ${lineNumber})`; + super(message, options); + } +} + +interface ParsedMail { + sections: { + header: string; + body: string; + }; + /** + * The empty line between headers and body. + */ + sep: string; + eol: string; +} + +export class Mail { + date?: Date; + messageId?: string; + + constructor(public raw: string) {} + + toUtf8Bytes(): Uint8Array { + const utf8Encoder = new TextEncoder(); + return utf8Encoder.encode(this.raw); + } + + toBase64(): string { + return encodeBase64(this.raw); + } + + simpleParse(): ParsedMail { + const twoEolMatch = this.raw.match(/(\r?\n)(\r?\n)/); + if (twoEolMatch == null) { + throw new MailParseError( + "No header/body section separator (2 successive EOLs) found.", + this, + ); + } + + const [eol, sep] = [twoEolMatch[1], twoEolMatch[2]]; + + if (eol !== sep) { + getLogger().warn("Different EOLs (\\r\\n, \\n) found."); + } + + return { + sections: { + header: this.raw.slice(0, twoEolMatch.index!), + body: this.raw.slice(twoEolMatch.index! + eol.length + sep.length), + }, + sep, + eol, + }; + } + + simpleParseHeaders(): [key: string, value: string][] { + const { sections } = this.simpleParse(); + const headers: [string, string][] = []; + + let field: string | null = null; + let lineNumber = 1; + + const handleField = () => { + if (field == null) return; + const sepPos = field.indexOf(":"); + if (sepPos === -1) { + throw new MailParseError( + "No ':' in the header field.", + this, + lineNumber, + ); + } + headers.push([field.slice(0, sepPos).trim(), field.slice(sepPos + 1)]); + field = null; + }; + + for (const line of sections.header.trimEnd().split(/\r?\n|\r/)) { + if (line.match(/^\s/)) { + if (field == null) { + throw new MailParseError( + "Header field starts with a space.", + this, + lineNumber, + ); + } + field += line; + } else { + handleField(); + field = line; + } + lineNumber += 1; + } + + handleField(); + + return headers; + } + + simpleParseDate<T = undefined>( + invalidValue: T | undefined = undefined, + ): Date | T | undefined { + const headers = this.simpleParseHeaders(); + for (const [key, value] of headers) { + if (key.toLowerCase() === "date") { + const date = new Date(value); + if (isNaN(date.getTime())) { + getLogger().warn(`Invalid date string (${value}) found in header.`); + return invalidValue; + } + return date; + } + } + return undefined; + } + + simpleParseReceipts( + options?: { domain?: string; headers?: string[] }, + ): string[] { + const headers = options?.headers ?? ["to", "cc", "bcc", "x-original-to"]; + const receipts = new Set<string>(); + for (const [key, value] of this.simpleParseHeaders()) { + if (headers.includes(key.toLowerCase())) { + emailAddresses.parseAddressList(value)?.flatMap((a) => + a.type === "mailbox" ? a.address : a.addresses.map((a) => a.address) + )?.forEach((a) => receipts.add(a)); + } + } + const domain = options?.domain; + if (domain != null) { + return [...receipts].filter((r) => r.endsWith(domain)); + } + return [...receipts]; + } + + // TODO: Add folding. + appendHeaders(headers: [key: string, value: string][]) { + const { sections, sep, eol } = this.simpleParse(); + + this.raw = sections.header + eol + + headers.map(([k, v]) => `${k}: ${v}`).join(eol) + eol + sep + + sections.body; + } +} + +export type MailDeliverResultKind = "done" | "fail" | "retry"; + +export interface MailDeliverReceiptResult { + kind: MailDeliverResultKind; + message: string; + cause?: unknown; +} + +export class MailDeliverResult { + readonly receipts: Map<string, MailDeliverReceiptResult> = new Map(); + + add( + receipt: string, + kind: MailDeliverResultKind, + message: string, + cause?: unknown, + ) { + this.receipts.set(receipt, { kind, message, cause }); + } + + set(receipt: string, result: MailDeliverReceiptResult) { + this.receipts.set(receipt, result); + } + + [Symbol.for("Deno.customInspect")]() { + return [ + ...this.receipts.entries().map(([receipt, result]) => + `${receipt}[${result.kind}]: ${result.message}` + ), + ].join("\n"); + } +} + +export class MailDeliverContext { + readonly result = new MailDeliverResult(); + constructor(public mail: Mail) { + } +} + +export type MailDeliverHook = (context: MailDeliverContext) => Promise<void>; + +export abstract class MailDeliverer { + abstract readonly name: string; + preHooks: MailDeliverHook[] = []; + postHooks: MailDeliverHook[] = []; + + protected abstract doDeliver( + mail: Mail, + context: MailDeliverContext, + ): Promise<void>; + + async deliverRaw(rawMail: string): Promise<Mail> { + const mail = new Mail(rawMail); + await this.deliver(mail); + return mail; + } + + async deliver(mail: Mail): Promise<MailDeliverResult> { + getLogger().log(`Begin to deliver mail via ${this.name}...`); + + const context = new MailDeliverContext(mail); + + for (const hook of this.preHooks) { + await hook(context); + } + + await this.doDeliver(context.mail, context); + + for (const hook of this.postHooks) { + await hook(context); + } + + getLogger().log("Deliver result:", context.result); + + if (context.result.receipts.values().some((r) => r.kind !== "done")) { + getLogger().warn(context.result); + throw new Error("Mail failed to deliver."); + } + + return context.result; + } +} |