aboutsummaryrefslogtreecommitdiff
path: root/deno/mail-relay/mail.ts
blob: 94944b079529ee7da3c4a9d8bc01777f94d0e90b (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
import { encodeBase64 } from "@std/encoding/base64";
import { parse } from "@std/csv/parse";
import { simpleParseMail } from "./mail-parsing.ts";

export class Mail {
  #raw;
  #parsed;

  constructor(raw: string) {
    this.#raw = raw;
    this.#parsed = simpleParseMail(raw);
  }

  get raw() {
    return this.#raw;
  }

  set raw(value) {
    this.#raw = value;
    this.#parsed = simpleParseMail(value);
  }

  get parsed() {
    return this.#parsed;
  }

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

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

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

export interface MailDeliverRecipientResult {
  kind: "success" | "failure";
  message?: string;
  cause?: unknown;
}

export class MailDeliverResult {
  message?: string;
  smtpMessage?: string;
  recipients = new Map<string, MailDeliverRecipientResult>();
  constructor(public mail: Mail) {}

  get hasFailure() {
    return this.recipients.values().some((v) => v.kind !== "success");
  }

  generateLogMessage(prefix: string) {
    const lines = [];
    if (this.message != null) lines.push(`${prefix} message: ${this.message}`);
    if (this.smtpMessage != null) {
      lines.push(`${prefix} smtpMessage: ${this.smtpMessage}`);
    }
    for (const [name, result] of this.recipients.entries()) {
      const { kind, message, cause } = result;
      lines.push(`${prefix}   (${name}): ${kind} ${message} ${cause}`);
    }
    return lines.join("\n");
  }
}

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

  constructor(public logTag: string, public mail: Mail) {
    this.result = new MailDeliverResult(this.mail);
  }
}

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

export abstract class MailDeliverer {
  #counter = 1;
  #last?: Promise<void>;

  abstract name: string;
  preHooks: MailDeliverHook[] = [];
  postHooks: MailDeliverHook[] = [];

  constructor(public sync: boolean) {}

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

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

  async #deliverCore(context: MailDeliverContext) {
    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);
    }
  }

  async deliver(options: {
    mail: Mail;
    recipients?: string[];
    logTag?: string;
  }): Promise<MailDeliverResult> {
    const logTag = options.logTag ?? `[${this.name} ${this.#counter}]`;
    this.#counter++;

    if (this.#last != null) {
      console.info(logTag, "Wait for last delivering done...");
      await this.#last;
    }

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

    console.info(context.logTag, "Begin to deliver mail...");

    const deliverPromise = this.#deliverCore(context);

    if (this.sync) {
      this.#last = deliverPromise.then(() => {}, () => {});
    }

    await deliverPromise;
    this.#last = undefined;

    console.info(context.logTag, "Deliver result:");
    console.info(context.result.generateLogMessage(context.logTag));

    if (context.result.hasFailure) {
      throw new Error("Failed to deliver to some recipients.");
    }

    return context.result;
  }
}

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

  callback(context: MailDeliverContext) {
    if (context.recipients.size !== 0) {
      console.warn(
        context.logTag,
        "Recipients are already filled, skip inferring from headers.",
      );
    } else {
      [...context.mail.parsed.recipients].filter((r) =>
        r.endsWith("@" + this.mailDomain)
      ).forEach((r) => context.recipients.add(r));

      console.info(
        context.logTag,
        "Use recipients inferred 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) {
      console.info(
        context.logTag,
        "Use fallback recipients:" + [...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(logTag: string): Promise<Map<string, string>> {
    const result = new Map();
    if ((await Deno.stat(this.#aliasFile)).isFile) {
      const text = await Deno.readTextFile(this.#aliasFile);
      const csv = parse(text);
      for (const [real, ...aliases] of csv) {
        aliases.forEach((a) => result.set(a, real));
      }
    } else {
      console.warn(
        logTag,
        `Recipient alias file ${this.#aliasFile} is not found.`,
      );
    }
    return result;
  }

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