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