@prunellejs/mail 0.6.0 → 0.7.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -31,18 +31,19 @@
31
31
  - `await mail.send({ to, subject, body: <Welcome name="Ada" /> })` renders both `html` and a clean `text` alternative automatically (explicit `text` or `html` overrides the rendered part).
32
32
  - `await renderMail(node)` returns `{ html, text }` from any JSX/TSX element, compiled `Html`, async component result, or render factory.
33
33
  - Built-in email-safe components work identically in compiled Prunelle routes and direct Bun execution:
34
- - `Email({ lang?, title?, preview?, backgroundColor?, containerBackgroundColor?, width?, children })` — full HTML email document with Outlook MSO namespaces & DPI XML, dark-mode `<meta>` + `@media (prefers-color-scheme: dark)` CSS, hidden preheader, and centered 600px table layout.
35
- - `Section`, `Heading` (`h1`–`h3`), `Text` (`muted?`), `Button` (Outlook VML roundrect + dark-mode CTA), `Divider`, `Footer`, `Link`.
34
+ - `Email({ lang? (default: `lang` from `prunelle.config.ts`, else `en`), title?, preview?, backgroundColor?, containerBackgroundColor?, width?, children })` — full HTML email document with Outlook MSO namespaces & DPI XML, dark-mode `<meta>` + `@media (prefers-color-scheme: dark)` CSS, hidden preheader, and centered 600px table layout.
35
+ - `Section`, `Heading` (`h1`–`h3`), `Text` (`muted?`), `Button` (Outlook VML roundrect as wide as its label + dark-mode CTA), `Divider`, `Footer`, `Link`.
36
36
 
37
37
  ## Transports & `MAIL_URL`
38
38
 
39
39
  - `transportFromUrl(url)` supports:
40
- - `smtp://[user:pass@]host[:port]` (default port 587; upgrades via `STARTTLS` when advertised, `?tls=true`/`?starttls=true` to require, `?tls=false` to disable, `?allowInsecureAuth=true` to allow plaintext `AUTH` on non-loopback hosts)
40
+ - `smtp://[user:pass@]host[:port]` (default port 587; `STARTTLS` is required on a non-loopback host, so a server that does not offer it fails the send instead of getting the mail in plaintext; `?tls=true`/`?starttls=true` requires it on a loopback host too, `?tls=opportunistic` sends in plaintext when it is missing, `?tls=false` disables it, `?allowInsecureAuth=true` allows a plaintext send and plaintext `AUTH` on non-loopback hosts; any other `tls` value throws)
41
41
  - `smtps://[user:pass@]host[:port]` (default port 465; implicit TLS)
42
42
  - `resend://<apiKey>` or `resend://:<apiKey>@api.resend.com`
43
43
  - `postmark://<serverToken>` or `postmark://:<serverToken>@api.postmarkapp.com`
