@prunellejs/mail 0.1.1 → 0.7.3

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.
package/src/smtp.ts ADDED
@@ -0,0 +1,534 @@
1
+ // Zero-dependency SMTP / SMTPS / STARTTLS transport built directly on `Bun.connect` sockets.
2
+ // Implements RFC 5321 multi-line response parsing, EHLO, STARTTLS, AUTH PLAIN / LOGIN, MAIL FROM, RCPT TO, DATA dot-stuffing, MIME multipart/alternative, and QUIT.
3
+
4
+ import type { Socket, SocketHandler, TLSOptions } from 'bun'
5
+ import type { MailTransport, SentMail } from './types'
6
+ import { isLoopbackHost } from 'prunelle/internal/server'
7
+ import { buildMimeMessage, dotStuffSmtpData, validateEhloHost } from './mime'
8
+ import { extractEmailAddress } from './types'
9
+
10
+ export { buildMimeMessage, dotStuffSmtpData } from './mime'
11
+
12
+ export interface SmtpOptions {
13
+ host: string
14
+ port?: number | undefined
15
+ /** Implicit TLS (`smtps://`, typically port 465). Defaults to `true` when `port === 465`, else `false`. */
16
+ secure?: boolean | undefined
17
+ /** Require the STARTTLS upgrade on a plaintext connection, failing when the server does not offer it. Defaults to `true`, except on a loopback host or with `allowInsecureAuth`; `false` sends in plaintext when STARTTLS is missing. */
18
+ requireTls?: boolean | undefined
19
+ /** Disable automatic STARTTLS even when the server advertises it. */
20
+ disableStartTls?: boolean | undefined
21
+ /** Allow sending SMTP AUTH credentials over an unencrypted non-loopback connection (default `false`). */
22
+ allowInsecureAuth?: boolean | undefined
23
+ /** Verify the server TLS certificate (default `true`). */
24
+ rejectUnauthorized?: boolean | undefined
25
+ user?: string | undefined
26
+ pass?: string | undefined
27
+ /** Hostname announced in `EHLO` (default `'localhost'`). */
28
+ ehloHost?: string | undefined
29
+ /** Socket read/connect timeout in milliseconds (default `15_000`). */
30
+ timeoutMs?: number | undefined
31
+ /** Longest one `send()` may take in all, connection to `QUIT`, in milliseconds (default `60_000`). */
32
+ deadlineMs?: number | undefined
33
+ /** Connections open at once; further sends wait for one to close (default `4`). */
34
+ maxConnections?: number | undefined
35
+ }
36
+
37
+ interface SmtpResponse {
38
+ code: number
39
+ lines: string[]
40
+ }
41
+
42
+ const DEFAULT_SMTP_TIMEOUT_MS = 15_000
43
+ const DEFAULT_SMTP_DEADLINE_MS = 60_000
44
+ const DEFAULT_SMTP_CONNECTIONS = 4
45
+ // A server's reply is a few lines: 64 KiB, or 100 replies nobody asked for, is a server that is not speaking SMTP.
46
+ const MAX_REPLY_BYTES = 64 * 1024
47
+ const MAX_QUEUED_REPLIES = 100
48
+ const SMTP_LINE_RE = /^(\d{3})([ -])(.*)$/
49
+
50
+ interface PendingRead {
51
+ resolve: (res: SmtpResponse) => void
52
+ reject: (err: Error) => void
53
+ timer: ReturnType<typeof setTimeout>
54
+ }
55
+
56
+ interface PendingDrain {
57
+ resolve: () => void
58
+ reject: (err: Error) => void
59
+ timer: ReturnType<typeof setTimeout>
60
+ }
61
+
62
+ interface QueuedResponse {
63
+ res: SmtpResponse
64
+ bytes: number
65
+ }
66
+
67
+ const EMPTY_BYTES = new Uint8Array(0)
68
+
69
+ class SmtpConnection {
70
+ private socket: Socket<undefined> | undefined
71
+ private rawBuffer: Uint8Array = EMPTY_BYTES
72
+ private multiCode: number | undefined
73
+ private multiLines: string[] = []
74
+ private readonly responses: QueuedResponse[] = []
75
+ private unexpectedLines = 0
76
+ private replyBytes = 0
77
+ private currentReplyBytes = 0
78
+ private generation = 0
79
+ private pendingConnect: { reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> } | undefined
80
+ private pendingRead: PendingRead | undefined
81
+ private pendingDrain: PendingDrain | undefined
82
+ private pendingHandshake: { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> } | undefined
83
+ private fatalError: Error | undefined
84
+ private closed = false
85
+ private decoder = new TextDecoder()
86
+
87
+ constructor(private readonly timeoutMs: number) {}
88
+
89
+ private resetParser(): void {
90
+ this.rawBuffer = EMPTY_BYTES
91
+ this.multiCode = undefined
92
+ this.multiLines = []
93
+ this.responses.length = 0
94
+ this.unexpectedLines = 0
95
+ this.replyBytes = 0
96
+ this.currentReplyBytes = 0
97
+ this.decoder = new TextDecoder()
98
+ }
99
+
100
+ private makeHandler(gen: number): SocketHandler<undefined> {
101
+ return {
102
+ data: (_socket, chunk) => {
103
+ if (gen !== this.generation)
104
+ return
105
+ this.onChunk(chunk)
106
+ },
107
+ drain: () => {
108
+ if (gen !== this.generation)
109
+ return
110
+ const d = this.pendingDrain
111
+ if (d !== undefined) {
112
+ this.pendingDrain = undefined
113
+ clearTimeout(d.timer)
114
+ d.resolve()
115
+ }
116
+ },
117
+ handshake: (_socket, success, authorizationError) => {
118
+ if (gen !== this.generation)
119
+ return
120
+ const h = this.pendingHandshake
121
+ if (h === undefined)
122
+ return
123
+ this.pendingHandshake = undefined
124
+ clearTimeout(h.timer)
125
+ if (success)
126
+ h.resolve()
127
+ else
128
+ h.reject(authorizationError ?? new Error('@prunellejs/mail (smtp): TLS handshake failed'))
129
+ },
130
+ error: (_socket, error) => {
131
+ if (gen !== this.generation)
132
+ return
133
+ this.fail(error instanceof Error ? error : new Error(String(error)))
134
+ },
135
+ connectError: (_socket, error) => {
136
+ if (gen !== this.generation)
137
+ return
138
+ this.fail(error instanceof Error ? error : new Error(String(error)))
139
+ },
140
+ close: () => {
141
+ if (gen !== this.generation)
142
+ return
143
+ this.closed = true
144
+ this.fail(new Error('@prunellejs/mail (smtp): connection closed unexpectedly'))
145
+ },
146
+ }
147
+ }
148
+
149
+ private dropLimit(message: string): void {
150
+ this.responses.length = 0
151
+ this.replyBytes = 0
152
+ this.currentReplyBytes = 0
153
+ this.fail(new Error(message))
154
+ this.close()
155
+ }
156
+
157
+ private onChunk(chunk: Uint8Array): void {
158
+ this.replyBytes += chunk.byteLength
159
+ if (this.replyBytes > MAX_REPLY_BYTES) {
160
+ this.dropLimit(`@prunellejs/mail (smtp): the server's reply passed ${MAX_REPLY_BYTES} bytes, so the connection was dropped`)
161
+ return
162
+ }
163
+ const data = this.rawBuffer.length === 0 ? chunk : Buffer.concat([this.rawBuffer, chunk])
164
+ let offset = 0
165
+ while (!this.closed) {
166
+ const nl = data.indexOf(0x0a, offset)
167
+ if (nl === -1)
168
+ break
169
+ const lineBytes = nl + 1 - offset
170
+ const end = nl > offset && data[nl - 1] === 0x0d ? nl - 1 : nl
171
+ const line = this.decoder.decode(data.subarray(offset, end))
172
+ offset = nl + 1
173
+ this.parseLine(line, lineBytes)
174
+ }
175
+ this.rawBuffer = this.closed || offset >= data.length ? EMPTY_BYTES : Uint8Array.from(data.subarray(offset))
176
+ }
177
+
178
+ private parseLine(line: string, lineBytes: number): void {
179
+ const match = SMTP_LINE_RE.exec(line)
180
+ if (match === null) {
181
+ if (this.multiCode !== undefined) {
182
+ this.currentReplyBytes += lineBytes
183
+ this.multiLines.push(line)
184
+ }
185
+ else {
186
+ this.unexpectedLines++
187
+ }
188
+ return
189
+ }
190
+ const code = Number(match[1])
191
+ const sep = match[2]
192
+ const msg = match[3] ?? ''
193
+ this.currentReplyBytes += lineBytes
194
+ if (sep === '-') {
195
+ this.multiCode = code
196
+ this.multiLines.push(msg)
197
+ return
198
+ }
199
+ const lines = this.multiCode === code ? [...this.multiLines, msg] : [msg]
200
+ const bytes = this.currentReplyBytes
201
+ this.multiCode = undefined
202
+ this.multiLines = []
203
+ this.currentReplyBytes = 0
204
+ this.deliverResponse({ code, lines }, bytes)
205
+ }
206
+
207
+ private deliverResponse(res: SmtpResponse, bytes: number): void {
208
+ const waiter = this.pendingRead
209
+ if (waiter !== undefined) {
210
+ this.replyBytes = Math.max(0, this.replyBytes - bytes)
211
+ this.pendingRead = undefined
212
+ clearTimeout(waiter.timer)
213
+ waiter.resolve(res)
214
+ return
215
+ }
216
+ if (this.responses.length >= MAX_QUEUED_REPLIES) {
217
+ this.dropLimit(`@prunellejs/mail (smtp): the server queued more than ${MAX_QUEUED_REPLIES} replies, so the connection was dropped`)
218
+ return
219
+ }
220
+ this.responses.push({ res, bytes })
221
+ }
222
+
223
+ private fail(err: Error): void {
224
+ if (this.fatalError === undefined)
225
+ this.fatalError = err
226
+ for (const waiter of [this.pendingConnect, this.pendingRead, this.pendingDrain, this.pendingHandshake]) {
227
+ if (waiter !== undefined) {
228
+ clearTimeout(waiter.timer)
229
+ waiter.reject(err)
230
+ }
231
+ }
232
+ this.pendingConnect = undefined
233
+ this.pendingRead = undefined
234
+ this.pendingDrain = undefined
235
+ this.pendingHandshake = undefined
236
+ }
237
+
238
+ async connect(host: string, port: number, tls: TLSOptions | false): Promise<void> {
239
+ if (this.closed || this.fatalError !== undefined)
240
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): connection closed')
241
+ let aborted = false
242
+ const gen = this.generation
243
+ const connectPromise = Bun.connect<undefined>({
244
+ hostname: host,
245
+ port,
246
+ tls: tls === false ? false : tls,
247
+ socket: this.makeHandler(gen),
248
+ })
249
+ const waiterPromise = new Promise<never>((_, reject) => {
250
+ const timer = setTimeout(() => {
251
+ aborted = true
252
+ this.pendingConnect = undefined
253
+ reject(new Error(`@prunellejs/mail (smtp): connect timed out after ${this.timeoutMs}ms`))
254
+ }, this.timeoutMs)
255
+ this.pendingConnect = {
256
+ reject: (err) => {
257
+ aborted = true
258
+ reject(err)
259
+ },
260
+ timer,
261
+ }
262
+ })
263
+ try {
264
+ const sock = await Promise.race([connectPromise, waiterPromise])
265
+ if (this.closed) {
266
+ sock.end()
267
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): connection closed')
268
+ }
269
+ this.socket = sock
270
+ }
271
+ catch (err) {
272
+ if (aborted) {
273
+ this.generation++
274
+ // Close a late-resolving socket and swallow late rejections so none become unhandled.
275
+ void connectPromise.then(
276
+ (sock) => {
277
+ sock.end()
278
+ },
279
+ () => undefined,
280
+ )
281
+ }
282
+ throw err
283
+ }
284
+ finally {
285
+ if (this.pendingConnect !== undefined) {
286
+ clearTimeout(this.pendingConnect.timer)
287
+ this.pendingConnect = undefined
288
+ }
289
+ }
290
+ }
291
+
292
+ async upgradeTls(tls: TLSOptions): Promise<void> {
293
+ if (this.socket === undefined)
294
+ throw new Error('@prunellejs/mail (smtp): socket is not connected')
295
+ const hasBufferedPlaintext = this.rawBuffer.length > 0
296
+ || this.responses.length > 0
297
+ || this.multiCode !== undefined
298
+ || this.multiLines.length > 0
299
+ || this.unexpectedLines > 0
300
+ this.resetParser()
301
+ if (hasBufferedPlaintext)
302
+ throw new Error('@prunellejs/mail (smtp): unexpected plaintext data received after STARTTLS (RFC 3207)')
303
+
304
+ const nextGen = ++this.generation
305
+ const handshakePromise = new Promise<void>((resolve, reject) => {
306
+ const timer = setTimeout(() => {
307
+ this.pendingHandshake = undefined
308
+ reject(new Error(`@prunellejs/mail (smtp): TLS handshake timed out after ${this.timeoutMs}ms`))
309
+ }, this.timeoutMs)
310
+ this.pendingHandshake = { resolve, reject, timer }
311
+ })
312
+ const [, tlsSocket] = this.socket.upgradeTLS({ tls, socket: this.makeHandler(nextGen) })
313
+ this.socket = tlsSocket
314
+ await handshakePromise
315
+ }
316
+
317
+ readResponse(): Promise<SmtpResponse> {
318
+ if (this.responses.length > 0) {
319
+ const next = this.responses.shift()!
320
+ this.replyBytes = Math.max(0, this.replyBytes - next.bytes)
321
+ return Promise.resolve(next.res)
322
+ }
323
+ if (this.fatalError !== undefined)
324
+ return Promise.reject(this.fatalError)
325
+ return new Promise<SmtpResponse>((resolve, reject) => {
326
+ const timer = setTimeout(() => {
327
+ this.pendingRead = undefined
328
+ reject(new Error(`@prunellejs/mail (smtp): response timed out after ${this.timeoutMs}ms`))
329
+ }, this.timeoutMs)
330
+ this.pendingRead = { resolve, reject, timer }
331
+ })
332
+ }
333
+
334
+ async writeAll(data: string): Promise<void> {
335
+ const socket = this.socket
336
+ if (socket === undefined || this.closed)
337
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): socket is closed')
338
+ this.unexpectedLines = 0
339
+ let bytes = Buffer.from(data, 'utf8')
340
+ while (bytes.length > 0) {
341
+ const written = socket.write(bytes)
342
+ if (written < 0)
343
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): socket write failed')
344
+ if (written >= bytes.length)
345
+ return
346
+ bytes = bytes.subarray(written)
347
+ await new Promise<void>((resolve, reject) => {
348
+ const timer = setTimeout(() => {
349
+ this.pendingDrain = undefined
350
+ reject(new Error(`@prunellejs/mail (smtp): write timed out after ${this.timeoutMs}ms`))
351
+ }, this.timeoutMs)
352
+ this.pendingDrain = { resolve, reject, timer }
353
+ })
354
+ }
355
+ }
356
+
357
+ async command(line: string, expectedCodes: readonly number[]): Promise<SmtpResponse> {
358
+ await this.writeAll(`${line}\r\n`)
359
+ const res = await this.readResponse()
360
+ if (!expectedCodes.includes(res.code))
361
+ throw new Error(`@prunellejs/mail (smtp): unexpected response ${res.code} ${res.lines.join(' ')}`)
362
+ return res
363
+ }
364
+
365
+ /** Ends the send: whatever waits on this connection fails with `err`. */
366
+ abort(err: Error): void {
367
+ this.responses.length = 0
368
+ this.fail(err)
369
+ this.close()
370
+ }
371
+
372
+ close(): void {
373
+ this.closed = true
374
+ this.generation++
375
+ for (const waiter of [this.pendingConnect, this.pendingRead, this.pendingDrain, this.pendingHandshake]) {
376
+ if (waiter !== undefined)
377
+ clearTimeout(waiter.timer)
378
+ }
379
+ this.pendingConnect = undefined
380
+ this.pendingRead = undefined
381
+ this.pendingDrain = undefined
382
+ this.pendingHandshake = undefined
383
+ if (this.socket !== undefined) {
384
+ this.socket.end()
385
+ this.socket = undefined
386
+ }
387
+ }
388
+ }
389
+
390
+ function parseCapabilities(lines: readonly string[]): { starttls: boolean, authMethods: Set<string> } {
391
+ let starttls = false
392
+ const authMethods = new Set<string>()
393
+ for (let i = 1; i < lines.length; i++) {
394
+ const upper = lines[i]!.trim().toUpperCase()
395
+ if (upper === 'STARTTLS')
396
+ starttls = true
397
+ if (upper.startsWith('AUTH ') || upper.startsWith('AUTH=')) {
398
+ const tokens = upper.slice(5).split(/\s+/)
399
+ for (const token of tokens) {
400
+ if (token.length > 0)
401
+ authMethods.add(token)
402
+ }
403
+ }
404
+ }
405
+ return { starttls, authMethods }
406
+ }
407
+
408
+ async function negotiateEhlo(conn: SmtpConnection, ehloHost: string): Promise<{ starttls: boolean, authMethods: Set<string> }> {
409
+ await conn.writeAll(`EHLO ${ehloHost}\r\n`)
410
+ const res = await conn.readResponse()
411
+ if (res.code === 250)
412
+ return parseCapabilities(res.lines)
413
+ if (res.code === 500 || res.code === 502) {
414
+ await conn.command(`HELO ${ehloHost}`, [250])
415
+ return { starttls: false, authMethods: new Set() }
416
+ }
417
+ throw new Error(`@prunellejs/mail (smtp): EHLO failed with ${res.code} ${res.lines.join(' ')}`)
418
+ }
419
+
420
+ async function authenticateSmtp(
421
+ conn: SmtpConnection,
422
+ authMethods: ReadonlySet<string>,
423
+ user: string,
424
+ pass: string,
425
+ ): Promise<void> {
426
+ if (authMethods.has('LOGIN') && !authMethods.has('PLAIN')) {
427
+ await conn.command('AUTH LOGIN', [334])
428
+ await conn.command(Buffer.from(user, 'utf8').toString('base64'), [334])
429
+ await conn.command(Buffer.from(pass, 'utf8').toString('base64'), [235])
430
+ return
431
+ }
432
+ const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64')
433
+ await conn.command(`AUTH PLAIN ${token}`, [235])
434
+ }
435
+
436
+ /** At most `max` holders at once; the next waits for `release()`, which hands its place on. */
437
+ function createConnectionLimit(max: number): { acquire: () => Promise<void>, release: () => void } {
438
+ let active = 0
439
+ const waiting: Array<() => void> = []
440
+ return {
441
+ async acquire() {
442
+ if (active < max) {
443
+ active++
444
+ return
445
+ }
446
+ await new Promise<void>(resolve => waiting.push(resolve))
447
+ },
448
+ release() {
449
+ const next = waiting.shift()
450
+ if (next !== undefined)
451
+ next()
452
+ else
453
+ active--
454
+ },
455
+ }
456
+ }
457
+
458
+ /** Zero-dependency SMTP/SMTPS/STARTTLS transport backed directly by `Bun.connect`. */
459
+ export function smtp(options: SmtpOptions): MailTransport {
460
+ const host = options.host.trim()
461
+ if (host.length === 0)
462
+ throw new RangeError('@prunellejs/mail (smtp): `host` must be a non-empty hostname')
463
+ const secure = options.secure ?? options.port === 465
464
+ const port = options.port ?? (secure ? 465 : 587)
465
+ const ehloHost = validateEhloHost(options.ehloHost ?? 'localhost')
466
+ if (!secure && options.requireTls === true && options.disableStartTls === true)
467
+ throw new RangeError('@prunellejs/mail (smtp): cannot set both `requireTls` and `disableStartTls`')
468
+ const requireTls = options.requireTls ?? !(options.allowInsecureAuth === true || isLoopbackHost(host))
469
+ const timeoutMs = options.timeoutMs ?? DEFAULT_SMTP_TIMEOUT_MS
470
+ const deadlineMs = options.deadlineMs ?? DEFAULT_SMTP_DEADLINE_MS
471
+ const connections = createConnectionLimit(Math.max(1, options.maxConnections ?? DEFAULT_SMTP_CONNECTIONS))
472
+ const tlsConfig: TLSOptions = {
473
+ serverName: host,
474
+ rejectUnauthorized: options.rejectUnauthorized ?? true,
475
+ }
476
+
477
+ return {
478
+ async send(mail: SentMail): Promise<void> {
479
+ const envelopeFrom = extractEmailAddress(mail.from)
480
+ const envelopeTo = mail.to.map(extractEmailAddress)
481
+ const message = buildMimeMessage(mail, ehloHost)
482
+ await connections.acquire()
483
+ const conn = new SmtpConnection(timeoutMs)
484
+ const deadline = setTimeout(() => conn.abort(new Error(`@prunellejs/mail (smtp): the send passed its ${deadlineMs}ms deadline`)), deadlineMs)
485
+
486
+ try {
487
+ await conn.connect(host, port, secure ? tlsConfig : false)
488
+ const greeting = await conn.readResponse()
489
+ if (greeting.code !== 220)
490
+ throw new Error(`@prunellejs/mail (smtp): unexpected greeting ${greeting.code} ${greeting.lines.join(' ')}`)
491
+
492
+ let caps = await negotiateEhlo(conn, ehloHost)
493
+
494
+ let encrypted = secure
495
+ if (!secure && !options.disableStartTls) {
496
+ if (caps.starttls) {
497
+ await conn.command('STARTTLS', [220])
498
+ await conn.upgradeTls(tlsConfig)
499
+ encrypted = true
500
+ caps = await negotiateEhlo(conn, ehloHost)
501
+ }
502
+ else if (requireTls) {
503
+ throw new Error('@prunellejs/mail (smtp): server does not advertise STARTTLS, so the mail would leave unencrypted: enable STARTTLS on the server, or set `requireTls: false` (MAIL_URL `?tls=opportunistic`) to send it in plaintext')
504
+ }
505
+ }
506
+
507
+ if (options.user !== undefined || options.pass !== undefined) {
508
+ const allowPlaintextAuth = isLoopbackHost(host) || options.allowInsecureAuth === true || options.requireTls === false
509
+ if (!encrypted && !allowPlaintextAuth)
510
+ throw new Error('@prunellejs/mail (smtp): refusing to send AUTH credentials over an unencrypted connection; server did not upgrade via STARTTLS (set `allowInsecureAuth: true` or `requireTls: false` to override)')
511
+ await authenticateSmtp(conn, caps.authMethods, options.user ?? '', options.pass ?? '')
512
+ }
513
+
514
+ await conn.command(`MAIL FROM:<${envelopeFrom}>`, [250])
515
+ for (const recipient of envelopeTo)
516
+ await conn.command(`RCPT TO:<${recipient}>`, [250, 251])
517
+
518
+ await conn.command('DATA', [354])
519
+ await conn.writeAll(dotStuffSmtpData(message))
520
+ const dataRes = await conn.readResponse()
521
+ if (dataRes.code !== 250)
522
+ throw new Error(`@prunellejs/mail (smtp): DATA rejected with ${dataRes.code} ${dataRes.lines.join(' ')}`)
523
+
524
+ // The server has accepted the mail: a QUIT that stalls, fails or gets no 221 must not make the caller retry and send it twice.
525
+ await conn.writeAll('QUIT\r\n').then(() => conn.readResponse()).catch(() => undefined)
526
+ }
527
+ finally {
528
+ clearTimeout(deadline)
529
+ conn.close()
530
+ connections.release()
531
+ }
532
+ },
533
+ }
534
+ }