aboutsummaryrefslogtreecommitdiff
path: root/deno/mail-relay/mail.ts
blob: 8c977fea0f8f0dbe8277d5c3027f6eb06f8d01d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import { encodeBase64 } from "@std/encoding/base64";
import { parse } from "@std/csv/parse";
import emailAddresses from "email-addresses";

import { Logger } from "@crupest/base/log";

class MailSimpleParseError extends Error {}

class MailSimpleParsedHeaders {
  #logger;

  constructor(
    logger: Logger | undefined,
    public fields: [key: string, value: string][],
  ) {
    this.#logger = logger;
  }

  getFirst(fieldKey: string): string | undefined {
    for (const [key, value] of this.fields) {
      if (key.toLowerCase() === fieldKey.toLowerCase()) return value;
    }
    return undefined;
  }

  messageId(): string | undefined {
    const messageIdField = this.getFirst("message-id");
    if (messageIdField == null) return undefined;

    const match = messageIdField.match(/\<(.*?)\>/);
    if (match != null) {
      return match[1];
    } else {
      this.#logger?.warn("Invalid message-id header of mail: ", messageIdField);
      return undefined;
    }
  }

  date(invalidToUndefined: boolean = true): Date | undefined {
    const dateField = this.getFirst("date");
    if (dateField == null) return undefined;

    const date = new Date(dateField);
    if (invalidToUndefined && isNaN(date.getTime())) {
      this.#logger?.warn(`Invalid date string (${dateField}) found in header.`);
      return undefined;
    }
    return date;
  }

  recipients(options?: { domain?: string; headers?: string[] }): Set<string> {
    const domain = options?.domain;
    const headers = options?.headers ?? ["to", "cc", "bcc", "x-original-to"];
    const recipients = new Set<string>();
    for (const [key, value] of this.fields) {
      if (headers.includes(key.toLowerCase())) {
        emailAddresses
          .parseAddressList(value)
          ?.flatMap((a) => (a.type === "mailbox" ? a : a.addresses))
          ?.forEach(({ address }) => {
            if (domain == null || address.endsWith(domain)) {
              recipients.add(address);
            }
          });
      }
    }
    return recipients;
  }
}

class MailSimpleParsedSections {
  header: string;
  body: string;
  eol: string;
  sep: string;

  #logger;

  constructor(logger: Logger | undefined, raw: string) {
    this.#logger = logger;

    const twoEolMatch = raw.match(/(\r?\n)(\r?\n)/);
    if (twoEolMatch == null) {
      throw new MailSimpleParseError(
        "No header/body section separator (2 successive EOLs) found.",
      );
    }

    const [eol, sep] = [twoEolMatch[1], twoEolMatch[2]];

    if (eol !== sep) {
      logger?.warn("Different EOLs (\\r\\n, \\n) found.");
    }

    this.header = raw.slice(0, twoEolMatch.index!);
    this.body = raw.slice(twoEolMatch.index! + eol.length + sep.length);
    this.eol = eol;
    this.sep = sep;
  }

  headers(): MailSimpleParsedHeaders {
    const headers = [] as [key: string, value: string][];

    let field: string | null = null;
    let lineNumber = 1;

    const handleField = () => {
      if (field == null) return;
      const sepPos = field.indexOf(":");
      if (sepPos === -1) {
        throw new MailSimpleParseError(`No ':' in the header line: ${field}`);
      }
      headers.push([field.slice(0, sepPos).trim(), field.slice(sepPos + 1)]);
      field = null;
    };

    for (const line of this.header.trimEnd().split(/\r?\n|\r/)) {
      if (line.match(/^\s/)) {
        if (field == null) {
          throw new MailSimpleParseError("Header section starts with a space.");
        }
        field += line;
      } else {
        handleField();
        field = line;
      }
      lineNumber += 1;
    }

    handleField();

    return new MailSimpleParsedHeaders(this.#logger, headers);
  }
}

export class Mail {
  constructor(public raw: string) {}

  toUtf8Bytes(): Uint8Array {
    const utf8Encoder = new TextEncoder();
    return utf8Encoder.encode(this.raw);
  }

  toBase64(): string {
    return encodeBase64(this.raw);
  }

  startSimpleParse(logger?: Logger) {
    return { sections: () => new MailSimpleParsedSections(logger, this.raw) };
  }

  simpleFindAllAddresses(): string[] {
    const re = /,?\<?([a-z0-9_'+\-\.]+\@[a-z0-9_'+\-\.]+)\>?,?/gi;
    return [...this.raw.matchAll(re)].map((m) => m[1]);
  }
}

export type MailDeliverResultKind = "done" | "fail";

export interface MailDeliverRecipientResult {
  kind: MailDeliverResultKind;
  message: string;
  cause?: unknown;
}

export class MailDeliverResult {
  message: string = "";
  recipients: Map<string, MailDeliverRecipientResult> = new Map();

