aboutsummaryrefslogtreecommitdiff
path: root/deno/mail-relay/mail-parsing.ts
blob: 7e7625781987c626de6a0e54d79cab3b252d4fc2 (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
import emailAddresses from "email-addresses";

class MailSimpleParseError extends Error {}

function lazy<T>(calculator: () => T): () => T {
  const tag = new Object();
  let cache: typeof tag | T = tag;
  return () => {
    if (cache === tag) cache = calculator();
    return cache as T;
  };
}

class MailSimpleParsedHeaders {
  #headerSection;

  #headers = lazy(() => {
    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.#headerSection.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 headers;
  });

  #messageId = lazy(() => {
    const messageIdField = this.#getFirst("message-id");
    if (messageIdField == null) return undefined;

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

  #date = lazy(() => {
    const dateField = this.#getFirst("date");
    if (dateField == null) return undefined;

    const date = new Date(dateField);
    if (isNaN(date.getTime())) {
      console.warn(`Invalid date string (${dateField}) found in header.`);
      return undefined;
    }
    return date;
  });

  #from = lazy(() => {
    const fromField = this.#getFirst("from");
    if (fromField == null) return undefined;

    const addr = emailAddresses.parseOneAddress(fromField);
    return addr?.type === "mailbox" ? addr.address : undefined;
  });

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

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

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

  get messageId() {
    return this.#messageId();
  }
  get date() {
    return this.#date();
  }
  get from() {
    return this.#from();
  }
  get recipients() {
    return this.#recipients();
  }

  toList(): [string, string][] {
    return [...this.#headers()];
  }
}

class MailSimpleParsed {
  #raw;

  #sections = lazy(() => {
    const twoEolMatch = this.#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) {
      console.warn("Different EOLs (\\r\\n, \\n) found.");
    }

    return {
      header: this.#raw.slice(0, twoEolMatch.index!),
      body: this.#raw.slice(twoEolMatch.index! + eol.length + sep.length),
      eol,
      sep,
    };
  });

  #headers = lazy(() => {
    return new MailSimpleParsedHeaders(this.header);
  });

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

  get header() {
    return this.#sections().header;
  }
  get body() {
    return this.#sections().body;
  }
  get sep() {
    return this.#sections().sep;
  }
  get eol() {
    return this.#sections().eol;
  }

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

  get date() {
    return this.headers.date;
  }

  get messageId() {
    return this.headers.messageId;
  }

  get from() {
    return this.headers.from;
  }

  get recipients() {
    return this.headers.recipients;
  }
}

export function simpleParseMail(raw: string): MailSimpleParsed {
  return new MailSimpleParsed(raw);
}