@im-more/dsh-mail 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +14 -0
  3. package/lib/index.js +1334 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +49 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +189 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +51 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +55 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +60 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +195 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +33 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +156 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/html.d.ts +30 -0
  22. package/lib/types/html.d.ts.map +1 -0
  23. package/lib/types/html.js +121 -0
  24. package/lib/types/html.js.map +1 -0
  25. package/lib/types/index.d.ts +11 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +10 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/mail.d.ts +24 -0
  30. package/lib/types/mail.d.ts.map +1 -0
  31. package/lib/types/mail.js +26 -0
  32. package/lib/types/mail.js.map +1 -0
  33. package/lib/types/media.d.ts +52 -0
  34. package/lib/types/media.d.ts.map +1 -0
  35. package/lib/types/media.js +81 -0
  36. package/lib/types/media.js.map +1 -0
  37. package/lib/types/modes/html.d.ts +13 -0
  38. package/lib/types/modes/html.d.ts.map +1 -0
  39. package/lib/types/modes/html.js +70 -0
  40. package/lib/types/modes/html.js.map +1 -0
  41. package/lib/types/modes/shared.d.ts +114 -0
  42. package/lib/types/modes/shared.d.ts.map +1 -0
  43. package/lib/types/modes/shared.js +185 -0
  44. package/lib/types/modes/shared.js.map +1 -0
  45. package/lib/types/send.d.ts +26 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +58 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/transport/imap.d.ts +95 -0
  50. package/lib/types/transport/imap.d.ts.map +1 -0
  51. package/lib/types/transport/imap.js +354 -0
  52. package/lib/types/transport/imap.js.map +1 -0
  53. package/package.json +70 -3
  54. package/src/bot.ts +264 -0
  55. package/src/config.ts +98 -0
  56. package/src/decode.ts +275 -0
  57. package/src/errors.ts +199 -0
  58. package/src/html.ts +137 -0
  59. package/src/index.ts +32 -0
  60. package/src/mail.ts +46 -0
  61. package/src/media.ts +102 -0
  62. package/src/modes/html.ts +105 -0
  63. package/src/modes/shared.ts +285 -0
  64. package/src/send.ts +87 -0
  65. package/src/transport/imap.ts +418 -0
  66. package/README.md +0 -3
