@tylix/mail 0.4.1 → 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 +17 -5
- package/SmtpClient.js +139 -26
- package/drivers/SmtpDriver.js +8 -7
- package/index.d.ts +36 -13
- package/package.json +3 -3
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
|
|
35
|
-
recipient:
|
|
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
|
|
45
|
-
recipient:
|
|
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
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import net from 'node:net'
|
|
2
2
|
import tls from 'node:tls'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
3
4
|
|
|
4
5
|
const DEFAULT_TIMEOUT_MS = 10_000
|
|
5
6
|
|
|
@@ -137,6 +138,111 @@ function connectSocket(options, timeoutMs) {
|
|
|
137
138
|
})
|
|
138
139
|
}
|
|
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(/ /g, ' ')
|
|
203
|
+
.replace(/&/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
|
+
|
|
140
246
|
export class SmtpClient {
|
|
141
247
|
constructor({
|
|
142
248
|
host,
|
|
@@ -144,6 +250,10 @@ export class SmtpClient {
|
|
|
144
250
|
secure = false,
|
|
145
251
|
user,
|
|
146
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',
|
|
147
257
|
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
148
258
|
}) {
|
|
149
259
|
this.host = host
|
|
@@ -151,6 +261,7 @@ export class SmtpClient {
|
|
|
151
261
|
this.secure = secure
|
|
152
262
|
this.user = user
|
|
153
263
|
this.password = password
|
|
264
|
+
this.clientName = clientName
|
|
154
265
|
this.timeoutMs = timeoutMs
|
|
155
266
|
}
|
|
156
267
|
|
|
@@ -162,7 +273,7 @@ export class SmtpClient {
|
|
|
162
273
|
this.reader = new SmtpResponseReader(this.socket)
|
|
163
274
|
|
|
164
275
|
checkCode(await this.reader.read(this.timeoutMs), [220])
|
|
165
|
-
writeCommand(this.socket, `EHLO ${this.
|
|
276
|
+
writeCommand(this.socket, `EHLO ${this.clientName}`)
|
|
166
277
|
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
167
278
|
|
|
168
279
|
if (!this.secure && this.port === 587) {
|
|
@@ -171,7 +282,12 @@ export class SmtpClient {
|
|
|
171
282
|
|
|
172
283
|
this.reader.detach()
|
|
173
284
|
this.socket = await new Promise((resolve, reject) => {
|
|
174
|
-
|
|
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
|
+
})
|
|
175
291
|
const timer = setTimeout(() => {
|
|
176
292
|
tlsSocket.destroy()
|
|
177
293
|
reject(new Error('STARTTLS upgrade timed out'))
|
|
@@ -187,7 +303,7 @@ export class SmtpClient {
|
|
|
187
303
|
})
|
|
188
304
|
this.reader = new SmtpResponseReader(this.socket)
|
|
189
305
|
|
|
190
|
-
writeCommand(this.socket, `EHLO ${this.
|
|
306
|
+
writeCommand(this.socket, `EHLO ${this.clientName}`)
|
|
191
307
|
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
192
308
|
}
|
|
193
309
|
|
|
@@ -202,13 +318,27 @@ export class SmtpClient {
|
|
|
202
318
|
}
|
|
203
319
|
|
|
204
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
|
+
|
|
205
336
|
try {
|
|
206
337
|
await this.connect()
|
|
207
338
|
|
|
208
339
|
writeCommand(this.socket, `MAIL FROM:<${from}>`)
|
|
209
340
|
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
210
341
|
|
|
211
|
-
const recipients = Array.isArray(to) ? to : [to]
|
|
212
342
|
for (const recipient of recipients) {
|
|
213
343
|
writeCommand(this.socket, `RCPT TO:<${recipient}>`)
|
|
214
344
|
checkCode(await this.reader.read(this.timeoutMs), [250, 251])
|
|
@@ -217,33 +347,16 @@ export class SmtpClient {
|
|
|
217
347
|
writeCommand(this.socket, 'DATA')
|
|
218
348
|
checkCode(await this.reader.read(this.timeoutMs), [354])
|
|
219
349
|
|
|
220
|
-
|
|
221
|
-
const body = [
|
|
222
|
-
`From: ${from}`,
|
|
223
|
-
`To: ${recipients.join(', ')}`,
|
|
224
|
-
`Subject: ${subject}`,
|
|
225
|
-
'MIME-Version: 1.0',
|
|
226
|
-
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
|
227
|
-
'',
|
|
228
|
-
`--${boundary}`,
|
|
229
|
-
'Content-Type: text/plain; charset=utf-8',
|
|
230
|
-
'',
|
|
231
|
-
(text || '').replace(/^\./gm, '..'), // dot-stuffing per RFC 5321
|
|
232
|
-
`--${boundary}`,
|
|
233
|
-
'Content-Type: text/html; charset=utf-8',
|
|
234
|
-
'',
|
|
235
|
-
(html || '').replace(/^\./gm, '..'),
|
|
236
|
-
`--${boundary}--`,
|
|
237
|
-
'.',
|
|
238
|
-
].join('\r\n')
|
|
239
|
-
|
|
240
|
-
writeCommand(this.socket, body)
|
|
350
|
+
writeCommand(this.socket, message)
|
|
241
351
|
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
242
352
|
|
|
243
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(() => {})
|
|
244
357
|
} finally {
|
|
245
358
|
this.reader?.detach()
|
|
246
359
|
this.socket?.end()
|
|
247
360
|
}
|
|
248
361
|
}
|
|
249
|
-
}
|
|
362
|
+
}
|
package/drivers/SmtpDriver.js
CHANGED
|
@@ -6,13 +6,14 @@ export class SmtpDriver {
|
|
|
6
6
|
}
|
|
7
7
|
|
|
8
8
|
async deliver({ to, subject, html, text }) {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
|
|
16
|
-
|
|
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
|
|
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.
|
|
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": [
|
|
@@ -28,10 +28,10 @@
|
|
|
28
28
|
"SmtpClient.js"
|
|
29
29
|
],
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@tylix/shared": "^0.
|
|
31
|
+
"@tylix/shared": "^0.5.0"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
|
-
"@tylix/orm": "^0.
|
|
34
|
+
"@tylix/orm": "^0.5.0"
|
|
35
35
|
},
|
|
36
36
|
"publishConfig": {
|
|
37
37
|
"access": "public"
|