44
- - `smtp(options)` uses `Bun.connect` TCP/TLS sockets directly (zero npm dependencies): RFC 5321 multi-line parsing, `EHLO`, `STARTTLS` (with RFC 3207 response-injection protection and plaintext credential downgrade refusal on non-loopback hosts unless `allowInsecureAuth: true` or `requireTls: false`), `AUTH PLAIN` / `AUTH LOGIN`, `MAIL FROM`, `RCPT TO`, `DATA` with CRLF normalization + dot-stuffing, MIME `multipart/alternative`, and `QUIT`.
45
- - `resend({ apiKey?, endpoint?, timeoutMs?, retries? })` and `postmark({ serverToken?, endpoint?, timeoutMs?, retries?, messageStream? })` use native `fetch()` with timeout and retries on `429`/`5xx` and transient network/timeout errors.
44
+ - `smtp(options)` uses `Bun.connect` TCP/TLS sockets directly (zero npm dependencies): RFC 5321 multi-line parsing, `EHLO`, `STARTTLS` (with RFC 3207 response-injection protection and plaintext credential downgrade refusal on non-loopback hosts unless `allowInsecureAuth: true` or `requireTls: false`), `AUTH PLAIN` / `AUTH LOGIN`, `MAIL FROM`, `RCPT TO`, `DATA` with CRLF normalization + dot-stuffing, MIME `multipart/alternative`, and `QUIT`. Bodies go out as quoted-printable (7-bit, lines of at most 76 characters), headers are folded at 78, a non-ASCII display name or subject becomes RFC 2047 encoded words of at most 75 characters, and once the server accepts the data a failing `QUIT` does not fail the send.
45
+ - `resend({ apiKey?, endpoint?, timeoutMs?, retries? })` and `postmark({ serverToken?, endpoint?, timeoutMs?, retries?, messageStream? })` use native `fetch()` with a timeout. `resend()` retries `429`/`5xx` and transient network/timeout errors under an idempotency key; `postmark()` has none, so it retries only `429`. Provider error bodies are cut to 200 characters, a malformed `MAIL_URL` is not echoed, and Resend and Postmark are US processors (DPA with SCCs and DPF, see the docs: a transfer outside the EU).
46
+ - `smtp({ maxConnections? (4), deadlineMs? (60_000) })`: connections open at once and the longest a send may take; a reply past 64 KiB drops the connection. `buildMimeMessage` throws on a line break in an address, subject or id, and `<Link>`/`<Button>` refuse `//host`, control characters and backslashes in `href`.
46
47
 
47
48
  ## Mounted Routes (`prunelle dev` or `NODE_ENV=test` only — never in production or built servers outside test)
48
49
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/mail",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Zero-dependency email delivery (JSX/TSX templates, SMTP/SMTPS, Resend, Postmark, MAIL_URL, @prunellejs/jobs retries) and dev outbox/preview plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-mail"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.6.0"
24
+ "prunelle": "^0.7.0"
25
25
  }
26
26
  }
package/src/components.ts CHANGED
@@ -2,12 +2,12 @@
2
2
  // Built with `raw`/`esc`/`escAttr` from `prunelle/server` so they render identically both in compiled Prunelle routes and direct Bun execution.
3
3
 
4
4
  import type { Html, PrunelleChild } from 'prunelle/jsx-runtime'
5
- import { esc, escAttr, raw } from 'prunelle/server'
5
+ import { esc, escAttr, raw, safeRedirect } from 'prunelle/server'
6
6
 
7
7
  export type TextAlign = 'left' | 'center' | 'right'
8
8
 
