@nocobase/plugin-workflow-mailer 1.2.13-alpha → 1.3.0-alpha.20240710084543

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.
Files changed (57) hide show
  1. package/package.json +2 -2
  2. package/dist/client/MailerInstruction.d.ts +0 -352
  3. package/dist/client/index.d.ts +0 -14
  4. package/dist/client/index.js +0 -16
  5. package/dist/externalVersion.js +0 -16
  6. package/dist/index.d.ts +0 -10
  7. package/dist/index.js +0 -48
  8. package/dist/locale/en-US.json +0 -19
  9. package/dist/locale/index.d.ts +0 -11
  10. package/dist/locale/index.js +0 -48
  11. package/dist/locale/zh-CN.json +0 -19
  12. package/dist/node_modules/nodemailer/.gitattributes +0 -6
  13. package/dist/node_modules/nodemailer/.ncurc.js +0 -7
  14. package/dist/node_modules/nodemailer/.prettierrc.js +0 -8
  15. package/dist/node_modules/nodemailer/LICENSE +0 -16
  16. package/dist/node_modules/nodemailer/SECURITY.txt +0 -22
  17. package/dist/node_modules/nodemailer/lib/addressparser/index.js +0 -313
  18. package/dist/node_modules/nodemailer/lib/base64/index.js +0 -142
  19. package/dist/node_modules/nodemailer/lib/dkim/index.js +0 -251
  20. package/dist/node_modules/nodemailer/lib/dkim/message-parser.js +0 -155
  21. package/dist/node_modules/nodemailer/lib/dkim/relaxed-body.js +0 -154
  22. package/dist/node_modules/nodemailer/lib/dkim/sign.js +0 -117
  23. package/dist/node_modules/nodemailer/lib/fetch/cookies.js +0 -281
  24. package/dist/node_modules/nodemailer/lib/fetch/index.js +0 -274
  25. package/dist/node_modules/nodemailer/lib/json-transport/index.js +0 -82
  26. package/dist/node_modules/nodemailer/lib/mail-composer/index.js +0 -565
  27. package/dist/node_modules/nodemailer/lib/mailer/index.js +0 -429
  28. package/dist/node_modules/nodemailer/lib/mailer/mail-message.js +0 -315
  29. package/dist/node_modules/nodemailer/lib/mime-funcs/index.js +0 -625
  30. package/dist/node_modules/nodemailer/lib/mime-funcs/mime-types.js +0 -2102
  31. package/dist/node_modules/nodemailer/lib/mime-node/index.js +0 -1314
  32. package/dist/node_modules/nodemailer/lib/mime-node/last-newline.js +0 -33
  33. package/dist/node_modules/nodemailer/lib/mime-node/le-unix.js +0 -43
  34. package/dist/node_modules/nodemailer/lib/mime-node/le-windows.js +0 -52
  35. package/dist/node_modules/nodemailer/lib/nodemailer.js +0 -1
  36. package/dist/node_modules/nodemailer/lib/punycode/index.js +0 -460
  37. package/dist/node_modules/nodemailer/lib/qp/index.js +0 -219
  38. package/dist/node_modules/nodemailer/lib/sendmail-transport/index.js +0 -210
  39. package/dist/node_modules/nodemailer/lib/ses-transport/index.js +0 -349
  40. package/dist/node_modules/nodemailer/lib/shared/index.js +0 -688
  41. package/dist/node_modules/nodemailer/lib/smtp-connection/data-stream.js +0 -108
  42. package/dist/node_modules/nodemailer/lib/smtp-connection/http-proxy-client.js +0 -143
  43. package/dist/node_modules/nodemailer/lib/smtp-connection/index.js +0 -1825
  44. package/dist/node_modules/nodemailer/lib/smtp-pool/index.js +0 -648
  45. package/dist/node_modules/nodemailer/lib/smtp-pool/pool-resource.js +0 -253
  46. package/dist/node_modules/nodemailer/lib/smtp-transport/index.js +0 -416
  47. package/dist/node_modules/nodemailer/lib/stream-transport/index.js +0 -135
  48. package/dist/node_modules/nodemailer/lib/well-known/index.js +0 -47
  49. package/dist/node_modules/nodemailer/lib/well-known/services.json +0 -343
  50. package/dist/node_modules/nodemailer/lib/xoauth2/index.js +0 -376
  51. package/dist/node_modules/nodemailer/package.json +0 -1
  52. package/dist/server/MailerInstruction.d.ts +0 -13
  53. package/dist/server/MailerInstruction.js +0 -119
  54. package/dist/server/Plugin.d.ts +0 -12
  55. package/dist/server/Plugin.js +0 -50
  56. package/dist/server/index.d.ts +0 -9
  57. package/dist/server/index.js +0 -42