@@ -0,0 +1,418 @@
1
+ /**
2
+ * IMAP inbound transport: connection lifecycle, scanning, acknowledgement and reconnection.
3
+ *
4
+ * `node-imap` owns IDLE/NOOP keepalive internally, so this transport never sends a keepalive itself. It starts one
5
+ * `Connection` and reuses it for every reconnect (the library resets its own state and keeps listeners). Every
6
+ * `\\Seen` write happens only after the host accepted the message: a crash or a failed intake therefore leaves the
7
+ * message unread, and the next scan delivers it again (the host dedupes by `Message-ID`). A malformed message is the
8
+ * one exception: it is marked seen, because retrying it would fail forever.
9
+ */
10
+
11
+ import { simpleParser } from 'mailparser'
12
+ import type { ParsedMail } from 'mailparser'
13
+ import NodeIMAP from 'node-imap'
14
+ import type { Readable } from 'node:stream'
15
+ import type { Config } from '../config.ts'
16
+ import type { MailSource } from '../decode.ts'
17
+
18
+ /** The `source` field `node-imap` attaches to its errors (`'authentication'`, `'timeout'`, `'socket'`, …). */
19
+ export interface ImapError extends Error {
20
+ source?: string
21
+ }
22
+
23
+ /** The logging surface the transport uses (a `ctx.logger`). */
24
+ export interface MailLogger {
25
+ info(...args: unknown[]): void
26
+ warn(...args: unknown[]): void
27
+ error(...args: unknown[]): void
28
+ debug(...args: unknown[]): void
29
+ }
30
+
31
+ /** What the transport needs from the adapter. */
32
+ export interface ImapTransportOptions {
33
+ config: Config
34
+ logger: MailLogger
35
+ /** Hand one parsed message to the host; rejection means "not accepted", so the message stays unseen. */
36
+ deliver(mail: ParsedMail, source: MailSource): Promise<void>
37
+ /** The connection opened its mailbox and the first scan may run. */
38
+ onOnline(): void
39
+ /** The connection is down and a reconnect is scheduled (`Status.RECONNECT`). */
40
+ onReconnect(): void
41
+ /** A permanent failure (credentials, mailbox) ended the reconnect loop. */
42
+ onOffline(error: unknown): void
43
+ }
44
+
45
+ /** One message read from the server. */
46
+ interface ReadResult {
47
+ uid: number | undefined
48
+ size: number
49
+ mail?: ParsedMail
50
+ error?: unknown
51
+ }
52
+
53
+ /**
54
+ * The delay before the next connection attempt.
55
+ *
56
+ * The fast budget counts consecutive failures: the first `retry.times` dials wait `retry.interval`, later ones wait
57
+ * `retry.lazy`. A successful connection resets the count, so a flap is retried fast again.
58
+ *
59
+ * @param failures - consecutive failures before this attempt.
60
+ * @param retry - the configured retry budget and delays.
61
+ * @returns the delay in milliseconds.
62
+ */
63
+ export function reconnectDelay(
64
+ failures: number,
65
+ retry: Config['retry'],
66
+ ): number {
67
+ return failures < retry.times ? retry.interval : retry.lazy
68
+ }
69
+
70
+ /** The error message of a caught value. */
71
+ function messageOf(error: unknown): string {
72
+ return error instanceof Error ? error.message : String(error)
73
+ }
74
+
75
+ /**
76
+ * Read and parse one fetched message. The body stream is piped into `simpleParser` as soon as it arrives (an unread
77
+ * stream would block the parser), so the result is a promise of either the parsed message, a parse error or neither
78
+ * when the server sent no body.
79
+ */
80
+ function readMessage(message: NodeIMAP.ImapMessage): Promise<ReadResult> {
81
+ let uid: number | undefined
82
+ let size = 0
83
+ let parsing: Promise<ParsedMail> | undefined
84
+ return new Promise<ReadResult>((resolve) => {
85
+ message.on('body', (stream, info) => {
86
+ size = info.size
87
+ // node-imap hands over a `stream.Readable`, which its declaration file types as `NodeJS.ReadableStream`.
88
+ parsing = simpleParser(stream as Readable)
89
+ // Observed right away: the explicit await below may come later, and an unhandled rejection would end the process.
90
+ parsing.catch(() => undefined)
91
+ })
92
+ message.on('attributes', (attributes) => {
93
+ uid = attributes.uid
94
+ })
95
+ message.on('end', () => {
96
+ const pending = parsing
97
+ if (pending === undefined) {
98
+ resolve({ uid, size })
99
+ return
100
+ }
101
+ pending.then(
102
+ (mail) => {
103
+ resolve({ uid, size, mail })
104
+ },
105
+ (error: unknown) => {
106
+ resolve({ uid, size, error })
107
+ },
108
+ )
109
+ })
110
+ })
111
+ }
112
+
113
+ /**
114
+ * The inbound connection of one account.
115
+ *
116
+ * `start()` resolves once the first attempt reached a stable state: the mailbox is open and the first scan runs in
117
+ * the background, or the failure was transient and the reconnect timer took over. A permanent failure (credentials,
118
+ * mailbox) rejects instead, so a misconfiguration is visible at startup.
119
+ */
120
+ export class ImapTransport {
121
+ private imap: NodeIMAP | undefined
122
+ private first:
123
+ { resolve: () => void; reject: (error: unknown) => void } | undefined
124
+ private failures = 0
125
+ private connected = false
126
+ private stopping = false
127
+ private permanent: unknown
128
+ private reconnectTimer: ReturnType<typeof setTimeout> | undefined
129
+ private scanning = false
130
+ private rescan = false
131
+ private scanPromise: Promise<void> | undefined
132
+ private mailListenerAttached = false
133
+
134
+ constructor(private readonly options: ImapTransportOptions) {}
135
+
136
+ /** Create the connection (once) and wait for the first attempt's stable outcome. */
137
+ async start(): Promise<void> {
138
+ const { config } = this.options
139
+ const imap = new NodeIMAP({
140
+ user: config.username,
141
+ password: config.password,
142
+ host: config.imap.host,
143
+ port: config.imap.port,
144
+ tls: config.imap.tls,
145
+ })
146
+ this.imap = imap
147
+ imap.on('error', (error) => {
148
+ this.handleError(error)
149
+ })
150
+ imap.on('ready', () => {
151
+ this.handleReady()
152
+ })
153
+ imap.on('close', () => {
154
+ this.handleClose()
155
+ })
156
+ const first = new Promise<void>((resolve, reject) => {
157
+ this.first = { resolve, reject }
158
+ })
159
+ imap.connect()
160
+ return first
161
+ }
162
+
163
+ /** Abort the reconnect timer, log out and wait for an in-flight scan. */
164
+ async stop(): Promise<void> {
165
+ this.stopping = true
166
+ this.clearReconnect()
167
+ const imap = this.imap
168
+ this.imap = undefined
169
+ if (imap !== undefined) imap.end()
170
+ await this.scanPromise?.catch(() => undefined)
171
+ }
172
+
173
+ /**
174
+ * Re-fetch one message by UID for the attachment route (`undefined` when the UID no longer exists).
175
+ * @param uid - the IMAP UID to fetch.
176
+ * @returns the parsed message.
177
+ */
178
+ async fetch(uid: number): Promise<ParsedMail | undefined> {
179
+ const imap = this.imap
180
+ if (imap === undefined)
181
+ throw new Error('mail: the IMAP connection is not open')
182
+ const fetched = imap.fetch(uid, { bodies: '' })
183
+ const results: ReadResult[] = []
184
+ const tasks: Promise<void>[] = []
185
+ await new Promise<void>((resolve, reject) => {
186
+ fetched.on('message', (message) => {
187
+ tasks.push(
188
+ readMessage(message).then((result) => {
189
+ results.push(result)
190
+ }),
191
+ )
192
+ })
193
+ fetched.on('end', () => {
194
+ resolve()
195
+ })
196
+ fetched.on('error', reject)
197
+ })
198
+ await Promise.all(tasks)
199
+ const [result] = results
200
+ if (result === undefined) return undefined
201
+ if (result.error !== undefined) throw result.error
202
+ return result.mail
203
+ }
204
+
205
+ private handleReady(): void {
206
+ if (this.stopping) return
207
+ const imap = this.imap
208
+ if (imap === undefined) return
209
+ imap.openBox(this.options.config.mailbox, false, (error) => {
210
+ if (this.stopping) return
211
+ if (error) {
212
+ this.options.logger.error(
213
+ 'mail: the mailbox %s could not be opened: %s',
214
+ this.options.config.mailbox,
215
+ messageOf(error),
216
+ )
217
+ this.failPermanently(error)
218
+ return
219
+ }
220
+ this.failures = 0
221
+ this.connected = true
222
+ this.options.onOnline()
223
+ this.first?.resolve()
224
+ this.first = undefined
225
+ this.attachMailListener()
226
+ void this.scan()
227
+ })
228
+ }
229
+
230
+ private handleError(error: ImapError): void {
231
+ if (this.stopping) return
232
+ if (error.source === 'authentication') {
233
+ this.options.logger.error(
234
+ 'mail: IMAP authentication failed: %s',
235
+ messageOf(error),
236
+ )
237
+ this.failPermanently(error)
238
+ return
239
+ }
240
+ this.options.logger.warn(
241
+ 'mail: IMAP error (%s): %s',
242
+ error.source ?? 'unknown',
243
+ messageOf(error),
244
+ )
245
+ // A transient first failure lets startup continue with the reconnect timer instead of failing the whole profile.
246
+ this.first?.resolve()
247
+ this.first = undefined
248
+ }
249
+
250
+ private handleClose(): void {
251
+ if (this.stopping) return
252
+ this.connected = false
253
+ if (this.permanent !== undefined) return
254
+ // A close during the first attempt is transient too: the reconnect loop takes over.
255
+ this.first?.resolve()
256
+ this.first = undefined
257
+ this.options.onReconnect()
258
+ this.scheduleReconnect()
259
+ }
260
+
261
+ private failPermanently(error: unknown): void {
262
+ this.permanent = error
263
+ this.connected = false
264
+ this.clearReconnect()
265
+ this.first?.reject(error)
266
+ this.first = undefined
267
+ this.options.onOffline(error)
268
+ }
269
+
270
+ private scheduleReconnect(): void {
271
+ if (
272
+ this.stopping ||
273
+ this.permanent !== undefined ||
274
+ this.reconnectTimer !== undefined ||
275
+ this.connected
276
+ )
277
+ return
278
+ const delay = reconnectDelay(this.failures, this.options.config.retry)
279
+ this.failures += 1
280
+ this.reconnectTimer = setTimeout(() => {
281
+ this.reconnectTimer = undefined
282
+ if (this.stopping || this.permanent !== undefined) return
283
+ this.imap?.connect()
284
+ }, delay)
285
+ }
286
+
287
+ private clearReconnect(): void {
288
+ if (this.reconnectTimer === undefined) return
289
+ clearTimeout(this.reconnectTimer)
290
+ this.reconnectTimer = undefined
291
+ }
292
+
293
+ /** Register the new-mail listener once: every reconnect reuses the connection and its listeners. */
294
+ private attachMailListener(): void {
295
+ const imap = this.imap
296
+ if (this.mailListenerAttached || imap === undefined) return
297
+ this.mailListenerAttached = true
298
+ imap.on('mail', () => {
299
+ void this.scan()
300
+ })
301
+ }
302
+
303
+ /** Run one scan; a request during a scan sets one "run again" flag instead of starting a second scan. */
304
+ private scan(): Promise<void> {
305
+ if (this.scanning) {
306
+ this.rescan = true
307
+ return Promise.resolve()
308
+ }
309
+ this.scanning = true
310
+ const run = (async () => {
311
+ try {
312
+ do {
313
+ this.rescan = false
314
+ await this.scanOnce()
315
+ } while (this.rescan && !this.stopping && this.connected)
316
+ } catch (error) {
317
+ // A failed scan never ends the connection loop: the next mail event or reconnect scans again.
318
+ this.options.logger.error('mail: the scan failed: %s', messageOf(error))
319
+ } finally {
320
+ this.scanning = false
321
+ }
322
+ })()
323
+ this.scanPromise = run
324
+ return run
325
+ }
326
+
327
+ private async scanOnce(): Promise<void> {
328
+ const imap = this.imap
329
+ if (imap === undefined) return
330
+ const uids = await new Promise<number[]>((resolve, reject) => {
331
+ imap.search(['UNSEEN'], (error, result) => {
332
+ if (error) reject(error)
333
+ else resolve(result ?? [])
334
+ })
335
+ })
336
+ if (uids.length === 0) return
337
+ const fetched = imap.fetch(uids, { bodies: '' })
338
+ const tasks: Promise<void>[] = []
339
+ await new Promise<void>((resolve) => {
340
+ let settled = false
341
+ const done = () => {
342
+ if (settled) return
343
+ settled = true
344
+ resolve()
345
+ }
346
+ fetched.on('message', (message) => {
347
+ tasks.push(this.deliverMessage(message))
348
+ })
349
+ fetched.on('end', done)
350
+ fetched.on('error', (error) => {
351
+ this.options.logger.error(
352
+ 'mail: fetching the message bodies failed: %s',
353
+ messageOf(error),
354
+ )
355
+ done()
356
+ })
357
+ })
358
+ await Promise.all(tasks)
359
+ }
360
+
361
+ /** Parse one fetched message, hand it to the host and acknowledge it only when the host accepted it. */
362
+ private async deliverMessage(message: NodeIMAP.ImapMessage): Promise<void> {
363
+ const result = await readMessage(message)
364
+ if (result.mail === undefined) {
365
+ // A malformed message can never be parsed: marking it seen is the only way out of the retry loop.
366
+ if (result.error !== undefined) {
367
+ this.options.logger.error(
368
+ 'mail: the message could not be parsed: %s',
369
+ messageOf(result.error),
370
+ )
371
+ } else {
372
+ this.options.logger.error('mail: a fetched message carried no body')
373
+ }
374
+ if (result.uid !== undefined) await this.markSeen(result.uid)
375
+ return
376
+ }
377
+ if (result.uid === undefined) {
378
+ // Without the UID there is nothing to acknowledge; the host still receives the message.
379
+ this.options.logger.error('mail: a fetched message carried no UID')
380
+ return
381
+ }
382
+ try {
383
+ await this.options.deliver(result.mail, {
384
+ uid: result.uid,
385
+ mailbox: this.options.config.mailbox,
386
+ size: result.size,
387
+ })
388
+ } catch (error) {
389
+ // Not accepted: leave it unseen so the next scan retries it.
390
+ this.options.logger.error(
391
+ 'mail: the host did not accept a message, it stays unseen: %s',
392
+ messageOf(error),
393
+ )
394
+ return
395
+ }
396
+ await this.markSeen(result.uid)
397
+ }
398
+
399
+ /** Write `\\Seen`; a failure only warns, because the host deduplicates the redelivery by `Message-ID`. */
400
+ private async markSeen(uid: number): Promise<void> {
401
+ const imap = this.imap
402
+ if (imap === undefined) return
403
+ try {
404
+ await new Promise<void>((resolve, reject) => {
405
+ imap.setFlags(uid, ['\\SEEN'], (error) => {
406
+ if (error) reject(error)
407
+ else resolve()
408
+ })
409
+ })
410
+ } catch (error) {
411
+ this.options.logger.warn(
412
+ 'mail: the message %d could not be marked as seen: %s',
413
+ uid,
414
+ messageOf(error),
415
+ )
416
+ }
417
+ }
418
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.