9
9
  export interface EmailProps {
10
- /** Document language attribute (default `'en'`). */
10
+ /** Document language attribute (default: `lang` from `prunelle.config.ts`, else `'en'`). */
11
11
  lang?: string | undefined
12
12
  /** Optional `<title>` inside `<head>`. */
13
13
  title?: string | undefined
@@ -73,8 +73,9 @@ export interface LinkProps {
73
73
  children?: PrunelleChild | undefined
74
74
  }
75
75
 
76
- const SAFE_URL_SCHEME_RE = /^(?:https?:|mailto:|tel:|\/|#)/i
76
+ const SAFE_URL_SCHEME_RE = /^(?:https?:|mailto:|tel:)/i
77
77
  const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
78
+ const CONTROL_OR_BACKSLASH_RE = /[\u0000-\u001F\u007F\\]/
78
79
 
79
80
  const EMAIL_HEAD_CSS = [
80
81
  ':root{color-scheme:light dark;supported-color-schemes:light dark;}',
@@ -108,7 +109,10 @@ const PREVIEW_SPACER = '&zwnj;&nbsp;'.repeat(24)
108
109
 
109
110
  function safeEmailUrl(href: string, component: string): string {
110
111
  const trimmed = href.trim()
111
- if (HAS_SCHEME_RE.test(trimmed) && !SAFE_URL_SCHEME_RE.test(trimmed))
112
+ // A browser drops a tab or newline from a URL, so `java\tscript:` is `javascript:` and `/\t/host` is `//host`: no control character or backslash is let through, and a path goes through the same check as a redirect.
113
+ const unsafe = CONTROL_OR_BACKSLASH_RE.test(trimmed)
114
+ || (trimmed.startsWith('/') ? safeRedirect(trimmed, '') !== trimmed : HAS_SCHEME_RE.test(trimmed) && !SAFE_URL_SCHEME_RE.test(trimmed))
115
+ if (unsafe)
112
116
  throw new RangeError(`@prunellejs/mail: <${component}> refused unsafe URL "${href}"`)
113
117
  return trimmed
114
118
  }
@@ -122,13 +126,28 @@ function appendExtraStyle(base: string, extra?: string): string {
122
126
  return base.endsWith(';') ? `${base}${normalized}` : `${base};${normalized}`
123
127
  }
124
128
 
129
+ const TAG_RE = /<[^>]*>/g
130
+ const ENTITY_RE = /&#?\w+;/g
131
+
132
+ // Characters a reader sees in escaped HTML: tags dropped, each entity one character.
133
+ function visibleLength(html: string): number {
134
+ return html.replace(TAG_RE, '').replace(ENTITY_RE, '_').length
135
+ }
136
+
125
137
  function safeAlign(align?: TextAlign): TextAlign {
126
138
  return align === 'center' || align === 'right' ? align : 'left'
127
139
  }
128
140
 
141
+ let appLang: string | undefined
142
+
143
+ /** Set by the mail plugin from `prunelle.config.ts`, so an email speaks the app's language unless it says otherwise. */
144
+ export function setAppLang(lang: string | undefined): void {
145
+ appLang = lang
146
+ }
147
+
129
148
  /** Root HTML email document with Outlook MSO namespaces/DPI settings, dark-mode meta + CSS, and centered 600px table container. */
130
149
  export function Email(props: EmailProps = {}): Html {
131
- const lang = props.lang ?? 'en'
150
+ const lang = props.lang ?? appLang ?? 'en'
132
151
  const bg = props.backgroundColor ?? '#f4f4f5'
133
152
  const cardBg = props.containerBackgroundColor ?? '#ffffff'
134
153
  const width = props.width ?? 600
@@ -210,6 +229,8 @@ export function Button(props: ButtonProps): Html {
210
229
  const align = safeAlign(props.align)
211
230
  const arcsize = Math.min(50, Math.max(0, Math.round((radius / 44) * 100)))
212
231
  const label = esc(props.children)
232
+ // VML cannot size to its text: about 8.5px per character of 15px semibold, plus the 24px side padding.
233
+ const vmlWidth = Math.max(120, Math.round(visibleLength(label) * 8.5) + 48)
213
234
  const linkStyle = appendExtraStyle(
214
235
  `display:inline-block;padding:12px 24px;background-color:${bg};color:${color};font-size:15px;font-weight:600;line-height:1.2;text-decoration:none;border-radius:${radius}px;mso-hide:all;`,
215
236
  props.style,
@@ -218,7 +239,7 @@ export function Button(props: ButtonProps): Html {
218
239
  return raw(
219
240
  `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;margin:20px 0;">`
220
241
  + `<tr><td align="${align}">`
221
- + `<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="${escAttr(href)}" style="height:44px;v-text-anchor:middle;width:220px;" arcsize="${arcsize}%" stroke="f" fillcolor="${escAttr(bg)}"><w:anchorlock/><center style="color:${escAttr(color)};font-family:sans-serif;font-size:15px;font-weight:600;">${label}</center></v:roundrect><![endif]-->`
242
+ + `<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="${escAttr(href)}" style="height:44px;v-text-anchor:middle;width:${vmlWidth}px;" arcsize="${arcsize}%" stroke="f" fillcolor="${escAttr(bg)}"><w:anchorlock/><center style="color:${escAttr(color)};font-family:sans-serif;font-size:15px;font-weight:600;">${label}</center></v:roundrect><![endif]-->`
222
243
  + `<!--[if !mso]><!--><a href="${escAttr(href)}" class="pru-email-btn" style="${escAttr(linkStyle)}">${label}</a><!--<![endif]-->`
223
244
  + `</td></tr></table>`,
224
245
  )
package/src/index.ts CHANGED
@@ -5,7 +5,9 @@ import type { JobsQueueOptions, JobsService } from 'prunelle/config'
5
5
  import type { PrunelleChild } from 'prunelle/jsx-runtime'
6
6
  import type { MailBody, Mailer, MailerOptions, MailMessage, MailPreviewEntry, MailPreviewRegisterOptions, MailTransport, SentMail } from './types'
7
7
  import { definePlugin, JOBS_SERVICE } from 'prunelle/config'
8
+ import { devFromEnv } from 'prunelle/internal/server'
8
9
  import { nodeEnv } from 'prunelle/server'
10
+ import { setAppLang } from './components'
9
11
  import { renderOutboxHtml, renderPreviewEntries } from './preview'
10
12
  import { renderMail } from './render'
11
13
  import { resend, transportFromUrl } from './transports'
@@ -150,11 +152,13 @@ export function createMailer(options: MailerOptions = {}): Mailer {
150
152
  after: ['@prunellejs/jobs'],
151
153
  server(api) {
152
154
  serverDev = api.dev
155
+ setAppLang(typeof api.config?.lang === 'string' ? api.config.lang : undefined)
153
156
  injectJobs = () => api.inject(JOBS_SERVICE)
154
157
  ensureJobsQueue()
155
158
 
156
159
  api.onShutdown(() => {
157
160
  injectJobs = undefined
161
+ setAppLang(undefined)
158
162
  })
159
163
 
160
164
  const enablePreview = options.preview !== false && isDevOrTest(api.dev)
@@ -184,7 +188,7 @@ export function createMailer(options: MailerOptions = {}): Mailer {
184
188
  requires() {
185
189
  const unmet: string[] = []
186
190
  if (getTransport() === undefined && !options.optional)
187
- unmet.push('no transport, so every send() throws: set `RESEND_API_KEY`, or pass `transport` to `createMailer()` (`optional: true` drops mail instead).')
191
+ unmet.push('no transport, so every send() throws: set `MAIL_URL` or `RESEND_API_KEY`, or pass `transport` to `createMailer()` (`optional: true` drops mail instead).')
188
192
  if ((options.from ?? process.env.MAIL_FROM) === undefined)
189
193
  unmet.push('no sender, so mail goes out from noreply@localhost: set `MAIL_FROM`, or pass `from` to `createMailer()`.')
190
194
  return unmet
@@ -231,7 +235,7 @@ export function createMailer(options: MailerOptions = {}): Mailer {
231
235
  sentAt: new Date().toISOString(),
232
236
  }
233
237
 
234
- const devOrTest = isDevOrTest(serverDev ?? (process.env.PRUNELLE_DEV === '1'))
238
+ const devOrTest = isDevOrTest(serverDev ?? devFromEnv())
235
239
  await deliverRecord({
236
240
  record,
237
241
  transport: getTransport(),
package/src/preview.ts CHANGED
@@ -6,7 +6,7 @@ import { esc, escAttr } from 'prunelle/server'
6
6
  import { renderMail } from './render'
7
7
 
8
8
  const MAIL_OUTBOX_CSS = [
9
- 'body{font-family:system-ui,sans-serif;max-width:52rem;margin:2rem auto;padding:0 1rem;background:#f9fafb;color:#111827}',
9
+ 'body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Noto Sans","Helvetica Neue",Arial,sans-serif;max-width:52rem;margin:2rem auto;padding:0 1rem;background:#f9fafb;color:#111827}',
10
10
  'h1{margin:0 0 1.25rem;font-size:1.5rem}',
11
11
  '.section-title{margin:2rem 0 .75rem;font-size:1.1rem;color:#374151;border-bottom:1px solid #e5e7eb;padding-bottom:.35rem}',
12
12
  'article{border:1px solid #e5e7eb;border-radius:8px;padding:1rem;margin-bottom:1rem;background:#fff}',
package/src/smtp.ts CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { Socket, SocketHandler, TLSOptions } from 'bun'
5
5
  import type { MailTransport, SentMail } from './types'
6
+ import { isLoopbackHost } from 'prunelle/internal/server'
6
7
  import { assertNoHeaderInjection, extractEmailAddress } from './types'
7
8
 
8
9
  export interface SmtpOptions {
@@ -10,7 +11,7 @@ export interface SmtpOptions {
10
11
  port?: number | undefined
11
12
  /** Implicit TLS (`smtps://`, typically port 465). Defaults to `true` when `port === 465`, else `false`. */
12
13
  secure?: boolean | undefined
13
- /** Require STARTTLS upgrade on plaintext connections; fails if server does not advertise STARTTLS. */
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. */
14
15
  requireTls?: boolean | undefined
15
16
  /** Disable automatic STARTTLS even when the server advertises it. */
16
17
  disableStartTls?: boolean | undefined
@@ -24,6 +25,10 @@ export interface SmtpOptions {
24
25
  ehloHost?: string | undefined
25
26
  /** Socket read/connect timeout in milliseconds (default `15_000`). */
26
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
27
32
  }
28
33
 
29
34
  interface SmtpResponse {
@@ -32,6 +37,11 @@ interface SmtpResponse {
32
37
  }
33
38
 
34
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
35
45
  const SMTP_LINE_RE = /^(\d{3})([ -])(.*)$/
36
46
  const NON_ASCII_RE = /[^\x20-\x7E]/
37
47
  const WHITESPACE_OR_ANGLE_RE = /[\s<>]/
@@ -43,15 +53,82 @@ function validateEhloHost(value: string): string {
43
53
  return value
44
54
  }
45
55
 
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
- }
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 = /^"(.*)"$/
50
62
 
63
+ /** Splits non-ASCII text into space-separated RFC 2047 encoded words, never cutting a UTF-8 sequence. */
51
64
  function encodeRfc2047(value: string): string {
52
65
  if (!NON_ASCII_RE.test(value))
53
66
  return value
54
- return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`
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')
55
132
  }
56
133
 
57
134
  function normalizeCrlf(text: string): string {
@@ -68,11 +145,13 @@ export function dotStuffSmtpData(rawMessage: string): string {
68
145
  /** Builds an RFC 5322 + MIME message (using `multipart/alternative` when both `text` and `html` are present). */
69
146
  export function buildMimeMessage(mail: SentMail, domain = 'localhost'): string {
70
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)
71
150
  const headers = [
72
- `From: ${mail.from}`,
73
- `To: ${mail.to.join(', ')}`,
74
- ...(mail.replyTo !== undefined ? [`Reply-To: ${mail.replyTo}`] : []),
75
- `Subject: ${encodeRfc2047(mail.subject)}`,
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)),
76
155
  `Date: ${new Date(mail.sentAt).toUTCString()}`,
77
156
  `Message-ID: <${mail.id}@${safeDomain}>`,
78
157
  'MIME-Version: 1.0',
@@ -89,26 +168,26 @@ export function buildMimeMessage(mail: SentMail, domain = 'localhost'): string {
89
168
  '',
90
169
  `--${boundary}`,
91
170
  'Content-Type: text/plain; charset=utf-8',
92
- 'Content-Transfer-Encoding: 8bit',
171
+ 'Content-Transfer-Encoding: quoted-printable',
93
172
  '',
94
- normalizeCrlf(mail.text!),
173
+ encodeQuotedPrintable(mail.text!),
95
174
  `--${boundary}`,
96
175
  'Content-Type: text/html; charset=utf-8',
97
- 'Content-Transfer-Encoding: 8bit',
176
+ 'Content-Transfer-Encoding: quoted-printable',
98
177
  '',
99
- normalizeCrlf(mail.html!),
178
+ encodeQuotedPrintable(mail.html!),
100
179
  `--${boundary}--`,
101
180
  '',
102
181
  ].join('\r\n')
103
182
  }
104
183
 
105
184
  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`
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`
108
187
  }
109
188
 
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`
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`
112
191
  }
113
192
 
114
193
  interface PendingRead {
@@ -130,6 +209,7 @@ class SmtpConnection {
130
209
  private multiLines: string[] = []
131
210
  private readonly responses: SmtpResponse[] = []
132
211
  private unexpectedLines = 0
212
+ private replyBytes = 0
133
213
  private generation = 0
134
214
  private pendingRead: PendingRead | undefined
135
215
  private pendingDrain: PendingDrain | undefined
@@ -146,6 +226,7 @@ class SmtpConnection {
146
226
  this.multiLines = []
147
227
  this.responses.length = 0
148
228
  this.unexpectedLines = 0
229
+ this.replyBytes = 0
149
230
  this.decoder = new TextDecoder()
150
231
  }
151
232
 
@@ -199,6 +280,12 @@ class SmtpConnection {
199
280
  }
200
281
 
201
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
+ }
202
289
  this.buffer += text
203
290
  for (;;) {
204
291
  const nl = this.buffer.indexOf('\n')
@@ -234,6 +321,7 @@ class SmtpConnection {
234
321
  }
235
322
 
236
323
  private deliverResponse(res: SmtpResponse): void {
324
+ this.replyBytes = 0
237
325
  const waiter = this.pendingRead
238
326
  if (waiter !== undefined) {
239
327
  this.pendingRead = undefined
@@ -382,6 +470,12 @@ class SmtpConnection {
382
470
  return res
383
471
  }
384
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
+
385
479
  close(): void {
386
480
  this.closed = true
387
481
  this.generation++
@@ -450,6 +544,28 @@ async function authenticateSmtp(
450
544
  await conn.command(`AUTH PLAIN ${token}`, [235])
451
545
  }
452
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
+
453
569
  /** Zero-dependency SMTP/SMTPS/STARTTLS transport backed directly by `Bun.connect`. */
454
570
  export function smtp(options: SmtpOptions): MailTransport {
455
571
  const host = options.host.trim()
@@ -460,7 +576,10 @@ export function smtp(options: SmtpOptions): MailTransport {
460
576
  const ehloHost = validateEhloHost(options.ehloHost ?? 'localhost')
461
577
  if (!secure && options.requireTls === true && options.disableStartTls === true)
462
578
  throw new RangeError('@prunellejs/mail (smtp): cannot set both `requireTls` and `disableStartTls`')
579
+ const requireTls = options.requireTls ?? !(options.allowInsecureAuth === true || isLoopbackHost(host))
463
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))
464
583
  const tlsConfig: TLSOptions = {
465
584
  serverName: host,
466
585
  rejectUnauthorized: options.rejectUnauthorized ?? true,
@@ -470,7 +589,10 @@ export function smtp(options: SmtpOptions): MailTransport {
470
589
  async send(mail: SentMail): Promise<void> {
471
590
  const envelopeFrom = extractEmailAddress(mail.from)
472
591
  const envelopeTo = mail.to.map(extractEmailAddress)
592
+ const message = buildMimeMessage(mail, ehloHost)
593
+ await connections.acquire()
473
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)
474
596
 
475
597
  try {
476
598
  await conn.connect(host, port, secure ? tlsConfig : false)
@@ -488,8 +610,8 @@ export function smtp(options: SmtpOptions): MailTransport {
488
610
  encrypted = true
489
611
  caps = await negotiateEhlo(conn, ehloHost)
490
612
  }
491
- else if (options.requireTls) {
492
- throw new Error('@prunellejs/mail (smtp): server does not advertise STARTTLS')
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')
493
615
  }
494
616
  }
495
617
 
@@ -505,24 +627,18 @@ export function smtp(options: SmtpOptions): MailTransport {
505
627
  await conn.command(`RCPT TO:<${recipient}>`, [250, 251])
506
628
 
507
629
  await conn.command('DATA', [354])
508
- const mime = buildMimeMessage(mail, ehloHost)
509
- await conn.writeAll(dotStuffSmtpData(mime))
630
+ await conn.writeAll(dotStuffSmtpData(message))
510
631
  const dataRes = await conn.readResponse()
511
632
  if (dataRes.code !== 250)
512
633
  throw new Error(`@prunellejs/mail (smtp): DATA rejected with ${dataRes.code} ${dataRes.lines.join(' ')}`)
513
634
 
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
- }
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)
523
637
  }
524
638
  finally {
639
+ clearTimeout(deadline)
525
640
  conn.close()
641
+ connections.release()
526
642
  }
527
643
  },
528
644
  }
package/src/transports.ts CHANGED
@@ -5,6 +5,8 @@ import { smtp } from './smtp'
5
5
  import { MailNotConfiguredError } from './types'
6
6
 
7
7
  const DEFAULT_HTTP_TIMEOUT_MS = 10_000
8
+ // A provider's error body lands in the thrown message and so in logs: enough to name the cause, not to copy a mail or a token back.
9
+ const ERROR_BODY_MAX_CHARS = 200
8
10
 
9
11
  export interface ResendOptions {
10
12
  apiKey?: string | undefined
@@ -40,8 +42,10 @@ async function sendJsonWithRetry(params: {
40
42
  body: string
41
43
  timeoutMs: number
42
44
  retries: number
45
+ /** Whether the provider drops a repeated send (an idempotency key); without it only a 429, which sent nothing, is retried. */
46
+ idempotent: boolean
43
47
  }): Promise<void> {
44
- const { provider, endpoint, headers, body, timeoutMs, retries } = params
48
+ const { provider, endpoint, headers, body, timeoutMs, retries, idempotent } = params
45
49
  for (let attempt = 0; ; attempt++) {
46
50
  let res: Response
47
51
  try {
@@ -53,15 +57,16 @@ async function sendJsonWithRetry(params: {
53
57
  })
54
58
  }
55
59
  catch (error) {
56
- if (!isRetryableFetchError(error) || attempt >= retries)
60
+ if (!idempotent || !isRetryableFetchError(error) || attempt >= retries)
57
61
  throw error
58
62
  await Bun.sleep(retryDelayMs(undefined, attempt))
59
63
  continue
60
64
  }
61
65
  if (res.ok)
62
66
  return
63
- const text = await res.text()
64
- if ((res.status !== 429 && res.status < 500) || attempt >= retries)
67
+ const text = (await res.text()).slice(0, ERROR_BODY_MAX_CHARS)
68
+ const retryable = res.status === 429 || (idempotent && res.status >= 500)
69
+ if (!retryable || attempt >= retries)
65
70
  throw new Error(`@prunellejs/mail (${provider}): HTTP ${res.status}: ${text}`)
66
71
  await Bun.sleep(retryDelayMs(res, attempt))
67
72
  }
@@ -96,12 +101,13 @@ export function resend(options: ResendOptions = {}): MailTransport {
96
101
  body,
97
102
  timeoutMs,
98
103
  retries,
104
+ idempotent: true,
99
105
  })
100
106
  },
101
107
  }
102
108
  }
103
109
 
104
- /** Zero-dependency Postmark HTTP transport using native fetch(); retries 429 and 5xx answers like `resend()`. */
110
+ /** Zero-dependency Postmark HTTP transport using native fetch(). Postmark documents no idempotency key, so only a 429 answer, which sent nothing, is retried `retries` times (default 2): a 5xx or a timeout may have sent the mail, and is thrown instead of risking a second one. */
105
111
  export function postmark(options: PostmarkOptions = {}): MailTransport {
106
112
  const endpoint = options.endpoint ?? 'https://api.postmarkapp.com/email'
107
113
  const timeoutMs = options.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS
@@ -131,6 +137,7 @@ export function postmark(options: PostmarkOptions = {}): MailTransport {
131
137
  body,
132
138
  timeoutMs,
133
139
  retries,
140
+ idempotent: false,
134
141
  })
135
142
  },
136
143
  }
@@ -181,6 +188,23 @@ function parseApiUrl(
181
188
  return { token, endpoint, timeoutMs, retries }
182
189
  }
183
190
 
191
+ const TLS_PARAM_MODES: Readonly<Record<string, { requireTls: boolean | undefined, disableStartTls: boolean }>> = {
192
+ true: { requireTls: true, disableStartTls: false },
193
+ 1: { requireTls: true, disableStartTls: false },
194
+ opportunistic: { requireTls: false, disableStartTls: false },
195
+ false: { requireTls: undefined, disableStartTls: true },
196
+ 0: { requireTls: undefined, disableStartTls: true },
197
+ }
198
+
199
+ function parseTlsParam(value: string | null): { requireTls: boolean | undefined, disableStartTls: boolean } {
200
+ if (value === null)
201
+ return { requireTls: undefined, disableStartTls: false }
202
+ const mode = TLS_PARAM_MODES[value]
203
+ if (mode === undefined)
204
+ throw new RangeError(`@prunellejs/mail: invalid tls value "${value}" in MAIL_URL: use true, opportunistic or false`)
205
+ return mode
206
+ }
207
+
184
208
  /** Builds a `MailTransport` from a `MAIL_URL` connection string (`smtp://`, `smtps://`, `resend://`, or `postmark://`). */
185
209
  export function transportFromUrl(url: string): MailTransport {
186
210
  const trimmed = url.trim()
@@ -189,7 +213,8 @@ export function transportFromUrl(url: string): MailTransport {
189
213
  parsed = new URL(trimmed)
190
214
  }
191
215
  catch {
192
- throw new RangeError(`@prunellejs/mail: invalid MAIL_URL "${url}"`)
216
+ // Never echo the value: it holds the password or the API key.
217
+ throw new RangeError('@prunellejs/mail: invalid MAIL_URL (not echoed, it holds credentials): expected smtp://user:pass@host:587, smtps://, resend://<key> or postmark://<token>')
193
218
  }
194
219
 
195
220
  const protocol = parsed.protocol.toLowerCase()
@@ -203,8 +228,7 @@ export function transportFromUrl(url: string): MailTransport {
203
228
  if (!Number.isInteger(port) || port < 1 || port > 65535)
204
229
  throw new RangeError(`@prunellejs/mail: invalid SMTP port "${parsed.port}" in MAIL_URL`)
205
230
  const tlsParam = parsed.searchParams.get('tls') ?? parsed.searchParams.get('starttls')
206
- const requireTls = tlsParam === 'true' || tlsParam === '1' ? true : undefined
207
- const disableStartTls = tlsParam === 'false' || tlsParam === '0'
231
+ const { requireTls, disableStartTls } = parseTlsParam(tlsParam)
208
232
  const insecureAuthParam = parsed.searchParams.get('allowInsecureAuth')
209
233
  const allowInsecureAuth = insecureAuthParam === 'true' || insecureAuthParam === '1' ? true : undefined
210
234
  const rejectUnauthorized = parsed.searchParams.get('rejectUnauthorized') !== 'false'