@@ -1,1825 +0,0 @@
1
- 'use strict';
2
-
3
- const packageInfo = require('../../package.json');
4
- const EventEmitter = require('events').EventEmitter;
5
- const net = require('net');
6
- const tls = require('tls');
7
- const os = require('os');
8
- const crypto = require('crypto');
9
- const DataStream = require('./data-stream');
10
- const PassThrough = require('stream').PassThrough;
11
- const shared = require('../shared');
12
-
13
- // default timeout values in ms
14
- const CONNECTION_TIMEOUT = 2 * 60 * 1000; // how much to wait for the connection to be established
15
- const SOCKET_TIMEOUT = 10 * 60 * 1000; // how much to wait for socket inactivity before disconnecting the client
16
- const GREETING_TIMEOUT = 30 * 1000; // how much to wait after connection is established but SMTP greeting is not receieved
17
- const DNS_TIMEOUT = 30 * 1000; // how much to wait for resolveHostname
18
-
19
- /**
20
- * Generates a SMTP connection object
21
- *
22
- * Optional options object takes the following possible properties:
23
- *
24
- * * **port** - is the port to connect to (defaults to 587 or 465)
25
- * * **host** - is the hostname or IP address to connect to (defaults to 'localhost')
26
- * * **secure** - use SSL
27
- * * **ignoreTLS** - ignore server support for STARTTLS
28
- * * **requireTLS** - forces the client to use STARTTLS
29
- * * **name** - the name of the client server
30
- * * **localAddress** - outbound address to bind to (see: http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener)
31
- * * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 10000)
32
- * * **connectionTimeout** - how many milliseconds to wait for the connection to establish
33
- * * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 1 hour)
34
- * * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds)
35
- * * **lmtp** - if true, uses LMTP instead of SMTP protocol
36
- * * **logger** - bunyan compatible logger interface
37
- * * **debug** - if true pass SMTP traffic to the logger
38
- * * **tls** - options for createCredentials
39
- * * **socket** - existing socket to use instead of creating a new one (see: http://nodejs.org/api/net.html#net_class_net_socket)
40
- * * **secured** - boolean indicates that the provided socket has already been upgraded to tls
41
- *
42
- * @constructor
43
- * @namespace SMTP Client module
44
- * @param {Object} [options] Option properties
45
- */
46
- class SMTPConnection extends EventEmitter {
47
- constructor(options) {
48
- super(options);
49
-
50
- this.id = crypto.randomBytes(8).toString('base64').replace(/\W/g, '');
51
- this.stage = 'init';
52
-
53
- this.options = options || {};
54
-
55
- this.secureConnection = !!this.options.secure;
56
- this.alreadySecured = !!this.options.secured;
57
-
58
- this.port = Number(this.options.port) || (this.secureConnection ? 465 : 587);
59
- this.host = this.options.host || 'localhost';
60
-
61
- this.servername = this.options.servername ? this.options.servername : !net.isIP(this.host) ? this.host : false;
62
-
63
- this.allowInternalNetworkInterfaces = this.options.allowInternalNetworkInterfaces || false;
64
-
65
- if (typeof this.options.secure === 'undefined' && this.port === 465) {
66
- // if secure option is not set but port is 465, then default to secure
67
- this.secureConnection = true;
68
- }
69
-
70
- this.name = this.options.name || this._getHostname();
71
-
72
- this.logger = shared.getLogger(this.options, {
73
- component: this.options.component || 'smtp-connection',
74
- sid: this.id
75
- });
76
-
77
- this.customAuth = new Map();
78
- Object.keys(this.options.customAuth || {}).forEach(key => {
79
- let mapKey = (key || '').toString().trim().toUpperCase();
80
- if (!mapKey) {
81
- return;
82
- }
83
- this.customAuth.set(mapKey, this.options.customAuth[key]);
84
- });
85
-
86
- /**
87
- * Expose version nr, just for the reference
88
- * @type {String}
89
- */
90
- this.version = packageInfo.version;
91
-
92
- /**
93
- * If true, then the user is authenticated
94
- * @type {Boolean}
95
- */
96
- this.authenticated = false;
97
-
98
- /**
99
- * If set to true, this instance is no longer active
100
- * @private
101
- */
102
- this.destroyed = false;
103
-
104
- /**
105
- * Defines if the current connection is secure or not. If not,
106
- * STARTTLS can be used if available
107
- * @private
108
- */
109
- this.secure = !!this.secureConnection;
110
-
111
- /**
112
- * Store incomplete messages coming from the server
113
- * @private
114
- */
115
- this._remainder = '';
116
-
117
- /**
118
- * Unprocessed responses from the server
119
- * @type {Array}
120
- */
121
- this._responseQueue = [];
122
-
123
- this.lastServerResponse = false;
124
-
125
- /**
126
- * The socket connecting to the server
127
- * @publick
128
- */
129
- this._socket = false;
130
-
131
- /**
132
- * Lists supported auth mechanisms
133
- * @private
134
- */
135
- this._supportedAuth = [];
136
-
137
- /**
138
- * Set to true, if EHLO response includes "AUTH".
139
- * If false then authentication is not tried
140
- */
141
- this.allowsAuth = false;
142
-
143
- /**
144
- * Includes current envelope (from, to)
145
- * @private
146
- */
147
- this._envelope = false;
148
-
149
- /**
150
- * Lists supported extensions
151
- * @private
152
- */
153
- this._supportedExtensions = [];
154
-
155
- /**
156
- * Defines the maximum allowed size for a single message
157
- * @private
158
- */
159
- this._maxAllowedSize = 0;
160
-
161
- /**
162
- * Function queue to run if a data chunk comes from the server
163
- * @private
164
- */
165
- this._responseActions = [];
166
- this._recipientQueue = [];
167
-
168
- /**
169
- * Timeout variable for waiting the greeting
170
- * @private
171
- */
172
- this._greetingTimeout = false;
173
-
174
- /**
175
- * Timeout variable for waiting the connection to start
176
- * @private
177
- */
178
- this._connectionTimeout = false;
179
-
180
- /**
181
- * If the socket is deemed already closed
182
- * @private
183
- */
184
- this._destroyed = false;
185
-
186
- /**
187
- * If the socket is already being closed
188
- * @private
189
- */
190
- this._closing = false;
191
-
192
- /**
193
- * Callbacks for socket's listeners
194
- */
195
- this._onSocketData = chunk => this._onData(chunk);
196
- this._onSocketError = error => this._onError(error, 'ESOCKET', false, 'CONN');
197
- this._onSocketClose = () => this._onClose();
198
- this._onSocketEnd = () => this._onEnd();
199
- this._onSocketTimeout = () => this._onTimeout();
200
- }
201
-
202
- /**
203
- * Creates a connection to a SMTP server and sets up connection
204
- * listener
205
- */
206
- connect(connectCallback) {
207
- if (typeof connectCallback === 'function') {
208
- this.once('connect', () => {
209
- this.logger.debug(
210
- {
211
- tnx: 'smtp'
212
- },
213
- 'SMTP handshake finished'
214
- );
215
- connectCallback();
216
- });
217
-
218
- const isDestroyedMessage = this._isDestroyedMessage('connect');
219
- if (isDestroyedMessage) {
220
- return connectCallback(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'CONN'));
221
- }
222
- }
223
-
224
- let opts = {
225
- port: this.port,
226
- host: this.host,
227
- allowInternalNetworkInterfaces: this.allowInternalNetworkInterfaces,
228
- timeout: this.options.dnsTimeout || DNS_TIMEOUT
229
- };
230
-
231
- if (this.options.localAddress) {
232
- opts.localAddress = this.options.localAddress;
233
- }
234
-
235
- let setupConnectionHandlers = () => {
236
- this._connectionTimeout = setTimeout(() => {
237
- this._onError('Connection timeout', 'ETIMEDOUT', false, 'CONN');
238
- }, this.options.connectionTimeout || CONNECTION_TIMEOUT);
239
-
240
- this._socket.on('error', this._onSocketError);
241
- };
242
-
243
- if (this.options.connection) {
244
- // connection is already opened
245
- this._socket = this.options.connection;
246
- if (this.secureConnection && !this.alreadySecured) {
247
- setImmediate(() =>
248
- this._upgradeConnection(err => {
249
- if (err) {
250
- this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'CONN');
251
- return;
252
- }
253
- this._onConnect();
254
- })
255
- );
256
- } else {
257
- setImmediate(() => this._onConnect());
258
- }
259
- return;
260
- } else if (this.options.socket) {
261
- // socket object is set up but not yet connected
262
- this._socket = this.options.socket;
263
- return shared.resolveHostname(opts, (err, resolved) => {
264
- if (err) {
265
- return setImmediate(() => this._onError(err, 'EDNS', false, 'CONN'));
266
- }
267
- this.logger.debug(
268
- {
269
- tnx: 'dns',
270
- source: opts.host,
271
- resolved: resolved.host,
272
- cached: !!resolved.cached
273
- },
274
- 'Resolved %s as %s [cache %s]',
275
- opts.host,
276
- resolved.host,
277
- resolved.cached ? 'hit' : 'miss'
278
- );
279
- Object.keys(resolved).forEach(key => {
280
- if (key.charAt(0) !== '_' && resolved[key]) {
281
- opts[key] = resolved[key];
282
- }
283
- });
284
- try {
285
- this._socket.connect(this.port, this.host, () => {
286
- this._socket.setKeepAlive(true);
287
- this._onConnect();
288
- });
289
- setupConnectionHandlers();
290
- } catch (E) {
291
- return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN'));
292
- }
293
- });
294
- } else if (this.secureConnection) {
295
- // connect using tls
296
- if (this.options.tls) {
297
- Object.keys(this.options.tls).forEach(key => {
298
- opts[key] = this.options.tls[key];
299
- });
300
- }
301
-
302
- // ensure servername for SNI
303
- if (this.servername && !opts.servername) {
304
- opts.servername = this.servername;
305
- }
306
-
307
- return shared.resolveHostname(opts, (err, resolved) => {
308
- if (err) {
309
- return setImmediate(() => this._onError(err, 'EDNS', false, 'CONN'));
310
- }
311
- this.logger.debug(
312
- {
313
- tnx: 'dns',
314
- source: opts.host,
315
- resolved: resolved.host,
316
- cached: !!resolved.cached
317
- },
318
- 'Resolved %s as %s [cache %s]',
319
- opts.host,
320
- resolved.host,
321
- resolved.cached ? 'hit' : 'miss'
322
- );
323
- Object.keys(resolved).forEach(key => {
324
- if (key.charAt(0) !== '_' && resolved[key]) {
325
- opts[key] = resolved[key];
326
- }
327
- });
328
- try {
329
- this._socket = tls.connect(opts, () => {
330
- this._socket.setKeepAlive(true);
331
- this._onConnect();
332
- });
333
- setupConnectionHandlers();
334
- } catch (E) {
335
- return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN'));
336
- }
337
- });
338
- } else {
339
- // connect using plaintext
340
- return shared.resolveHostname(opts, (err, resolved) => {
341
- if (err) {
342
- return setImmediate(() => this._onError(err, 'EDNS', false, 'CONN'));
343
- }
344
- this.logger.debug(
345
- {
346
- tnx: 'dns',
347
- source: opts.host,
348
- resolved: resolved.host,
349
- cached: !!resolved.cached
350
- },
351
- 'Resolved %s as %s [cache %s]',
352
- opts.host,
353
- resolved.host,
354
- resolved.cached ? 'hit' : 'miss'
355
- );
356
- Object.keys(resolved).forEach(key => {
357
- if (key.charAt(0) !== '_' && resolved[key]) {
358
- opts[key] = resolved[key];
359
- }
360
- });
361
- try {
362
- this._socket = net.connect(opts, () => {
363
- this._socket.setKeepAlive(true);
364
- this._onConnect();
365
- });
366
- setupConnectionHandlers();
367
- } catch (E) {
368
- return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN'));
369
- }
370
- });
371
- }
372
- }
373
-
374
- /**
375
- * Sends QUIT
376
- */
377
- quit() {
378
- this._sendCommand('QUIT');
379
- this._responseActions.push(this.close);
380
- }
381
-
382
- /**
383
- * Closes the connection to the server
384
- */
385
- close() {
386
- clearTimeout(this._connectionTimeout);
387
- clearTimeout(this._greetingTimeout);
388
- this._responseActions = [];
389
-
390
- // allow to run this function only once
391
- if (this._closing) {
392
- return;
393
- }
394
- this._closing = true;
395
-
396
- let closeMethod = 'end';
397
-
398
- if (this.stage === 'init') {
399
- // Close the socket immediately when connection timed out
400
- closeMethod = 'destroy';
401
- }
402
-
403
- this.logger.debug(
404
- {
405
- tnx: 'smtp'
406
- },
407
- 'Closing connection to the server using "%s"',
408
- closeMethod
409
- );
410
-
411
- let socket = (this._socket && this._socket.socket) || this._socket;
412
-
413
- if (socket && !socket.destroyed) {
414
- try {
415
- this._socket[closeMethod]();
416
- } catch (E) {
417
- // just ignore
418
- }
419
- }
420
-
421
- this._destroy();
422
- }
423
-
424
- /**
425
- * Authenticate user
426
- */
427
- login(authData, callback) {
428
- const isDestroyedMessage = this._isDestroyedMessage('login');
429
- if (isDestroyedMessage) {
430
- return callback(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'API'));
431
- }
432
-
433
- this._auth = authData || {};
434
- // Select SASL authentication method
435
- this._authMethod = (this._auth.method || '').toString().trim().toUpperCase() || false;
436
-
437
- if (!this._authMethod && this._auth.oauth2 && !this._auth.credentials) {
438
- this._authMethod = 'XOAUTH2';
439
- } else if (!this._authMethod || (this._authMethod === 'XOAUTH2' && !this._auth.oauth2)) {
440
- // use first supported
441
- this._authMethod = (this._supportedAuth[0] || 'PLAIN').toUpperCase().trim();
442
- }
443
-
444
- if (this._authMethod !== 'XOAUTH2' && (!this._auth.credentials || !this._auth.credentials.user || !this._auth.credentials.pass)) {
445
- if ((this._auth.user && this._auth.pass) || this.customAuth.has(this._authMethod)) {
446
- this._auth.credentials = {
447
- user: this._auth.user,
448
- pass: this._auth.pass,
449
- options: this._auth.options
450
- };
451
- } else {
452
- return callback(this._formatError('Missing credentials for "' + this._authMethod + '"', 'EAUTH', false, 'API'));
453
- }
454
- }
455
-
456
- if (this.customAuth.has(this._authMethod)) {
457
- let handler = this.customAuth.get(this._authMethod);
458
- let lastResponse;
459
- let returned = false;
460
-
461
- let resolve = () => {
462
- if (returned) {
463
- return;
464
- }
465
- returned = true;
466
- this.logger.info(
467
- {
468
- tnx: 'smtp',
469
- username: this._auth.user,
470
- action: 'authenticated',
471
- method: this._authMethod
472
- },
473
- 'User %s authenticated',
474
- JSON.stringify(this._auth.user)
475
- );
476
- this.authenticated = true;
477
- callback(null, true);
478
- };
479
-
480
- let reject = err => {
481
- if (returned) {
482
- return;
483
- }
484
- returned = true;
485
- callback(this._formatError(err, 'EAUTH', lastResponse, 'AUTH ' + this._authMethod));
486
- };
487
-
488
- let handlerResponse = handler({
489
- auth: this._auth,
490
- method: this._authMethod,
491
-
492
- extensions: [].concat(this._supportedExtensions),
493
- authMethods: [].concat(this._supportedAuth),
494
- maxAllowedSize: this._maxAllowedSize || false,
495
-
496
- sendCommand: (cmd, done) => {
497
- let promise;
498
-
499
- if (!done) {
500
- promise = new Promise((resolve, reject) => {
501
- done = shared.callbackPromise(resolve, reject);
502
- });
503
- }
504
-
505
- this._responseActions.push(str => {
506
- lastResponse = str;
507
-
508
- let codes = str.match(/^(\d+)(?:\s(\d+\.\d+\.\d+))?\s/);
509
- let data = {
510
- command: cmd,
511
- response: str
512
- };
513
- if (codes) {
514
- data.status = Number(codes[1]) || 0;
515
- if (codes[2]) {
516
- data.code = codes[2];
517
- }
518
- data.text = str.substr(codes[0].length);
519
- } else {
520
- data.text = str;
521
- data.status = 0; // just in case we need to perform numeric comparisons
522
- }
523
- done(null, data);
524
- });
525
- setImmediate(() => this._sendCommand(cmd));
526
-
527
- return promise;
528
- },
529
-
530
- resolve,
531
- reject
532
- });
533
-
534
- if (handlerResponse && typeof handlerResponse.catch === 'function') {
535
- // a promise was returned
536
- handlerResponse.then(resolve).catch(reject);
537
- }
538
-
539
- return;
540
- }
541
-
542
- switch (this._authMethod) {
543
- case 'XOAUTH2':
544
- this._handleXOauth2Token(false, callback);
545
- return;
546
- case 'LOGIN':
547
- this._responseActions.push(str => {
548
- this._actionAUTH_LOGIN_USER(str, callback);
549
- });
550
- this._sendCommand('AUTH LOGIN');
551
- return;
552
- case 'PLAIN':
553
- this._responseActions.push(str => {
554
- this._actionAUTHComplete(str, callback);
555
- });
556
- this._sendCommand(
557
- 'AUTH PLAIN ' +
558
- Buffer.from(
559
- //this._auth.user+'\u0000'+
560
- '\u0000' + // skip authorization identity as it causes problems with some servers
561
- this._auth.credentials.user +
562
- '\u0000' +
563
- this._auth.credentials.pass,
564
- 'utf-8'
565
- ).toString('base64'),
566
- // log entry without passwords
567
- 'AUTH PLAIN ' +
568
- Buffer.from(
569
- //this._auth.user+'\u0000'+
570
- '\u0000' + // skip authorization identity as it causes problems with some servers
571
- this._auth.credentials.user +
572
- '\u0000' +
573
- '/* secret */',
574
- 'utf-8'
575
- ).toString('base64')
576
- );
577
- return;
578
- case 'CRAM-MD5':
579
- this._responseActions.push(str => {
580
- this._actionAUTH_CRAM_MD5(str, callback);
581
- });
582
- this._sendCommand('AUTH CRAM-MD5');
583
- return;
584
- }
585
-
586
- return callback(this._formatError('Unknown authentication method "' + this._authMethod + '"', 'EAUTH', false, 'API'));
587
- }
588
-
589
- /**
590
- * Sends a message
591
- *
592
- * @param {Object} envelope Envelope object, {from: addr, to: [addr]}
593
- * @param {Object} message String, Buffer or a Stream
594
- * @param {Function} callback Callback to return once sending is completed
595
- */
596
- send(envelope, message, done) {
597
- if (!message) {
598
- return done(this._formatError('Empty message', 'EMESSAGE', false, 'API'));
599
- }
600
-
601
- const isDestroyedMessage = this._isDestroyedMessage('send message');
602
- if (isDestroyedMessage) {
603
- return done(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'API'));
604
- }
605
-
606
- // reject larger messages than allowed
607
- if (this._maxAllowedSize && envelope.size > this._maxAllowedSize) {
608
- return setImmediate(() => {
609
- done(this._formatError('Message size larger than allowed ' + this._maxAllowedSize, 'EMESSAGE', false, 'MAIL FROM'));
610
- });
611
- }
612
-
613
- // ensure that callback is only called once
614
- let returned = false;
615
- let callback = function () {
616
- if (returned) {
617
- return;
618
- }
619
- returned = true;
620
-
621
- done(...arguments);
622
- };
623
-
624
- if (typeof message.on === 'function') {
625
- message.on('error', err => callback(this._formatError(err, 'ESTREAM', false, 'API')));
626
- }
627
-
628
- let startTime = Date.now();
629
- this._setEnvelope(envelope, (err, info) => {
630
- if (err) {
631
- return callback(err);
632
- }
633
- let envelopeTime = Date.now();
634
- let stream = this._createSendStream((err, str) => {
635
- if (err) {
636
- return callback(err);
637
- }
638
-
639
- info.envelopeTime = envelopeTime - startTime;
640
- info.messageTime = Date.now() - envelopeTime;
641
- info.messageSize = stream.outByteCount;
642
- info.response = str;
643
-
644
- return callback(null, info);
645
- });
646
- if (typeof message.pipe === 'function') {
647
- message.pipe(stream);
648
- } else {
649
- stream.write(message);
650
- stream.end();
651
- }
652
- });
653
- }
654
-
655
- /**
656
- * Resets connection state
657
- *
658
- * @param {Function} callback Callback to return once connection is reset
659
- */
660
- reset(callback) {
661
- this._sendCommand('RSET');
662
- this._responseActions.push(str => {
663
- if (str.charAt(0) !== '2') {
664
- return callback(this._formatError('Could not reset session state. response=' + str, 'EPROTOCOL', str, 'RSET'));
665
- }
666
- this._envelope = false;
667
- return callback(null, true);
668
- });
669
- }
670
-
671
- /**
672
- * Connection listener that is run when the connection to
673
- * the server is opened
674
- *
675
- * @event
676
- */
677
- _onConnect() {
678
- clearTimeout(this._connectionTimeout);
679
-
680
- this.logger.info(
681
- {
682
- tnx: 'network',
683
- localAddress: this._socket.localAddress,
684
- localPort: this._socket.localPort,
685
- remoteAddress: this._socket.remoteAddress,
686
- remotePort: this._socket.remotePort
687
- },
688
- '%s established to %s:%s',
689
- this.secure ? 'Secure connection' : 'Connection',
690
- this._socket.remoteAddress,
691
- this._socket.remotePort
692
- );
693
-
694
- if (this._destroyed) {
695
- // Connection was established after we already had canceled it
696
- this.close();
697
- return;
698
- }
699
-
700
- this.stage = 'connected';
701
-
702
- // clear existing listeners for the socket
703
- this._socket.removeListener('data', this._onSocketData);
704
- this._socket.removeListener('timeout', this._onSocketTimeout);
705
- this._socket.removeListener('close', this._onSocketClose);
706
- this._socket.removeListener('end', this._onSocketEnd);
707
-
708
- this._socket.on('data', this._onSocketData);
709
- this._socket.once('close', this._onSocketClose);
710
- this._socket.once('end', this._onSocketEnd);
711
-
712
- this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT);
713
- this._socket.on('timeout', this._onSocketTimeout);
714
-
715
- this._greetingTimeout = setTimeout(() => {
716
- // if still waiting for greeting, give up
717
- if (this._socket && !this._destroyed && this._responseActions[0] === this._actionGreeting) {
718
- this._onError('Greeting never received', 'ETIMEDOUT', false, 'CONN');
719
- }
720
- }, this.options.greetingTimeout || GREETING_TIMEOUT);
721
-
722
- this._responseActions.push(this._actionGreeting);
723
-
724
- // we have a 'data' listener set up so resume socket if it was paused
725
- this._socket.resume();
726
- }
727
-
728
- /**
729
- * 'data' listener for data coming from the server
730
- *
731
- * @event
732
- * @param {Buffer} chunk Data chunk coming from the server
733
- */
734
- _onData(chunk) {
735
- if (this._destroyed || !chunk || !chunk.length) {
736
- return;
737
- }
738
-
739
- let data = (chunk || '').toString('binary');
740
- let lines = (this._remainder + data).split(/\r?\n/);
741
- let lastline;
742
-
743
- this._remainder = lines.pop();
744
-
745
- for (let i = 0, len = lines.length; i < len; i++) {
746
- if (this._responseQueue.length) {
747
- lastline = this._responseQueue[this._responseQueue.length - 1];
748
- if (/^\d+-/.test(lastline.split('\n').pop())) {
749
- this._responseQueue[this._responseQueue.length - 1] += '\n' + lines[i];
750
- continue;
751
- }
752
- }
753
- this._responseQueue.push(lines[i]);
754
- }
755
-
756
- if (this._responseQueue.length) {
757
- lastline = this._responseQueue[this._responseQueue.length - 1];
758
- if (/^\d+-/.test(lastline.split('\n').pop())) {
759
- return;
760
- }
761
- }
762
-
763
- this._processResponse();
764
- }
765
-
766
- /**
767
- * 'error' listener for the socket
768
- *
769
- * @event
770
- * @param {Error} err Error object
771
- * @param {String} type Error name
772
- */
773
- _onError(err, type, data, command) {
774
- clearTimeout(this._connectionTimeout);
775
- clearTimeout(this._greetingTimeout);
776
-
777
- if (this._destroyed) {
778
- // just ignore, already closed
779
- // this might happen when a socket is canceled because of reached timeout
780
- // but the socket timeout error itself receives only after
781
- return;
782
- }
783
-
784
- err = this._formatError(err, type, data, command);
785
-
786
- this.logger.error(data, err.message);
787
-
788
- this.emit('error', err);
789
- this.close();
790
- }
791
-
792
- _formatError(message, type, response, command) {
793
- let err;
794
-
795
- if (/Error\]$/i.test(Object.prototype.toString.call(message))) {
796
- err = message;
797
- } else {
798
- err = new Error(message);
799
- }
800
-
801
- if (type && type !== 'Error') {
802
- err.code = type;
803
- }
804
-
805
- if (response) {
806
- err.response = response;
807
- err.message += ': ' + response;
808
- }
809
-
810
- let responseCode = (typeof response === 'string' && Number((response.match(/^\d+/) || [])[0])) || false;
811
- if (responseCode) {
812
- err.responseCode = responseCode;
813
- }
814
-
815
- if (command) {
816
- err.command = command;
817
- }
818
-
819
- return err;
820
- }
821
-
822
- /**
823
- * 'close' listener for the socket
824
- *
825
- * @event
826
- */
827
- _onClose() {
828
- let serverResponse = false;
829
-
830
- if (this._remainder && this._remainder.trim()) {
831
- if (this.options.debug || this.options.transactionLog) {
832
- this.logger.debug(
833
- {
834
- tnx: 'server'
835
- },
836
- this._remainder.replace(/\r?\n$/, '')
837
- );
838
- }
839
- this.lastServerResponse = serverResponse = this._remainder.trim();
840
- }
841
-
842
- this.logger.info(
843
- {
844
- tnx: 'network'
845
- },
846
- 'Connection closed'
847
- );
848
-
849
- if (this.upgrading && !this._destroyed) {
850
- return this._onError(new Error('Connection closed unexpectedly'), 'ETLS', serverResponse, 'CONN');
851
- } else if (![this._actionGreeting, this.close].includes(this._responseActions[0]) && !this._destroyed) {
852
- return this._onError(new Error('Connection closed unexpectedly'), 'ECONNECTION', serverResponse, 'CONN');
853
- } else if (/^[45]\d{2}\b/.test(serverResponse)) {
854
- return this._onError(new Error('Connection closed unexpectedly'), 'ECONNECTION', serverResponse, 'CONN');
855
- }
856
-
857
- this._destroy();
858
- }
859
-
860
- /**
861
- * 'end' listener for the socket
862
- *
863
- * @event
864
- */
865
- _onEnd() {
866
- if (this._socket && !this._socket.destroyed) {
867
- this._socket.destroy();
868
- }
869
- }
870
-
871
- /**
872
- * 'timeout' listener for the socket
873
- *
874
- * @event
875
- */
876
- _onTimeout() {
877
- return this._onError(new Error('Timeout'), 'ETIMEDOUT', false, 'CONN');
878
- }
879
-
880
- /**
881
- * Destroys the client, emits 'end'
882
- */
883
- _destroy() {
884
- if (this._destroyed) {
885
- return;
886
- }
887
- this._destroyed = true;
888
- this.emit('end');
889
- }
890
-
891
- /**
892
- * Upgrades the connection to TLS
893
- *
894
- * @param {Function} callback Callback function to run when the connection
895
- * has been secured
896
- */
897
- _upgradeConnection(callback) {
898
- // do not remove all listeners or it breaks node v0.10 as there's
899
- // apparently a 'finish' event set that would be cleared as well
900
-
901
- // we can safely keep 'error', 'end', 'close' etc. events
902
- this._socket.removeListener('data', this._onSocketData); // incoming data is going to be gibberish from this point onwards
903
- this._socket.removeListener('timeout', this._onSocketTimeout); // timeout will be re-set for the new socket object
904
-
905
- let socketPlain = this._socket;
906
- let opts = {
907
- socket: this._socket,
908
- host: this.host
909
- };
910
-
911
- Object.keys(this.options.tls || {}).forEach(key => {
912
- opts[key] = this.options.tls[key];
913
- });
914
-
915
- // ensure servername for SNI
916
- if (this.servername && !opts.servername) {
917
- opts.servername = this.servername;
918
- }
919
-
920
- this.upgrading = true;
921
- // tls.connect is not an asynchronous function however it may still throw errors and requires to be wrapped with try/catch
922
- try {
923
- this._socket = tls.connect(opts, () => {
924
- this.secure = true;
925
- this.upgrading = false;
926
- this._socket.on('data', this._onSocketData);
927
-
928
- socketPlain.removeListener('close', this._onSocketClose);
929
- socketPlain.removeListener('end', this._onSocketEnd);
930
-
931
- return callback(null, true);
932
- });
933
- } catch (err) {
934
- return callback(err);
935
- }
936
-
937
- this._socket.on('error', this._onSocketError);
938
- this._socket.once('close', this._onSocketClose);
939
- this._socket.once('end', this._onSocketEnd);
940
-
941
- this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT); // 10 min.
942
- this._socket.on('timeout', this._onSocketTimeout);
943
-
944
- // resume in case the socket was paused
945
- socketPlain.resume();
946
- }
947
-
948
- /**
949
- * Processes queued responses from the server
950
- *
951
- * @param {Boolean} force If true, ignores _processing flag
952
- */
953
- _processResponse() {
954
- if (!this._responseQueue.length) {
955
- return false;
956
- }
957
-
958
- let str = (this.lastServerResponse = (this._responseQueue.shift() || '').toString());
959
-
960
- if (/^\d+-/.test(str.split('\n').pop())) {
961
- // keep waiting for the final part of multiline response
962
- return;
963
- }
964
-
965
- if (this.options.debug || this.options.transactionLog) {
966
- this.logger.debug(
967
- {
968
- tnx: 'server'
969
- },
970
- str.replace(/\r?\n$/, '')
971
- );
972
- }
973
-
974
- if (!str.trim()) {
975
- // skip unexpected empty lines
976
- setImmediate(() => this._processResponse());
977
- }
978
-
979
- let action = this._responseActions.shift();
980
-
981
- if (typeof action === 'function') {
982
- action.call(this, str);
983
- setImmediate(() => this._processResponse());
984
- } else {
985
- return this._onError(new Error('Unexpected Response'), 'EPROTOCOL', str, 'CONN');
986
- }
987
- }
988
-
989
- /**
990
- * Send a command to the server, append \r\n
991
- *
992
- * @param {String} str String to be sent to the server
993
- * @param {String} logStr Optional string to be used for logging instead of the actual string
994
- */
995
- _sendCommand(str, logStr) {
996
- if (this._destroyed) {
997
- // Connection already closed, can't send any more data
998
- return;
999
- }
1000
-
1001
- if (this._socket.destroyed) {
1002
- return this.close();
1003
- }
1004
-
1005
- if (this.options.debug || this.options.transactionLog) {
1006
- this.logger.debug(
1007
- {
1008
- tnx: 'client'
1009
- },
1010
- (logStr || str || '').toString().replace(/\r?\n$/, '')
1011
- );
1012
- }
1013
-
1014
- this._socket.write(Buffer.from(str + '\r\n', 'utf-8'));
1015
- }
1016
-
1017
- /**
1018
- * Initiates a new message by submitting envelope data, starting with
1019
- * MAIL FROM: command
1020
- *
1021
- * @param {Object} envelope Envelope object in the form of
1022
- * {from:'...', to:['...']}
1023
- * or
1024
- * {from:{address:'...',name:'...'}, to:[address:'...',name:'...']}
1025
- */
1026
- _setEnvelope(envelope, callback) {
1027
- let args = [];
1028
- let useSmtpUtf8 = false;
1029
-
1030
- this._envelope = envelope || {};
1031
- this._envelope.from = ((this._envelope.from && this._envelope.from.address) || this._envelope.from || '').toString().trim();
1032
-
1033
- this._envelope.to = [].concat(this._envelope.to || []).map(to => ((to && to.address) || to || '').toString().trim());
1034
-
1035
- if (!this._envelope.to.length) {
1036
- return callback(this._formatError('No recipients defined', 'EENVELOPE', false, 'API'));
1037
- }
1038
-
1039
- if (this._envelope.from && /[\r\n<>]/.test(this._envelope.from)) {
1040
- return callback(this._formatError('Invalid sender ' + JSON.stringify(this._envelope.from), 'EENVELOPE', false, 'API'));
1041
- }
1042
-
1043
- // check if the sender address uses only ASCII characters,
1044
- // otherwise require usage of SMTPUTF8 extension
1045
- if (/[\x80-\uFFFF]/.test(this._envelope.from)) {
1046
- useSmtpUtf8 = true;
1047
- }
1048
-
1049
- for (let i = 0, len = this._envelope.to.length; i < len; i++) {
1050
- if (!this._envelope.to[i] || /[\r\n<>]/.test(this._envelope.to[i])) {
1051
- return callback(this._formatError('Invalid recipient ' + JSON.stringify(this._envelope.to[i]), 'EENVELOPE', false, 'API'));
1052
- }
1053
-
1054
- // check if the recipients addresses use only ASCII characters,
1055
- // otherwise require usage of SMTPUTF8 extension
1056
- if (/[\x80-\uFFFF]/.test(this._envelope.to[i])) {
1057
- useSmtpUtf8 = true;
1058
- }
1059
- }
1060
-
1061
- // clone the recipients array for latter manipulation
1062
- this._envelope.rcptQueue = JSON.parse(JSON.stringify(this._envelope.to || []));
1063
- this._envelope.rejected = [];
1064
- this._envelope.rejectedErrors = [];
1065
- this._envelope.accepted = [];
1066
-
1067
- if (this._envelope.dsn) {
1068
- try {
1069
- this._envelope.dsn = this._setDsnEnvelope(this._envelope.dsn);
1070
- } catch (err) {
1071
- return callback(this._formatError('Invalid DSN ' + err.message, 'EENVELOPE', false, 'API'));
1072
- }
1073
- }
1074
-
1075
- this._responseActions.push(str => {
1076
- this._actionMAIL(str, callback);
1077
- });
1078
-
1079
- // If the server supports SMTPUTF8 and the envelope includes an internationalized
1080
- // email address then append SMTPUTF8 keyword to the MAIL FROM command
1081
- if (useSmtpUtf8 && this._supportedExtensions.includes('SMTPUTF8')) {
1082
- args.push('SMTPUTF8');
1083
- this._usingSmtpUtf8 = true;
1084
- }
1085
-
1086
- // If the server supports 8BITMIME and the message might contain non-ascii bytes
1087
- // then append the 8BITMIME keyword to the MAIL FROM command
1088
- if (this._envelope.use8BitMime && this._supportedExtensions.includes('8BITMIME')) {
1089
- args.push('BODY=8BITMIME');
1090
- this._using8BitMime = true;
1091
- }
1092
-
1093
- if (this._envelope.size && this._supportedExtensions.includes('SIZE')) {
1094
- args.push('SIZE=' + this._envelope.size);
1095
- }
1096
-
1097
- // If the server supports DSN and the envelope includes an DSN prop
1098
- // then append DSN params to the MAIL FROM command
1099
- if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) {
1100
- if (this._envelope.dsn.ret) {
1101
- args.push('RET=' + shared.encodeXText(this._envelope.dsn.ret));
1102
- }
1103
- if (this._envelope.dsn.envid) {
1104
- args.push('ENVID=' + shared.encodeXText(this._envelope.dsn.envid));
1105
- }
1106
- }
1107
-
1108
- this._sendCommand('MAIL FROM:<' + this._envelope.from + '>' + (args.length ? ' ' + args.join(' ') : ''));
1109
- }
1110
-
1111
- _setDsnEnvelope(params) {
1112
- let ret = (params.ret || params.return || '').toString().toUpperCase() || null;
1113
- if (ret) {
1114
- switch (ret) {
1115
- case 'HDRS':
1116
- case 'HEADERS':
1117
- ret = 'HDRS';
1118
- break;
1119
- case 'FULL':
1120
- case 'BODY':
1121
- ret = 'FULL';
1122
- break;
1123
- }
1124
- }
1125
-
1126
- if (ret && !['FULL', 'HDRS'].includes(ret)) {
1127
- throw new Error('ret: ' + JSON.stringify(ret));
1128
- }
1129
-
1130
- let envid = (params.envid || params.id || '').toString() || null;
1131
-
1132
- let notify = params.notify || null;
1133
- if (notify) {
1134
- if (typeof notify === 'string') {
1135
- notify = notify.split(',');
1136
- }
1137
- notify = notify.map(n => n.trim().toUpperCase());
1138
- let validNotify = ['NEVER', 'SUCCESS', 'FAILURE', 'DELAY'];
1139
- let invaliNotify = notify.filter(n => !validNotify.includes(n));
1140
- if (invaliNotify.length || (notify.length > 1 && notify.includes('NEVER'))) {
1141
- throw new Error('notify: ' + JSON.stringify(notify.join(',')));
1142
- }
1143
- notify = notify.join(',');
1144
- }
1145
-
1146
- let orcpt = (params.recipient || params.orcpt || '').toString() || null;
1147
- if (orcpt && orcpt.indexOf(';') < 0) {
1148
- orcpt = 'rfc822;' + orcpt;
1149
- }
1150
-
1151
- return {
1152
- ret,
1153
- envid,
1154
- notify,
1155
- orcpt
1156
- };
1157
- }
1158
-
1159
- _getDsnRcptToArgs() {
1160
- let args = [];
1161
- // If the server supports DSN and the envelope includes an DSN prop
1162
- // then append DSN params to the RCPT TO command
1163
- if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) {
1164
- if (this._envelope.dsn.notify) {
1165
- args.push('NOTIFY=' + shared.encodeXText(this._envelope.dsn.notify));
1166
- }
1167
- if (this._envelope.dsn.orcpt) {
1168
- args.push('ORCPT=' + shared.encodeXText(this._envelope.dsn.orcpt));
1169
- }
1170
- }
1171
- return args.length ? ' ' + args.join(' ') : '';
1172
- }
1173
-
1174
- _createSendStream(callback) {
1175
- let dataStream = new DataStream();
1176
- let logStream;
1177
-
1178
- if (this.options.lmtp) {
1179
- this._envelope.accepted.forEach((recipient, i) => {
1180
- let final = i === this._envelope.accepted.length - 1;
1181
- this._responseActions.push(str => {
1182
- this._actionLMTPStream(recipient, final, str, callback);
1183
- });
1184
- });
1185
- } else {
1186
- this._responseActions.push(str => {
1187
- this._actionSMTPStream(str, callback);
1188
- });
1189
- }
1190
-
1191
- dataStream.pipe(this._socket, {
1192
- end: false
1193
- });
1194
-
1195
- if (this.options.debug) {
1196
- logStream = new PassThrough();
1197
- logStream.on('readable', () => {
1198
- let chunk;
1199
- while ((chunk = logStream.read())) {
1200
- this.logger.debug(
1201
- {
1202
- tnx: 'message'
1203
- },
1204
- chunk.toString('binary').replace(/\r?\n$/, '')
1205
- );
1206
- }
1207
- });
1208
- dataStream.pipe(logStream);
1209
- }
1210
-
1211
- dataStream.once('end', () => {
1212
- this.logger.info(
1213
- {
1214
- tnx: 'message',
1215
- inByteCount: dataStream.inByteCount,
1216
- outByteCount: dataStream.outByteCount
1217
- },
1218
- '<%s bytes encoded mime message (source size %s bytes)>',
1219
- dataStream.outByteCount,
1220
- dataStream.inByteCount
1221
- );
1222
- });
1223
-
1224
- return dataStream;
1225
- }
1226
-
1227
- /** ACTIONS **/
1228
-
1229
- /**
1230
- * Will be run after the connection is created and the server sends
1231
- * a greeting. If the incoming message starts with 220 initiate
1232
- * SMTP session by sending EHLO command
1233
- *
1234
- * @param {String} str Message from the server
1235
- */
1236
- _actionGreeting(str) {
1237
- clearTimeout(this._greetingTimeout);
1238
-
1239
- if (str.substr(0, 3) !== '220') {
1240
- this._onError(new Error('Invalid greeting. response=' + str), 'EPROTOCOL', str, 'CONN');
1241
- return;
1242
- }
1243
-
1244
- if (this.options.lmtp) {
1245
- this._responseActions.push(this._actionLHLO);
1246
- this._sendCommand('LHLO ' + this.name);
1247
- } else {
1248
- this._responseActions.push(this._actionEHLO);
1249
- this._sendCommand('EHLO ' + this.name);
1250
- }
1251
- }
1252
-
1253
- /**
1254
- * Handles server response for LHLO command. If it yielded in
1255
- * error, emit 'error', otherwise treat this as an EHLO response
1256
- *
1257
- * @param {String} str Message from the server
1258
- */
1259
- _actionLHLO(str) {
1260
- if (str.charAt(0) !== '2') {
1261
- this._onError(new Error('Invalid LHLO. response=' + str), 'EPROTOCOL', str, 'LHLO');
1262
- return;
1263
- }
1264
-
1265
- this._actionEHLO(str);
1266
- }
1267
-
1268
- /**
1269
- * Handles server response for EHLO command. If it yielded in
1270
- * error, try HELO instead, otherwise initiate TLS negotiation
1271
- * if STARTTLS is supported by the server or move into the
1272
- * authentication phase.
1273
- *
1274
- * @param {String} str Message from the server
1275
- */
1276
- _actionEHLO(str) {
1277
- let match;
1278
-
1279
- if (str.substr(0, 3) === '421') {
1280
- this._onError(new Error('Server terminates connection. response=' + str), 'ECONNECTION', str, 'EHLO');
1281
- return;
1282
- }
1283
-
1284
- if (str.charAt(0) !== '2') {
1285
- if (this.options.requireTLS) {
1286
- this._onError(new Error('EHLO failed but HELO does not support required STARTTLS. response=' + str), 'ECONNECTION', str, 'EHLO');
1287
- return;
1288
- }
1289
-
1290
- // Try HELO instead
1291
- this._responseActions.push(this._actionHELO);
1292
- this._sendCommand('HELO ' + this.name);
1293
- return;
1294
- }
1295
-
1296
- this._ehloLines = str
1297
- .split(/\r?\n/)
1298
- .map(line => line.replace(/^\d+[ -]/, '').trim())
1299
- .filter(line => line)
1300
- .slice(1);
1301
-
1302
- // Detect if the server supports STARTTLS
1303
- if (!this.secure && !this.options.ignoreTLS && (/[ -]STARTTLS\b/im.test(str) || this.options.requireTLS)) {
1304
- this._sendCommand('STARTTLS');
1305
- this._responseActions.push(this._actionSTARTTLS);
1306
- return;
1307
- }
1308
-
1309
- // Detect if the server supports SMTPUTF8
1310
- if (/[ -]SMTPUTF8\b/im.test(str)) {
1311
- this._supportedExtensions.push('SMTPUTF8');
1312
- }
1313
-
1314
- // Detect if the server supports DSN
1315
- if (/[ -]DSN\b/im.test(str)) {
1316
- this._supportedExtensions.push('DSN');
1317
- }
1318
-
1319
- // Detect if the server supports 8BITMIME
1320
- if (/[ -]8BITMIME\b/im.test(str)) {
1321
- this._supportedExtensions.push('8BITMIME');
1322
- }
1323
-
1324
- // Detect if the server supports PIPELINING
1325
- if (/[ -]PIPELINING\b/im.test(str)) {
1326
- this._supportedExtensions.push('PIPELINING');
1327
- }
1328
-
1329
- // Detect if the server supports AUTH
1330
- if (/[ -]AUTH\b/i.test(str)) {
1331
- this.allowsAuth = true;
1332
- }
1333
-
1334
- // Detect if the server supports PLAIN auth
1335
- if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)PLAIN/i.test(str)) {
1336
- this._supportedAuth.push('PLAIN');
1337
- }
1338
-
1339
- // Detect if the server supports LOGIN auth
1340
- if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)LOGIN/i.test(str)) {
1341
- this._supportedAuth.push('LOGIN');
1342
- }
1343
-
1344
- // Detect if the server supports CRAM-MD5 auth
1345
- if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)CRAM-MD5/i.test(str)) {
1346
- this._supportedAuth.push('CRAM-MD5');
1347
- }
1348
-
1349
- // Detect if the server supports XOAUTH2 auth
1350
- if (/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH2/i.test(str)) {
1351
- this._supportedAuth.push('XOAUTH2');
1352
- }
1353
-
1354
- // Detect if the server supports SIZE extensions (and the max allowed size)
1355
- if ((match = str.match(/[ -]SIZE(?:[ \t]+(\d+))?/im))) {
1356
- this._supportedExtensions.push('SIZE');
1357
- this._maxAllowedSize = Number(match[1]) || 0;
1358
- }
1359
-
1360
- this.emit('connect');
1361
- }
1362
-
1363
- /**
1364
- * Handles server response for HELO command. If it yielded in
1365
- * error, emit 'error', otherwise move into the authentication phase.
1366
- *
1367
- * @param {String} str Message from the server
1368
- */
1369
- _actionHELO(str) {
1370
- if (str.charAt(0) !== '2') {
1371
- this._onError(new Error('Invalid HELO. response=' + str), 'EPROTOCOL', str, 'HELO');
1372
- return;
1373
- }
1374
-
1375
- // assume that authentication is enabled (most probably is not though)
1376
- this.allowsAuth = true;
1377
-
1378
- this.emit('connect');
1379
- }
1380
-
1381
- /**
1382
- * Handles server response for STARTTLS command. If there's an error
1383
- * try HELO instead, otherwise initiate TLS upgrade. If the upgrade
1384
- * succeedes restart the EHLO
1385
- *
1386
- * @param {String} str Message from the server
1387
- */
1388
- _actionSTARTTLS(str) {
1389
- if (str.charAt(0) !== '2') {
1390
- if (this.options.opportunisticTLS) {
1391
- this.logger.info(
1392
- {
1393
- tnx: 'smtp'
1394
- },
1395
- 'Failed STARTTLS upgrade, continuing unencrypted'
1396
- );
1397
- return this.emit('connect');
1398
- }
1399
- this._onError(new Error('Error upgrading connection with STARTTLS'), 'ETLS', str, 'STARTTLS');
1400
- return;
1401
- }
1402
-
1403
- this._upgradeConnection((err, secured) => {
1404
- if (err) {
1405
- this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'STARTTLS');
1406
- return;
1407
- }
1408
-
1409
- this.logger.info(
1410
- {
1411
- tnx: 'smtp'
1412
- },
1413
- 'Connection upgraded with STARTTLS'
1414
- );
1415
-
1416
- if (secured) {
1417
- // restart session
1418
- if (this.options.lmtp) {
1419
- this._responseActions.push(this._actionLHLO);
1420
- this._sendCommand('LHLO ' + this.name);
1421
- } else {
1422
- this._responseActions.push(this._actionEHLO);
1423
- this._sendCommand('EHLO ' + this.name);
1424
- }
1425
- } else {
1426
- this.emit('connect');
1427
- }
1428
- });
1429
- }
1430
-
1431
- /**
1432
- * Handle the response for AUTH LOGIN command. We are expecting
1433
- * '334 VXNlcm5hbWU6' (base64 for 'Username:'). Data to be sent as
1434
- * response needs to be base64 encoded username. We do not need
1435
- * exact match but settle with 334 response in general as some
1436
- * hosts invalidly use a longer message than VXNlcm5hbWU6
1437
- *
1438
- * @param {String} str Message from the server
1439
- */
1440
- _actionAUTH_LOGIN_USER(str, callback) {
1441
- if (!/^334[ -]/.test(str)) {
1442
- // expecting '334 VXNlcm5hbWU6'
1443
- callback(this._formatError('Invalid login sequence while waiting for "334 VXNlcm5hbWU6"', 'EAUTH', str, 'AUTH LOGIN'));
1444
- return;
1445
- }
1446
-
1447
- this._responseActions.push(str => {
1448
- this._actionAUTH_LOGIN_PASS(str, callback);
1449
- });
1450
-
1451
- this._sendCommand(Buffer.from(this._auth.credentials.user + '', 'utf-8').toString('base64'));
1452
- }
1453
-
1454
- /**
1455
- * Handle the response for AUTH CRAM-MD5 command. We are expecting
1456
- * '334 <challenge string>'. Data to be sent as response needs to be
1457
- * base64 decoded challenge string, MD5 hashed using the password as
1458
- * a HMAC key, prefixed by the username and a space, and finally all
1459
- * base64 encoded again.
1460
- *
1461
- * @param {String} str Message from the server
1462
- */
1463
- _actionAUTH_CRAM_MD5(str, callback) {
1464
- let challengeMatch = str.match(/^334\s+(.+)$/);
1465
- let challengeString = '';
1466
-
1467
- if (!challengeMatch) {
1468
- return callback(this._formatError('Invalid login sequence while waiting for server challenge string', 'EAUTH', str, 'AUTH CRAM-MD5'));
1469
- } else {
1470
- challengeString = challengeMatch[1];
1471
- }
1472
-
1473
- // Decode from base64
1474
- let base64decoded = Buffer.from(challengeString, 'base64').toString('ascii'),
1475
- hmacMD5 = crypto.createHmac('md5', this._auth.credentials.pass);
1476
-
1477
- hmacMD5.update(base64decoded);
1478
-
1479
- let prepended = this._auth.credentials.user + ' ' + hmacMD5.digest('hex');
1480
-
1481
- this._responseActions.push(str => {
1482
- this._actionAUTH_CRAM_MD5_PASS(str, callback);
1483
- });
1484
-
1485
- this._sendCommand(
1486
- Buffer.from(prepended).toString('base64'),
1487
- // hidden hash for logs
1488
- Buffer.from(this._auth.credentials.user + ' /* secret */').toString('base64')
1489
- );
1490
- }
1491
-
1492
- /**
1493
- * Handles the response to CRAM-MD5 authentication, if there's no error,
1494
- * the user can be considered logged in. Start waiting for a message to send
1495
- *
1496
- * @param {String} str Message from the server
1497
- */
1498
- _actionAUTH_CRAM_MD5_PASS(str, callback) {
1499
- if (!str.match(/^235\s+/)) {
1500
- return callback(this._formatError('Invalid login sequence while waiting for "235"', 'EAUTH', str, 'AUTH CRAM-MD5'));
1501
- }
1502
-
1503
- this.logger.info(
1504
- {
1505
- tnx: 'smtp',
1506
- username: this._auth.user,
1507
- action: 'authenticated',
1508
- method: this._authMethod
1509
- },
1510
- 'User %s authenticated',
1511
- JSON.stringify(this._auth.user)
1512
- );
1513
- this.authenticated = true;
1514
- callback(null, true);
1515
- }
1516
-
1517
- /**
1518
- * Handle the response for AUTH LOGIN command. We are expecting
1519
- * '334 UGFzc3dvcmQ6' (base64 for 'Password:'). Data to be sent as
1520
- * response needs to be base64 encoded password.
1521
- *
1522
- * @param {String} str Message from the server
1523
- */
1524
- _actionAUTH_LOGIN_PASS(str, callback) {
1525
- if (!/^334[ -]/.test(str)) {
1526
- // expecting '334 UGFzc3dvcmQ6'
1527
- return callback(this._formatError('Invalid login sequence while waiting for "334 UGFzc3dvcmQ6"', 'EAUTH', str, 'AUTH LOGIN'));
1528
- }
1529
-
1530
- this._responseActions.push(str => {
1531
- this._actionAUTHComplete(str, callback);
1532
- });
1533
-
1534
- this._sendCommand(
1535
- Buffer.from((this._auth.credentials.pass || '').toString(), 'utf-8').toString('base64'),
1536
- // Hidden pass for logs
1537
- Buffer.from('/* secret */', 'utf-8').toString('base64')
1538
- );
1539
- }
1540
-
1541
- /**
1542
- * Handles the response for authentication, if there's no error,
1543
- * the user can be considered logged in. Start waiting for a message to send
1544
- *
1545
- * @param {String} str Message from the server
1546
- */
1547
- _actionAUTHComplete(str, isRetry, callback) {
1548
- if (!callback && typeof isRetry === 'function') {
1549
- callback = isRetry;
1550
- isRetry = false;
1551
- }
1552
-
1553
- if (str.substr(0, 3) === '334') {
1554
- this._responseActions.push(str => {
1555
- if (isRetry || this._authMethod !== 'XOAUTH2') {
1556
- this._actionAUTHComplete(str, true, callback);
1557
- } else {
1558
- // fetch a new OAuth2 access token
1559
- setImmediate(() => this._handleXOauth2Token(true, callback));
1560
- }
1561
- });
1562
- this._sendCommand('');
1563
- return;
1564
- }
1565
-
1566
- if (str.charAt(0) !== '2') {
1567
- this.logger.info(
1568
- {
1569
- tnx: 'smtp',
1570
- username: this._auth.user,
1571
- action: 'authfail',
1572
- method: this._authMethod
1573
- },
1574
- 'User %s failed to authenticate',
1575
- JSON.stringify(this._auth.user)
1576
- );
1577
- return callback(this._formatError('Invalid login', 'EAUTH', str, 'AUTH ' + this._authMethod));
1578
- }
1579
-
1580
- this.logger.info(
1581
- {
1582
- tnx: 'smtp',
1583
- username: this._auth.user,
1584
- action: 'authenticated',
1585
- method: this._authMethod
1586
- },
1587
- 'User %s authenticated',
1588
- JSON.stringify(this._auth.user)
1589
- );
1590
- this.authenticated = true;
1591
- callback(null, true);
1592
- }
1593
-
1594
- /**
1595
- * Handle response for a MAIL FROM: command
1596
- *
1597
- * @param {String} str Message from the server
1598
- */
1599
- _actionMAIL(str, callback) {
1600
- let message, curRecipient;
1601
- if (Number(str.charAt(0)) !== 2) {
1602
- if (this._usingSmtpUtf8 && /^550 /.test(str) && /[\x80-\uFFFF]/.test(this._envelope.from)) {
1603
- message = 'Internationalized mailbox name not allowed';
1604
- } else {
1605
- message = 'Mail command failed';
1606
- }
1607
- return callback(this._formatError(message, 'EENVELOPE', str, 'MAIL FROM'));
1608
- }
1609
-
1610
- if (!this._envelope.rcptQueue.length) {
1611
- return callback(this._formatError('Can\x27t send mail - no recipients defined', 'EENVELOPE', false, 'API'));
1612
- } else {
1613
- this._recipientQueue = [];
1614
-
1615
- if (this._supportedExtensions.includes('PIPELINING')) {
1616
- while (this._envelope.rcptQueue.length) {
1617
- curRecipient = this._envelope.rcptQueue.shift();
1618
- this._recipientQueue.push(curRecipient);
1619
- this._responseActions.push(str => {
1620
- this._actionRCPT(str, callback);
1621
- });
1622
- this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs());
1623
- }
1624
- } else {
1625
- curRecipient = this._envelope.rcptQueue.shift();
1626
- this._recipientQueue.push(curRecipient);
1627
- this._responseActions.push(str => {
1628
- this._actionRCPT(str, callback);
1629
- });
1630
- this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs());
1631
- }
1632
- }
1633
- }
1634
-
1635
- /**
1636
- * Handle response for a RCPT TO: command
1637
- *
1638
- * @param {String} str Message from the server
1639
- */
1640
- _actionRCPT(str, callback) {
1641
- let message,
1642
- err,
1643
- curRecipient = this._recipientQueue.shift();
1644
- if (Number(str.charAt(0)) !== 2) {
1645
- // this is a soft error
1646
- if (this._usingSmtpUtf8 && /^553 /.test(str) && /[\x80-\uFFFF]/.test(curRecipient)) {
1647
- message = 'Internationalized mailbox name not allowed';
1648
- } else {
1649
- message = 'Recipient command failed';
1650
- }
1651
- this._envelope.rejected.push(curRecipient);
1652
- // store error for the failed recipient
1653
- err = this._formatError(message, 'EENVELOPE', str, 'RCPT TO');
1654
- err.recipient = curRecipient;
1655
- this._envelope.rejectedErrors.push(err);
1656
- } else {
1657
- this._envelope.accepted.push(curRecipient);
1658
- }
1659
-
1660
- if (!this._envelope.rcptQueue.length && !this._recipientQueue.length) {
1661
- if (this._envelope.rejected.length < this._envelope.to.length) {
1662
- this._responseActions.push(str => {
1663
- this._actionDATA(str, callback);
1664
- });
1665
- this._sendCommand('DATA');
1666
- } else {
1667
- err = this._formatError('Can\x27t send mail - all recipients were rejected', 'EENVELOPE', str, 'RCPT TO');
1668
- err.rejected = this._envelope.rejected;
1669
- err.rejectedErrors = this._envelope.rejectedErrors;
1670
- return callback(err);
1671
- }
1672
- } else if (this._envelope.rcptQueue.length) {
1673
- curRecipient = this._envelope.rcptQueue.shift();
1674
- this._recipientQueue.push(curRecipient);
1675
- this._responseActions.push(str => {
1676
- this._actionRCPT(str, callback);
1677
- });
1678
- this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs());
1679
- }
1680
- }
1681
-
1682
- /**
1683
- * Handle response for a DATA command
1684
- *
1685
- * @param {String} str Message from the server
1686
- */
1687
- _actionDATA(str, callback) {
1688
- // response should be 354 but according to this issue https://github.com/eleith/emailjs/issues/24
1689
- // some servers might use 250 instead, so lets check for 2 or 3 as the first digit
1690
- if (!/^[23]/.test(str)) {
1691
- return callback(this._formatError('Data command failed', 'EENVELOPE', str, 'DATA'));
1692
- }
1693
-
1694
- let response = {
1695
- accepted: this._envelope.accepted,
1696
- rejected: this._envelope.rejected
1697
- };
1698
-
1699
- if (this._ehloLines && this._ehloLines.length) {
1700
- response.ehlo = this._ehloLines;
1701
- }
1702
-
1703
- if (this._envelope.rejectedErrors.length) {
1704
- response.rejectedErrors = this._envelope.rejectedErrors;
1705
- }
1706
-
1707
- callback(null, response);
1708
- }
1709
-
1710
- /**
1711
- * Handle response for a DATA stream when using SMTP
1712
- * We expect a single response that defines if the sending succeeded or failed
1713
- *
1714
- * @param {String} str Message from the server
1715
- */
1716
- _actionSMTPStream(str, callback) {
1717
- if (Number(str.charAt(0)) !== 2) {
1718
- // Message failed
1719
- return callback(this._formatError('Message failed', 'EMESSAGE', str, 'DATA'));
1720
- } else {
1721
- // Message sent succesfully
1722
- return callback(null, str);
1723
- }
1724
- }
1725
-
1726
- /**
1727
- * Handle response for a DATA stream
1728
- * We expect a separate response for every recipient. All recipients can either
1729
- * succeed or fail separately
1730
- *
1731
- * @param {String} recipient The recipient this response applies to
1732
- * @param {Boolean} final Is this the final recipient?
1733
- * @param {String} str Message from the server
1734
- */
1735
- _actionLMTPStream(recipient, final, str, callback) {
1736
- let err;
1737
- if (Number(str.charAt(0)) !== 2) {
1738
- // Message failed
1739
- err = this._formatError('Message failed for recipient ' + recipient, 'EMESSAGE', str, 'DATA');
1740
- err.recipient = recipient;
1741
- this._envelope.rejected.push(recipient);
1742
- this._envelope.rejectedErrors.push(err);
1743
- for (let i = 0, len = this._envelope.accepted.length; i < len; i++) {
1744
- if (this._envelope.accepted[i] === recipient) {
1745
- this._envelope.accepted.splice(i, 1);
1746
- }
1747
- }
1748
- }
1749
- if (final) {
1750
- return callback(null, str);
1751
- }
1752
- }
1753
-
1754
- _handleXOauth2Token(isRetry, callback) {
1755
- this._auth.oauth2.getToken(isRetry, (err, accessToken) => {
1756
- if (err) {
1757
- this.logger.info(
1758
- {
1759
- tnx: 'smtp',
1760
- username: this._auth.user,
1761
- action: 'authfail',
1762
- method: this._authMethod
1763
- },
1764
- 'User %s failed to authenticate',
1765
- JSON.stringify(this._auth.user)
1766
- );
1767
- return callback(this._formatError(err, 'EAUTH', false, 'AUTH XOAUTH2'));
1768
- }
1769
- this._responseActions.push(str => {
1770
- this._actionAUTHComplete(str, isRetry, callback);
1771
- });
1772
- this._sendCommand(
1773
- 'AUTH XOAUTH2 ' + this._auth.oauth2.buildXOAuth2Token(accessToken),
1774
- // Hidden for logs
1775
- 'AUTH XOAUTH2 ' + this._auth.oauth2.buildXOAuth2Token('/* secret */')
1776
- );
1777
- });
1778
- }
1779
-
1780
- /**
1781
- *
1782
- * @param {string} command
1783
- * @private
1784
- */
1785
- _isDestroyedMessage(command) {
1786
- if (this._destroyed) {
1787
- return 'Cannot ' + command + ' - smtp connection is already destroyed.';
1788
- }
1789
-
1790
- if (this._socket) {
1791
- if (this._socket.destroyed) {
1792
- return 'Cannot ' + command + ' - smtp connection socket is already destroyed.';
1793
- }
1794
-
1795
- if (!this._socket.writable) {
1796
- return 'Cannot ' + command + ' - smtp connection socket is already half-closed.';
1797
- }
1798
- }
1799
- }
1800
-
1801
- _getHostname() {
1802
- // defaul hostname is machine hostname or [IP]
1803
- let defaultHostname;
1804
- try {
1805
- defaultHostname = os.hostname() || '';
1806
- } catch (err) {
1807
- // fails on windows 7
1808
- defaultHostname = 'localhost';
1809
- }
1810
-
1811
- // ignore if not FQDN
1812
- if (!defaultHostname || defaultHostname.indexOf('.') < 0) {
1813
- defaultHostname = '[127.0.0.1]';
1814
- }
1815
-
1816
- // IP should be enclosed in []
1817
- if (defaultHostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
1818
- defaultHostname = '[' + defaultHostname + ']';
1819
- }
1820
-
1821
- return defaultHostname;
1822
- }
1823
- }
1824
-
1825
- module.exports = SMTPConnection;