@tylix/mail 0.4.0 → 0.5.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/Mailer.js CHANGED
@@ -12,6 +12,16 @@ function resolveDriver(config) {
12
12
  return new LogDriver()
13
13
  }
14
14
 
15
+ // A logging failure (for example the mail_logs table not existing yet)
16
+ // must never change the outcome of the send itself.
17
+ async function logSafely(entry) {
18
+ try {
19
+ await MailLog.create(entry)
20
+ } catch (logErr) {
21
+ console.error('[mail] could not write mail log:', logErr.message)
22
+ }
23
+ }
24
+
15
25
  export class Mail {
16
26
  static async send({ to, subject, view, data = {} }, config) {
17
27
  let html = ''
@@ -26,13 +36,15 @@ export class Mail {
26
36
  html = templateEngine.render(template, data)
27
37
  }
28
38
 
39
+ // The recipient column is a string, so store arrays as "a, b".
40
+ const recipientLabel = [].concat(to).join(', ')
29
41
  const driver = resolveDriver(config)
30
42
 
31
43
  try {
32
44
  const result = await driver.deliver({ to, subject, html })
33
45
  if (config.driver === 'smtp') {
34
- await MailLog.create({
35
- recipient: to,
46
+ await logSafely({
47
+ recipient: recipientLabel,
36
48
  subject,
37
49
  body: html,
38
50
  driver: 'smtp',
@@ -41,8 +53,8 @@ export class Mail {
41
53
  }
42
54
  return result
43
55
  } catch (err) {
44
- await MailLog.create({
45
- recipient: to,
56
+ await logSafely({
57
+ recipient: recipientLabel,
46
58
  subject,
47
59
  body: html,
48
60
  driver: config.driver,
@@ -52,4 +64,4 @@ export class Mail {
52
64
  throw err
53
65
  }
54
66
  }
55
- }
67
+ }
package/SmtpClient.js ADDED
@@ -0,0 +1,362 @@
1
+ import net from 'node:net'
2
+ import tls from 'node:tls'
3
+ import crypto from 'node:crypto'
4
+
5
+ const DEFAULT_TIMEOUT_MS = 10_000
6
+
7
+ /**
8
+ * Buffers raw socket bytes and yields complete SMTP responses.
9
+ * A single response can span multiple `data` events (partial line),
10
+ * and can itself be multi-line (continuation lines use "250-", the
11
+ * final line uses "250 "). This waits for both conditions before
12
+ * resolving.
13
+ */
14
+ class SmtpResponseReader {
15
+ constructor(socket) {
16
+ this.socket = socket
17
+ this.buffer = ''
18
+ this.pending = []
19
+ this.onData = (chunk) => {
20
+ this.buffer += chunk.toString('utf-8')
21
+ this.flush()
22
+ }
23
+ this.onError = (err) => {
24
+ this.rejectAll(err)
25
+ }
26
+ socket.on('data', this.onData)
27
+ socket.on('error', this.onError)
28
+ }
29
+
30
+ flush() {
31
+ while (true) {
32
+ const lines = this.buffer.split('\r\n')
33
+ // Keep the last (possibly incomplete) fragment in the buffer.
34
+ const complete = lines.slice(0, -1)
35
+ if (complete.length === 0) return
36
+
37
+ // Find the first fully-formed response: consecutive lines
38
+ // sharing a 3-digit code, where "CODE-" continues and "CODE "
39
+ // ends the response.
40
+ let consumedLines = 0
41
+ let done = false
42
+ for (const line of complete) {
43
+ consumedLines++
44
+ if (/^\d{3} /.test(line)) {
45
+ done = true
46
+ break
47
+ }
48
+ if (!/^\d{3}-/.test(line)) {
49
+ // Malformed line — bail and let the caller see the raw text.
50
+ done = true
51
+ break
52
+ }
53
+ }
54
+
55
+ if (!done) return // waiting for more data to complete this response
56
+
57
+ const responseLines = complete.slice(0, consumedLines)
58
+ this.buffer = [...complete.slice(consumedLines), lines.at(-1)].join(
59
+ '\r\n',
60
+ )
61
+
62
+ const waiter = this.pending.shift()
63
+ if (waiter) waiter.resolve(responseLines.join('\r\n'))
64
+ if (this.pending.length === 0) return
65
+ }
66
+ }
67
+
68
+ read(timeoutMs = DEFAULT_TIMEOUT_MS) {
69
+ return new Promise((resolve, reject) => {
70
+ const timer = setTimeout(() => {
71
+ const idx = this.pending.indexOf(entry)
72
+ if (idx !== -1) this.pending.splice(idx, 1)
73
+ reject(new Error(`SMTP response timed out after ${timeoutMs}ms`))
74
+ }, timeoutMs)
75
+
76
+ const entry = {
77
+ resolve: (line) => {
78
+ clearTimeout(timer)
79
+ resolve(line)
80
+ },
81
+ reject,
82
+ }
83
+ this.pending.push(entry)
84
+ this.flush()
85
+ })
86
+ }
87
+
88
+ rejectAll(err) {
89
+ for (const waiter of this.pending) waiter.reject(err)
90
+ this.pending = []
91
+ }
92
+
93
+ detach() {
94
+ this.socket.off('data', this.onData)
95
+ this.socket.off('error', this.onError)
96
+ }
97
+ }
98
+
99
+ function writeCommand(socket, command) {
100
+ socket.write(`${command}\r\n`)
101
+ }
102
+
103
+ function checkCode(response, expected) {
104
+ const code = Number(response.slice(0, 3))
105
+ if (!expected.includes(code)) {
106
+ throw new Error(
107
+ `SMTP error: expected ${expected.join('/')}, got: ${response.trim()}`,
108
+ )
109
+ }
110
+ return response
111
+ }
112
+
113
+ function connectSocket(options, timeoutMs) {
114
+ return new Promise((resolve, reject) => {
115
+ const socket = options.secure
116
+ ? tls.connect({ host: options.host, port: options.port })
117
+ : net.connect({ host: options.host, port: options.port })
118
+
119
+ const timer = setTimeout(() => {
120
+ socket.destroy()
121
+ reject(
122
+ new Error(`Connection to ${options.host}:${options.port} timed out`),
123
+ )
124
+ }, timeoutMs)
125
+
126
+ socket.once('connect', () => {
127
+ clearTimeout(timer)
128
+ resolve(socket)
129
+ })
130
+ socket.once('secureConnect', () => {
131
+ clearTimeout(timer)
132
+ resolve(socket)
133
+ })
134
+ socket.once('error', (err) => {
135
+ clearTimeout(timer)
136
+ reject(err)
137
+ })
138
+ })
139
+ }
140
+
141
+ // --- Message building helpers -------------------------------------------
142
+
143
+ // Any CR or LF in a header value would let the caller add headers of
144
+ // their own (or extra SMTP commands, for the envelope addresses).
145
+ function assertNoLineBreaks(value, label) {
146
+ if (typeof value !== 'string' || /[\r\n]/.test(value)) {
147
+ throw new Error(`Invalid ${label}: line breaks are not allowed`)
148
+ }
149
+ return value
150
+ }
151
+
152
+ // Envelope and header addresses must be a plain "user@host". This is
153
+ // also what MAIL FROM:<...> / RCPT TO:<...> require.
154
+ function assertAddress(value, label) {
155
+ assertNoLineBreaks(value, label)
156
+ if (!value.includes('@') || /[<>\s]/.test(value)) {
157
+ throw new Error(`Invalid ${label}: expected a plain email address`)
158
+ }
159
+ return value
160
+ }
161
+
162
+ // RFC 2047: non-ASCII header text is sent as encoded words. Each word
163
+ // stays under the 75-character limit, and multi-byte characters are
164
+ // never split across words.
165
+ function encodeHeaderValue(value) {
166
+ assertNoLineBreaks(value, 'header value')
167
+ if (/^[\x20-\x7e]*$/.test(value)) return value
168
+
169
+ const words = []
170
+ let chunk = ''
171
+ let bytes = 0
172
+ for (const ch of value) {
173
+ const size = Buffer.byteLength(ch)
174
+ if (bytes + size > 45) {
175
+ words.push(chunk)
176
+ chunk = ''
177
+ bytes = 0
178
+ }
179
+ chunk += ch
180
+ bytes += size
181
+ }
182
+ if (chunk) words.push(chunk)
183
+
184
+ return words
185
+ .map((w) => `=?UTF-8?B?${Buffer.from(w).toString('base64')}?=`)
186
+ .join('\r\n ')
187
+ }
188
+
189
+ // Base64 body parts need no line-ending normalisation or dot-stuffing:
190
+ // the encoded text only has A-Z a-z 0-9 + / = and is wrapped at 76.
191
+ function base64Lines(value) {
192
+ const encoded = Buffer.from(value, 'utf-8').toString('base64')
193
+ return (encoded.match(/.{1,76}/g) ?? []).join('\r\n')
194
+ }
195
+
196
+ // Rough plain-text fallback so the text/plain part is never empty.
197
+ function htmlToText(html) {
198
+ return html
199
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
200
+ .replace(/<br\s*\/?>|<\/p>|<\/div>|<\/h[1-6]>/gi, '\n')
201
+ .replace(/<[^>]+>/g, '')
202
+ .replace(/&nbsp;/g, ' ')
203
+ .replace(/&amp;/g, '&')
204
+ .replace(/\n{3,}/g, '\n\n')
205
+ .trim()
206
+ }
207
+
208
+ function buildMessage({ from, recipients, subject, html, text }) {
209
+ const boundary = `tylix-${crypto.randomBytes(12).toString('hex')}`
210
+ const domain = from.split('@')[1]
211
+ // RFC 5322 date, with a numeric zone instead of "GMT".
212
+ const date = new Date().toUTCString().replace('GMT', '+0000')
213
+
214
+ const plain = text || htmlToText(html || '')
215
+
216
+ const message = [
217
+ `From: ${from}`,
218
+ `To: ${recipients.join(', ')}`,
219
+ `Subject: ${encodeHeaderValue(subject)}`,
220
+ `Date: ${date}`,
221
+ `Message-ID: <${crypto.randomUUID()}@${domain}>`,
222
+ 'MIME-Version: 1.0',
223
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
224
+ '',
225
+ `--${boundary}`,
226
+ 'Content-Type: text/plain; charset=utf-8',
227
+ 'Content-Transfer-Encoding: base64',
228
+ '',
229
+ base64Lines(plain),
230
+ `--${boundary}`,
231
+ 'Content-Type: text/html; charset=utf-8',
232
+ 'Content-Transfer-Encoding: base64',
233
+ '',
234
+ base64Lines(html || ''),
235
+ `--${boundary}--`,
236
+ ].join('\r\n')
237
+
238
+ // Dot-stuffing per RFC 5321, then the terminator. Nothing in the
239
+ // message above can start a line with "." today, but this keeps it
240
+ // safe if a part is ever sent unencoded.
241
+ return `${message.replace(/(^|\r\n)\./g, '$1..')}\r\n.`
242
+ }
243
+
244
+ // --- Client ----------------------------------------------------------------
245
+
246
+ export class SmtpClient {
247
+ constructor({
248
+ host,
249
+ port,
250
+ secure = false,
251
+ user,
252
+ password,
253
+ // Name announced in EHLO. Must identify THIS machine or app, not the
254
+ // server, which some servers reject. "localhost" is accepted by
255
+ // nearly all of them; set it to your app's hostname for production.
256
+ clientName = 'localhost',
257
+ timeoutMs = DEFAULT_TIMEOUT_MS,
258
+ }) {
259
+ this.host = host
260
+ this.port = port
261
+ this.secure = secure
262
+ this.user = user
263
+ this.password = password
264
+ this.clientName = clientName
265
+ this.timeoutMs = timeoutMs
266
+ }
267
+
268
+ async connect() {
269
+ this.socket = await connectSocket(
270
+ { host: this.host, port: this.port, secure: this.secure },
271
+ this.timeoutMs,
272
+ )
273
+ this.reader = new SmtpResponseReader(this.socket)
274
+
275
+ checkCode(await this.reader.read(this.timeoutMs), [220])
276
+ writeCommand(this.socket, `EHLO ${this.clientName}`)
277
+ checkCode(await this.reader.read(this.timeoutMs), [250])
278
+
279
+ if (!this.secure && this.port === 587) {
280
+ writeCommand(this.socket, 'STARTTLS')
281
+ checkCode(await this.reader.read(this.timeoutMs), [220])
282
+
283
+ this.reader.detach()
284
+ this.socket = await new Promise((resolve, reject) => {
285
+ // servername is needed so the certificate is checked against
286
+ // the real host name (and so SNI is sent).
287
+ const tlsSocket = tls.connect({
288
+ socket: this.socket,
289
+ servername: this.host,
290
+ })
291
+ const timer = setTimeout(() => {
292
+ tlsSocket.destroy()
293
+ reject(new Error('STARTTLS upgrade timed out'))
294
+ }, this.timeoutMs)
295
+ tlsSocket.once('secureConnect', () => {
296
+ clearTimeout(timer)
297
+ resolve(tlsSocket)
298
+ })
299
+ tlsSocket.once('error', (err) => {
300
+ clearTimeout(timer)
301
+ reject(err)
302
+ })
303
+ })
304
+ this.reader = new SmtpResponseReader(this.socket)
305
+
306
+ writeCommand(this.socket, `EHLO ${this.clientName}`)
307
+ checkCode(await this.reader.read(this.timeoutMs), [250])
308
+ }
309
+
310
+ if (this.user && this.password) {
311
+ writeCommand(this.socket, 'AUTH LOGIN')
312
+ checkCode(await this.reader.read(this.timeoutMs), [334])
313
+ writeCommand(this.socket, Buffer.from(this.user).toString('base64'))
314
+ checkCode(await this.reader.read(this.timeoutMs), [334])
315
+ writeCommand(this.socket, Buffer.from(this.password).toString('base64'))
316
+ checkCode(await this.reader.read(this.timeoutMs), [235])
317
+ }
318
+ }
319
+
320
+ async send({ from, to, subject, html, text }) {
321
+ // Validate everything before opening a connection.
322
+ assertAddress(from, 'from address')
323
+ const recipients = (Array.isArray(to) ? to : [to]).map((r) =>
324
+ assertAddress(r, 'recipient address'),
325
+ )
326
+ assertNoLineBreaks(subject ?? '', 'subject')
327
+
328
+ const message = buildMessage({
329
+ from,
330
+ recipients,
331
+ subject: subject ?? '',
332
+ html,
333
+ text,
334
+ })
335
+
336
+ try {
337
+ await this.connect()
338
+
339
+ writeCommand(this.socket, `MAIL FROM:<${from}>`)
340
+ checkCode(await this.reader.read(this.timeoutMs), [250])
341
+
342
+ for (const recipient of recipients) {
343
+ writeCommand(this.socket, `RCPT TO:<${recipient}>`)
344
+ checkCode(await this.reader.read(this.timeoutMs), [250, 251])
345
+ }
346
+
347
+ writeCommand(this.socket, 'DATA')
348
+ checkCode(await this.reader.read(this.timeoutMs), [354])
349
+
350
+ writeCommand(this.socket, message)
351
+ checkCode(await this.reader.read(this.timeoutMs), [250])
352
+
353
+ writeCommand(this.socket, 'QUIT')
354
+ // Give the server a moment to acknowledge before the socket closes.
355
+ // The message is already accepted, so a missing reply is not an error.
356
+ await this.reader.read(2000).catch(() => {})
357
+ } finally {
358
+ this.reader?.detach()
359
+ this.socket?.end()
360
+ }
361
+ }
362
+ }
@@ -6,13 +6,14 @@ export class SmtpDriver {
6
6
  }
7
7
 
8
8
  async deliver({ to, subject, html, text }) {
9
- const client = new SmtpClient({
10
- host: this.config.host,
11
- port: this.config.port,
12
- secure: this.config.secure,
13
- user: this.config.user,
14
- password: this.config.password,
15
- })
9
+ const client = new SmtpClient({
10
+ host: this.config.host,
11
+ port: this.config.port,
12
+ secure: this.config.secure,
13
+ user: this.config.user,
14
+ password: this.config.password,
15
+ clientName: this.config.clientName,
16
+ })
16
17
  await client.send({ from: this.config.from, to, subject, html, text })
17
18
  return { status: 'sent' }
18
19
  }
package/index.d.ts CHANGED
@@ -1,34 +1,57 @@
1
1
  import { Model } from '@tylix/orm'
2
2
 
3
- export interface MailContent {
4
- subject: string
5
- view: string
6
- data?: Record<string, unknown>
7
- }
8
-
9
3
  export interface MailConfig {
4
+ /** Anything other than "smtp" falls back to the log driver. */
10
5
  driver?: 'smtp' | 'log'
6
+ /** Sender address. Required for the smtp driver. */
7
+ from?: string
11
8
  host?: string
12
9
  port?: number
10
+ /** true = implicit TLS (port 465). Port 587 upgrades with STARTTLS. */
11
+ secure?: boolean
13
12
  user?: string
14
13
  password?: string
15
- from?: string
16
- [key: string]: unknown
14
+ /** Name announced in EHLO. Defaults to "localhost". */
15
+ clientName?: string
16
+ }
17
+
18
+ export interface MailContent {
19
+ subject: string
20
+ /** Name of an HTML file in resources/mail/, without the extension. */
21
+ view?: string
22
+ /** Values rendered into the view template. */
23
+ data?: Record<string, unknown>
24
+ }
25
+
26
+ export interface SendMailOptions extends MailContent {
27
+ to: string | string[]
28
+ }
29
+
30
+ export interface DeliveryResult {
31
+ status: 'sent' | 'captured'
32
+ }
33
+
34
+ export class Mail {
35
+ static send(options: SendMailOptions, config: MailConfig): Promise<DeliveryResult>
17
36
  }
18
37
 
19
38
  export abstract class Mailable {
20
39
  abstract build(): MailContent
21
- send(to: string, config?: MailConfig): Promise<unknown>
40
+ send(to: string | string[], config: MailConfig): Promise<DeliveryResult>
22
41
  }
23
42
 
24
43
  export class MailLog extends Model {
44
+ static table: string
45
+ static fillable: string[]
46
+ static recent(limit?: number): Promise<MailLog[]>
47
+
25
48
  id: number
26
49
  recipient: string
27
50
  subject: string
28
51
  body: string
52
+ driver: string
53
+ status: string
54
+ error?: string | null
29
55
  created_at?: string
30
- }
31
-
32
- export const Mail: {
33
- send(to: string, mailable: Mailable, config?: MailConfig): Promise<unknown>
56
+ updated_at?: string
34
57
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tylix/mail",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Mail system for Tylix: Mailables, SMTP and log drivers, and mail logging",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -24,13 +24,14 @@
24
24
  "Mailer.js",
25
25
  "Mailable.js",
26
26
  "models",
27
- "drivers"
27
+ "drivers",
28
+ "SmtpClient.js"
28
29
  ],
29
30
  "dependencies": {
30
- "@tylix/shared": "^0.4.0"
31
+ "@tylix/shared": "^0.5.0"
31
32
  },
32
33
  "peerDependencies": {
33
- "@tylix/orm": "^0.4.0"
34
+ "@tylix/orm": "^0.5.0"
34
35
  },
35
36
  "publishConfig": {
36
37
  "access": "public"