  constructor(public mail: Mail) {}

  hasError(): boolean {
    return (
      this.recipients.size === 0 ||
      this.recipients.values().some((r) => r.kind !== "done")
    );
  }

  [Symbol.for("Deno.customInspect")]() {
    return [
      `message: ${this.message}`,
      ...this.recipients
        .entries()
        .map(
          ([recipient, result]) =>
            `${recipient} [${result.kind}]: ${result.message}`,
        ),
    ].join("\n");
  }
}

export class MailDeliverContext {
  readonly recipients: Set<string> = new Set();
  readonly result;

  constructor(
    public readonly logger: Logger,
    public mail: Mail,
  ) {
    this.result = new MailDeliverResult(this.mail);
  }
}

export interface MailDeliverHook {
  callback(context: MailDeliverContext): Promise<void>;
}

export abstract class MailDeliverer {
  abstract readonly name: string;
  preHooks: MailDeliverHook[] = [];
  postHooks: MailDeliverHook[] = [];

  constructor(protected readonly logger: Logger) {}

  protected abstract doDeliver(
    mail: Mail,
    context: MailDeliverContext,
  ): Promise<void>;

  async deliverRaw(rawMail: string) {
    return await this.deliver({ mail: new Mail(rawMail) });
  }

  async deliver(options: {
    mail: Mail;
    recipients?: string[];
  }): Promise<MailDeliverResult> {
    this.logger.info(`Begin to deliver mail via ${this.name}...`);

    const context = new MailDeliverContext(this.logger, options.mail);
    options.recipients?.forEach((r) => context.recipients.add(r));

    for (const hook of this.preHooks) {
      await hook.callback(context);
    }

    await this.doDeliver(context.mail, context);

    for (const hook of this.postHooks) {
      await hook.callback(context);
    }

    context.logger.info("Deliver result:");
    context.logger.info(context.result);

    if (context.result.hasError()) {
      throw new Error("Mail failed to deliver.");
    }

    return context.result;
  }
}

export abstract class SyncMailDeliverer extends MailDeliverer {
  #last: Promise<void> = Promise.resolve();

  override async deliver(options: {
    mail: Mail;
    recipients?: string[];
  }): Promise<MailDeliverResult> {
    this.logger.info(
      "The mail deliverer is sync. Wait for last delivering done...",
    );
    await this.#last;
    const result = super.deliver(options);
    this.#last = result.then(
      () => {},
      () => {},
    );
    return result;
  }
}

export class RecipientFromHeadersHook implements MailDeliverHook {
  constructor(public mailDomain: string) {}

  callback(context: MailDeliverContext) {
    if (context.recipients.size !== 0) {
      context.logger.warn(
        "Recipients are already filled. Won't set them with ones in headers.",
      );
    } else {
      context.mail
        .startSimpleParse(context.logger)
        .sections()
        .headers()
        .recipients({
          domain: this.mailDomain,
        })
        .forEach((r) => context.recipients.add(r));

      context.logger.info(
        "Recipients found from mail headers: ",
        [...context.recipients].join(" "),
      );
    }
    return Promise.resolve();
  }
}

export class FallbackRecipientHook implements MailDeliverHook {
  constructor(public fallback: Set<string> = new Set()) {}

  callback(context: MailDeliverContext) {
    if (context.recipients.size === 0) {
      context.logger.info(
        "No recipients, fill with fallback: ",
        [...this.fallback].join(" "),
      );
      this.fallback.forEach((a) => context.recipients.add(a));
    }
    return Promise.resolve();
  }
}

export class AliasRecipientMailHook implements MailDeliverHook {
  #aliasFile;

  constructor(aliasFile: string) {
    this.#aliasFile = aliasFile;
  }

  async #parseAliasFile(logger: Logger): Promise<Map<string, string>> {
    const result = new Map();
    if ((await Deno.stat(this.#aliasFile)).isFile) {
      logger.info(`Found recipients alias file: ${this.#aliasFile}.`);
      const text = await Deno.readTextFile(this.#aliasFile);
      const csv = parse(text);
      for (const [real, ...aliases] of csv) {
        aliases.forEach((a) => result.set(a, real));
      }
    }
    return result;
  }

  async callback(context: MailDeliverContext) {
    const aliases = await this.#parseAliasFile(context.logger);
    for (const recipient of [...context.recipients]) {
      const realRecipients = aliases.get(recipient);
      if (realRecipients != null) {
        context.logger.info(
          `Recipient alias resolved: ${recipient} => ${realRecipients}.`,
        );
        context.recipients.delete(recipient);
        context.recipients.add(realRecipients);
      }
    }
  }
}