@prunellejs/mail 0.0.0-stage → 0.7.2

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,645 @@
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 { assertNoHeaderInjection, extractEmailAddress } from './types'
8
+
9
+ export interface SmtpOptions {
10
+ host: string
11
+ port?: number | undefined
12
+ /** Implicit TLS (`smtps://`, typically port 465). Defaults to `true` when `port === 465`, else `false`. */
13
+ secure?: boolean | undefined
14
+ /** 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. */
15
+ requireTls?: boolean | undefined
16
+ /** Disable automatic STARTTLS even when the server advertises it. */
17
+ disableStartTls?: boolean | undefined
18
+ /** Allow sending SMTP AUTH credentials over an unencrypted non-loopback connection (default `false`). */
19
+ allowInsecureAuth?: boolean | undefined
20
+ /** Verify the server TLS certificate (default `true`). */
21
+ rejectUnauthorized?: boolean | undefined
22
+ user?: string | undefined
23
+ pass?: string | undefined
24
+ /** Hostname announced in `EHLO` (default `'localhost'`). */
25
+ ehloHost?: string | undefined
26
+ /** Socket read/connect timeout in milliseconds (default `15_000`). */
27
+ timeoutMs?: number | undefined
28
+ /** Longest one `send()` may take in all, connection to `QUIT`, in milliseconds (default `60_000`). */
29
+ deadlineMs?: number | undefined
30
+ /** Connections open at once; further sends wait for one to close (default `4`). */
31
+ maxConnections?: number | undefined
32
+ }
33
+
34
+ interface SmtpResponse {
35
+ code: number
36
+ lines: string[]
37
+ }
38
+
39
+ const DEFAULT_SMTP_TIMEOUT_MS = 15_000
40
+ const DEFAULT_SMTP_DEADLINE_MS = 60_000
41
+ const DEFAULT_SMTP_CONNECTIONS = 4
42
+ // A server's reply is a few lines: 64 KiB, or 100 replies nobody asked for, is a server that is not speaking SMTP.
43
+ const MAX_REPLY_BYTES = 64 * 1024
44
+ const MAX_QUEUED_REPLIES = 100
45
+ const SMTP_LINE_RE = /^(\d{3})([ -])(.*)$/
46
+ const NON_ASCII_RE = /[^\x20-\x7E]/
47
+ const WHITESPACE_OR_ANGLE_RE = /[\s<>]/
48
+
49
+ function validateEhloHost(value: string): string {
50
+ assertNoHeaderInjection(value, 'ehloHost')
51
+ if (value.length === 0 || WHITESPACE_OR_ANGLE_RE.test(value))
52
+ throw new RangeError('@prunellejs/mail (smtp): `ehloHost` must be a non-empty hostname without whitespace or angle brackets')
53
+ return value
54
+ }
55
+
56
+ // An encoded word is at most 75 characters: 45 bytes of text make 60 base64 characters plus the 12 of `=?UTF-8?B?` and `?=`.
57
+ const ENCODED_WORD_MAX_BYTES = 45
58
+ const HEADER_LINE_MAX = 78
59
+ const QP_LINE_MAX = 76
60
+ const ANGLE_ADDRESS_RE = /^\s*(.*?)\s*(<[^<>]+>)\s*$/
61
+ const QUOTED_NAME_RE = /^"(.*)"$/
62
+
63
+ /** Splits non-ASCII text into space-separated RFC 2047 encoded words, never cutting a UTF-8 sequence. */
64
+ function encodeRfc2047(value: string): string {
65
+ if (!NON_ASCII_RE.test(value))
66
+ return value
67
+ const words: string[] = []
68
+ let chunk = ''
69
+ let chunkBytes = 0
70
+ for (const char of value) {
71
+ const bytes = Buffer.byteLength(char, 'utf8')
72
+ if (chunkBytes + bytes > ENCODED_WORD_MAX_BYTES) {
73
+ words.push(chunk)
74
+ chunk = ''
75
+ chunkBytes = 0
76
+ }
77
+ chunk += char
78
+ chunkBytes += bytes
79
+ }
80
+ words.push(chunk)
81
+ return words.map(word => `=?UTF-8?B?${Buffer.from(word, 'utf8').toString('base64')}?=`).join(' ')
82
+ }
83
+
84
+ /** Encodes the display name of `Name <addr>` when it is not ASCII; anything else is returned as it is. */
85
+ function encodeAddressHeader(address: string): string {
86
+ const match = ANGLE_ADDRESS_RE.exec(address)
87
+ if (match === null || !NON_ASCII_RE.test(match[1]!))
88
+ return address
89
+ const name = match[1]!.replace(QUOTED_NAME_RE, '$1').replace(/\\(.)/g, '$1')
90
+ return `${encodeRfc2047(name)} ${match[2]!}`
91
+ }
92
+
93
+ /** Folds a header at whitespace so no line passes 78 characters (RFC 5322 §2.2.3); a token longer than that stays whole. */
94
+ function foldHeader(name: string, value: string): string {
95
+ const lines: string[] = []
96
+ let line = `${name}:`
97
+ for (const token of value.split(' ')) {
98
+ if (line.length + 1 + token.length > HEADER_LINE_MAX) {
99
+ lines.push(line)
100
+ line = ` ${token}`
101
+ }
102
+ else {
103
+ line += ` ${token}`
104
+ }
105
+ }
106
+ lines.push(line)
107
+ return lines.join('\r\n')
108
+ }
109
+
110
+ function quotedPrintableLine(line: string): string {
111
+ const bytes = Buffer.from(line, 'utf8')
112
+ const out: string[] = []
113
+ let current = ''
114
+ for (const [i, byte] of bytes.entries()) {
115
+ const isLast = i === bytes.length - 1
116
+ const literal = (byte >= 33 && byte <= 126 && byte !== 61) || ((byte === 32 || byte === 9) && !isLast)
117
+ const token = literal ? String.fromCharCode(byte) : `=${byte.toString(16).toUpperCase().padStart(2, '0')}`
118
+ const fits = isLast ? current.length + token.length <= QP_LINE_MAX : current.length + token.length < QP_LINE_MAX
119
+ if (!fits) {
120
+ out.push(`${current}=`)
121
+ current = ''
122
+ }
123
+ current += token
124
+ }
125
+ out.push(current)
126
+ return out.join('\r\n')
127
+ }
128
+
129
+ /** RFC 2045 quoted-printable: 7-bit, lines of at most 76 characters with soft breaks, so the body needs neither 8BITMIME nor a line under 998. */
130
+ function encodeQuotedPrintable(text: string): string {
131
+ return normalizeCrlf(text).split('\r\n').map(quotedPrintableLine).join('\r\n')
132
+ }
133
+
134
+ function normalizeCrlf(text: string): string {
135
+ return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\n/g, '\r\n')
136
+ }
137
+
138
+ /** Applies RFC 5321 §4.5.2 dot-stuffing and appends the terminating `\r\n.\r\n`. */
139
+ export function dotStuffSmtpData(rawMessage: string): string {
140
+ const normalized = normalizeCrlf(rawMessage)
141
+ const stuffed = normalized.replace(/(^|\r\n)\./g, '$1..')
142
+ return stuffed.endsWith('\r\n') ? `${stuffed}.\r\n` : `${stuffed}\r\n.\r\n`
143
+ }
144
+
145
+ /** Builds an RFC 5322 + MIME message (using `multipart/alternative` when both `text` and `html` are present). */
146
+ export function buildMimeMessage(mail: SentMail, domain = 'localhost'): string {
147
+ const safeDomain = validateEhloHost(domain)
148
+ for (const [label, value] of [['from', mail.from], ['replyTo', mail.replyTo ?? ''], ['subject', mail.subject], ['id', mail.id], ...mail.to.map(to => ['to', to] as const)] as const)
149
+ assertNoHeaderInjection(value, label)
150
+ const headers = [
151
+ foldHeader('From', encodeAddressHeader(mail.from)),
152
+ foldHeader('To', mail.to.map(encodeAddressHeader).join(', ')),
153
+ ...(mail.replyTo !== undefined ? [foldHeader('Reply-To', encodeAddressHeader(mail.replyTo))] : []),
154
+ foldHeader('Subject', encodeRfc2047(mail.subject)),
155
+ `Date: ${new Date(mail.sentAt).toUTCString()}`,
156
+ `Message-ID: <${mail.id}@${safeDomain}>`,
157
+ 'MIME-Version: 1.0',
158
+ ]
159
+
160
+ const hasText = mail.text !== undefined
161
+ const hasHtml = mail.html !== undefined
162
+
163
+ if (hasText && hasHtml) {
164
+ const boundary = `----=_PruMail_${mail.id.replace(/[^A-Za-z0-9]/g, '')}`
165
+ headers.push(`Content-Type: multipart/alternative; boundary="${boundary}"`)
166
+ return [
167
+ headers.join('\r\n'),
168
+ '',
169
+ `--${boundary}`,
170
+ 'Content-Type: text/plain; charset=utf-8',
171
+ 'Content-Transfer-Encoding: quoted-printable',
172
+ '',
173
+ encodeQuotedPrintable(mail.text!),
174
+ `--${boundary}`,
175
+ 'Content-Type: text/html; charset=utf-8',
176
+ 'Content-Transfer-Encoding: quoted-printable',
177
+ '',
178
+ encodeQuotedPrintable(mail.html!),
179
+ `--${boundary}--`,
180
+ '',
181
+ ].join('\r\n')
182
+ }
183
+
184
+ if (hasHtml) {
185
+ headers.push('Content-Type: text/html; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
186
+ return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.html!)}\r\n`
187
+ }
188
+
189
+ headers.push('Content-Type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
190
+ return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.text ?? '')}\r\n`
191
+ }
192
+
193
+ interface PendingRead {
194
+ resolve: (res: SmtpResponse) => void
195
+ reject: (err: Error) => void
196
+ timer: ReturnType<typeof setTimeout>
197
+ }
198
+
199
+ interface PendingDrain {
200
+ resolve: () => void
201
+ reject: (err: Error) => void
202
+ timer: ReturnType<typeof setTimeout>
203
+ }
204
+
205
+ class SmtpConnection {
206
+ private socket: Socket<undefined> | undefined
207
+ private buffer = ''
208
+ private multiCode: number | undefined
209
+ private multiLines: string[] = []
210
+ private readonly responses: SmtpResponse[] = []
211
+ private unexpectedLines = 0
212
+ private replyBytes = 0
213
+ private generation = 0
214
+ private pendingRead: PendingRead | undefined
215
+ private pendingDrain: PendingDrain | undefined
216
+ private pendingHandshake: { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> } | undefined
217
+ private fatalError: Error | undefined
218
+ private closed = false
219
+ private decoder = new TextDecoder()
220
+
221
+ constructor(private readonly timeoutMs: number) {}
222
+
223
+ private resetParser(): void {
224
+ this.buffer = ''
225
+ this.multiCode = undefined
226
+ this.multiLines = []
227
+ this.responses.length = 0
228
+ this.unexpectedLines = 0
229
+ this.replyBytes = 0
230
+ this.decoder = new TextDecoder()
231
+ }
232
+
233
+ private makeHandler(gen: number): SocketHandler<undefined> {
234
+ return {
235
+ data: (_socket, chunk) => {
236
+ if (gen !== this.generation)
237
+ return
238
+ this.onChunk(this.decoder.decode(chunk, { stream: true }))
239
+ },
240
+ drain: () => {
241
+ if (gen !== this.generation)
242
+ return
243
+ const d = this.pendingDrain
244
+ if (d !== undefined) {
245
+ this.pendingDrain = undefined
246
+ clearTimeout(d.timer)
247
+ d.resolve()
248
+ }
249
+ },
250
+ handshake: (_socket, success, authorizationError) => {
251
+ if (gen !== this.generation)
252
+ return
253
+ const h = this.pendingHandshake
254
+ if (h === undefined)
255
+ return
256
+ this.pendingHandshake = undefined
257
+ clearTimeout(h.timer)
258
+ if (success)
259
+ h.resolve()
260
+ else
261
+ h.reject(authorizationError ?? new Error('@prunellejs/mail (smtp): TLS handshake failed'))
262
+ },
263
+ error: (_socket, error) => {
264
+ if (gen !== this.generation)
265
+ return
266
+ this.fail(error instanceof Error ? error : new Error(String(error)))
267
+ },
268
+ connectError: (_socket, error) => {
269
+ if (gen !== this.generation)
270
+ return
271
+ this.fail(error instanceof Error ? error : new Error(String(error)))
272
+ },
273
+ close: () => {
274
+ if (gen !== this.generation)
275
+ return
276
+ this.closed = true
277
+ this.fail(new Error('@prunellejs/mail (smtp): connection closed unexpectedly'))
278
+ },
279
+ }
280
+ }
281
+
282
+ private onChunk(text: string): void {
283
+ this.replyBytes += text.length
284
+ if (this.replyBytes > MAX_REPLY_BYTES || this.responses.length > MAX_QUEUED_REPLIES) {
285
+ this.fail(new Error(`@prunellejs/mail (smtp): the server's reply passed ${MAX_REPLY_BYTES} bytes, so the connection was dropped`))
286
+ this.close()
287
+ return
288
+ }
289
+ this.buffer += text
290
+ for (;;) {
291
+ const nl = this.buffer.indexOf('\n')
292
+ if (nl === -1)
293
+ break
294
+ const line = this.buffer.slice(0, nl).replace(/\r$/, '')
295
+ this.buffer = this.buffer.slice(nl + 1)
296
+ this.parseLine(line)
297
+ }
298
+ }
299
+
300
+ private parseLine(line: string): void {
301
+ const match = SMTP_LINE_RE.exec(line)
302
+ if (match === null) {
303
+ if (this.multiCode !== undefined)
304
+ this.multiLines.push(line)
305
+ else
306
+ this.unexpectedLines++
307
+ return
308
+ }
309
+ const code = Number(match[1])
310
+ const sep = match[2]
311
+ const msg = match[3] ?? ''
312
+ if (sep === '-') {
313
+ this.multiCode = code
314
+ this.multiLines.push(msg)
315
+ return
316
+ }
317
+ const lines = this.multiCode === code ? [...this.multiLines, msg] : [msg]
318
+ this.multiCode = undefined
319
+ this.multiLines = []
320
+ this.deliverResponse({ code, lines })
321
+ }
322
+
323
+ private deliverResponse(res: SmtpResponse): void {
324
+ this.replyBytes = 0
325
+ const waiter = this.pendingRead
326
+ if (waiter !== undefined) {
327
+ this.pendingRead = undefined
328
+ clearTimeout(waiter.timer)
329
+ waiter.resolve(res)
330
+ return
331
+ }
332
+ this.responses.push(res)
333
+ }
334
+
335
+ private fail(err: Error): void {
336
+ if (this.fatalError === undefined)
337
+ this.fatalError = err
338
+ const r = this.pendingRead
339
+ if (r !== undefined) {
340
+ this.pendingRead = undefined
341
+ clearTimeout(r.timer)
342
+ r.reject(err)
343
+ }
344
+ const d = this.pendingDrain
345
+ if (d !== undefined) {
346
+ this.pendingDrain = undefined
347
+ clearTimeout(d.timer)
348
+ d.reject(err)
349
+ }
350
+ const h = this.pendingHandshake
351
+ if (h !== undefined) {
352
+ this.pendingHandshake = undefined
353
+ clearTimeout(h.timer)
354
+ h.reject(err)
355
+ }
356
+ }
357
+
358
+ async connect(host: string, port: number, tls: TLSOptions | false): Promise<void> {
359
+ let timedOut = false
360
+ const gen = this.generation
361
+ const connectPromise = Bun.connect<undefined>({
362
+ hostname: host,
363
+ port,
364
+ tls: tls === false ? false : tls,
365
+ socket: this.makeHandler(gen),
366
+ })
367
+ let timer: ReturnType<typeof setTimeout> | undefined
368
+ const timeoutPromise = new Promise<never>((_, reject) => {
369
+ timer = setTimeout(() => {
370
+ timedOut = true
371
+ reject(new Error(`@prunellejs/mail (smtp): connect timed out after ${this.timeoutMs}ms`))
372
+ }, this.timeoutMs)
373
+ })
374
+ try {
375
+ const sock = await Promise.race([connectPromise, timeoutPromise])
376
+ if (this.closed) {
377
+ sock.end()
378
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): connection closed')
379
+ }
380
+ this.socket = sock
381
+ }
382
+ catch (err) {
383
+ if (timedOut) {
384
+ this.generation++
385
+ // Close a late-resolving socket and swallow late rejections so none become unhandled.
386
+ void connectPromise.then(
387
+ (sock) => {
388
+ sock.end()
389
+ },
390
+ () => undefined,
391
+ )
392
+ }
393
+ throw err
394
+ }
395
+ finally {
396
+ if (timer !== undefined)
397
+ clearTimeout(timer)
398
+ }
399
+ }
400
+
401
+ async upgradeTls(tls: TLSOptions): Promise<void> {
402
+ if (this.socket === undefined)
403
+ throw new Error('@prunellejs/mail (smtp): socket is not connected')
404
+ const trailingBytes = this.decoder.decode()
405
+ const hasBufferedPlaintext = trailingBytes.length > 0
406
+ || this.buffer.length > 0
407
+ || this.responses.length > 0
408
+ || this.multiCode !== undefined
409
+ || this.multiLines.length > 0
410
+ || this.unexpectedLines > 0
411
+ this.resetParser()
412
+ if (hasBufferedPlaintext)
413
+ throw new Error('@prunellejs/mail (smtp): unexpected plaintext data received after STARTTLS (RFC 3207)')
414
+
415
+ const nextGen = ++this.generation
416
+ const handshakePromise = new Promise<void>((resolve, reject) => {
417
+ const timer = setTimeout(() => {
418
+ this.pendingHandshake = undefined
419
+ reject(new Error(`@prunellejs/mail (smtp): TLS handshake timed out after ${this.timeoutMs}ms`))
420
+ }, this.timeoutMs)
421
+ this.pendingHandshake = { resolve, reject, timer }
422
+ })
423
+ const [, tlsSocket] = this.socket.upgradeTLS({ tls, socket: this.makeHandler(nextGen) })
424
+ this.socket = tlsSocket
425
+ await handshakePromise
426
+ }
427
+
428
+ readResponse(): Promise<SmtpResponse> {
429
+ if (this.responses.length > 0)
430
+ return Promise.resolve(this.responses.shift()!)
431
+ if (this.fatalError !== undefined)
432
+ return Promise.reject(this.fatalError)
433
+ return new Promise<SmtpResponse>((resolve, reject) => {
434
+ const timer = setTimeout(() => {
435
+ this.pendingRead = undefined
436
+ reject(new Error(`@prunellejs/mail (smtp): response timed out after ${this.timeoutMs}ms`))
437
+ }, this.timeoutMs)
438
+ this.pendingRead = { resolve, reject, timer }
439
+ })
440
+ }
441
+
442
+ async writeAll(data: string): Promise<void> {
443
+ const socket = this.socket
444
+ if (socket === undefined || this.closed)
445
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): socket is closed')
446
+ this.unexpectedLines = 0
447
+ let bytes = Buffer.from(data, 'utf8')
448
+ while (bytes.length > 0) {
449
+ const written = socket.write(bytes)
450
+ if (written < 0)
451
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): socket write failed')
452
+ if (written >= bytes.length)
453
+ return
454
+ bytes = bytes.subarray(written)
455
+ await new Promise<void>((resolve, reject) => {
456
+ const timer = setTimeout(() => {
457
+ this.pendingDrain = undefined
458
+ reject(new Error(`@prunellejs/mail (smtp): write timed out after ${this.timeoutMs}ms`))
459
+ }, this.timeoutMs)
460
+ this.pendingDrain = { resolve, reject, timer }
461
+ })
462
+ }
463
+ }
464
+
465
+ async command(line: string, expectedCodes: readonly number[]): Promise<SmtpResponse> {
466
+ await this.writeAll(`${line}\r\n`)
467
+ const res = await this.readResponse()
468
+ if (!expectedCodes.includes(res.code))
469
+ throw new Error(`@prunellejs/mail (smtp): unexpected response ${res.code} ${res.lines.join(' ')}`)
470
+ return res
471
+ }
472
+
473
+ /** Ends the send: whatever waits on this connection fails with `err`. */
474
+ abort(err: Error): void {
475
+ this.fail(err)
476
+ this.close()
477
+ }
478
+
479
+ close(): void {
480
+ this.closed = true
481
+ this.generation++
482
+ if (this.pendingRead !== undefined) {
483
+ clearTimeout(this.pendingRead.timer)
484
+ this.pendingRead = undefined
485
+ }
486
+ if (this.pendingDrain !== undefined) {
487
+ clearTimeout(this.pendingDrain.timer)
488
+ this.pendingDrain = undefined
489
+ }
490
+ if (this.pendingHandshake !== undefined) {
491
+ clearTimeout(this.pendingHandshake.timer)
492
+ this.pendingHandshake = undefined
493
+ }
494
+ if (this.socket !== undefined) {
495
+ this.socket.end()
496
+ this.socket = undefined
497
+ }
498
+ }
499
+ }
500
+
501
+ function parseCapabilities(lines: readonly string[]): { starttls: boolean, authMethods: Set<string> } {
502
+ let starttls = false
503
+ const authMethods = new Set<string>()
504
+ for (let i = 1; i < lines.length; i++) {
505
+ const upper = lines[i]!.trim().toUpperCase()
506
+ if (upper === 'STARTTLS')
507
+ starttls = true
508
+ if (upper.startsWith('AUTH ') || upper.startsWith('AUTH=')) {
509
+ const tokens = upper.slice(5).split(/\s+/)
510
+ for (const token of tokens) {
511
+ if (token.length > 0)
512
+ authMethods.add(token)
513
+ }
514
+ }
515
+ }
516
+ return { starttls, authMethods }
517
+ }
518
+
519
+ async function negotiateEhlo(conn: SmtpConnection, ehloHost: string): Promise<{ starttls: boolean, authMethods: Set<string> }> {
520
+ await conn.writeAll(`EHLO ${ehloHost}\r\n`)
521
+ const res = await conn.readResponse()
522
+ if (res.code === 250)
523
+ return parseCapabilities(res.lines)
524
+ if (res.code === 500 || res.code === 502) {
525
+ await conn.command(`HELO ${ehloHost}`, [250])
526
+ return { starttls: false, authMethods: new Set() }
527
+ }
528
+ throw new Error(`@prunellejs/mail (smtp): EHLO failed with ${res.code} ${res.lines.join(' ')}`)
529
+ }
530
+
531
+ async function authenticateSmtp(
532
+ conn: SmtpConnection,
533
+ authMethods: ReadonlySet<string>,
534
+ user: string,
535
+ pass: string,
536
+ ): Promise<void> {
537
+ if (authMethods.has('LOGIN') && !authMethods.has('PLAIN')) {
538
+ await conn.command('AUTH LOGIN', [334])
539
+ await conn.command(Buffer.from(user, 'utf8').toString('base64'), [334])
540
+ await conn.command(Buffer.from(pass, 'utf8').toString('base64'), [235])
541
+ return
542
+ }
543
+ const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64')
544
+ await conn.command(`AUTH PLAIN ${token}`, [235])
545
+ }
546
+
547
+ /** At most `max` holders at once; the next waits for `release()`, which hands its place on. */
548
+ function createConnectionLimit(max: number): { acquire: () => Promise<void>, release: () => void } {
549
+ let active = 0
550
+ const waiting: Array<() => void> = []
551
+ return {
552
+ async acquire() {
553
+ if (active < max) {
554
+ active++
555
+ return
556
+ }
557
+ await new Promise<void>(resolve => waiting.push(resolve))
558
+ },
559
+ release() {
560
+ const next = waiting.shift()
561
+ if (next !== undefined)
562
+ next()
563
+ else
564
+ active--
565
+ },
566
+ }
567
+ }
568
+
569
+ /** Zero-dependency SMTP/SMTPS/STARTTLS transport backed directly by `Bun.connect`. */
570
+ export function smtp(options: SmtpOptions): MailTransport {
571
+ const host = options.host.trim()
572
+ if (host.length === 0)
573
+ throw new RangeError('@prunellejs/mail (smtp): `host` must be a non-empty hostname')
574
+ const secure = options.secure ?? options.port === 465
575
+ const port = options.port ?? (secure ? 465 : 587)
576
+ const ehloHost = validateEhloHost(options.ehloHost ?? 'localhost')
577
+ if (!secure && options.requireTls === true && options.disableStartTls === true)
578
+ throw new RangeError('@prunellejs/mail (smtp): cannot set both `requireTls` and `disableStartTls`')
579
+ const requireTls = options.requireTls ?? !(options.allowInsecureAuth === true || isLoopbackHost(host))
580
+ const timeoutMs = options.timeoutMs ?? DEFAULT_SMTP_TIMEOUT_MS
581
+ const deadlineMs = options.deadlineMs ?? DEFAULT_SMTP_DEADLINE_MS
582
+ const connections = createConnectionLimit(Math.max(1, options.maxConnections ?? DEFAULT_SMTP_CONNECTIONS))
583
+ const tlsConfig: TLSOptions = {
584
+ serverName: host,
585
+ rejectUnauthorized: options.rejectUnauthorized ?? true,
586
+ }
587
+
588
+ return {
589
+ async send(mail: SentMail): Promise<void> {
590
+ const envelopeFrom = extractEmailAddress(mail.from)
591
+ const envelopeTo = mail.to.map(extractEmailAddress)
592
+ const message = buildMimeMessage(mail, ehloHost)
593
+ await connections.acquire()
594
+ const conn = new SmtpConnection(timeoutMs)
595
+ const deadline = setTimeout(() => conn.abort(new Error(`@prunellejs/mail (smtp): the send passed its ${deadlineMs}ms deadline`)), deadlineMs)
596
+
597
+ try {
598
+ await conn.connect(host, port, secure ? tlsConfig : false)
599
+ const greeting = await conn.readResponse()
600
+ if (greeting.code !== 220)
601
+ throw new Error(`@prunellejs/mail (smtp): unexpected greeting ${greeting.code} ${greeting.lines.join(' ')}`)
602
+
603
+ let caps = await negotiateEhlo(conn, ehloHost)
604
+
605
+ let encrypted = secure
606
+ if (!secure && !options.disableStartTls) {
607
+ if (caps.starttls) {
608
+ await conn.command('STARTTLS', [220])
609
+ await conn.upgradeTls(tlsConfig)
610
+ encrypted = true
611
+ caps = await negotiateEhlo(conn, ehloHost)
612
+ }
613
+ else if (requireTls) {
614
+ 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')
615
+ }
616
+ }
617
+
618
+ if (options.user !== undefined || options.pass !== undefined) {
619
+ const allowPlaintextAuth = isLoopbackHost(host) || options.allowInsecureAuth === true || options.requireTls === false
620
+ if (!encrypted && !allowPlaintextAuth)
621
+ 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)')
622
+ await authenticateSmtp(conn, caps.authMethods, options.user ?? '', options.pass ?? '')
623
+ }
624
+
625
+ await conn.command(`MAIL FROM:<${envelopeFrom}>`, [250])
626
+ for (const recipient of envelopeTo)
627
+ await conn.command(`RCPT TO:<${recipient}>`, [250, 251])
628
+
629
+ await conn.command('DATA', [354])
630
+ await conn.writeAll(dotStuffSmtpData(message))
631
+ const dataRes = await conn.readResponse()
632
+ if (dataRes.code !== 250)
633
+ throw new Error(`@prunellejs/mail (smtp): DATA rejected with ${dataRes.code} ${dataRes.lines.join(' ')}`)
634
+
635
+ // 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.
636
+ await conn.writeAll('QUIT\r\n').then(() => conn.readResponse()).catch(() => undefined)
637
+ }
638
+ finally {
639
+ clearTimeout(deadline)
640
+ conn.close()
641
+ connections.release()
642
+ }
643
+ },
644
+ }
645
+ }