emailjs 1.0.11 → 2.2.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/smtp/smtp.js CHANGED
@@ -1,589 +1,872 @@
1
1
  /*
2
2
  * SMTP class written using python's (2.7) smtplib.py as a base
3
3
  */
4
- var net = require('net');
5
- var crypto = require('crypto');
6
- var os = require('os');
7
- var tls = require('tls');
8
- var util = require('util');
9
- var events = require('events');
10
-
11
- var SMTPResponse = require('./response');
12
- var SMTPError = require('./error');
13
-
14
- var SMTP_PORT = 25;
15
- var SMTP_SSL_PORT = 465;
16
- var SMTP_TLS_PORT = 587;
17
- var CRLF = "\r\n";
18
- var AUTH_METHODS = {
19
- PLAIN: 'PLAIN',
20
- CRAM_MD5: 'CRAM-MD5',
21
- LOGIN: 'LOGIN',
22
- XOAUTH2: 'XOAUTH2'
23
- };
24
- var TIMEOUT = 5000;
25
- var DEBUG = 0;
26
-
27
- var log = function() {
28
- if (DEBUG) {
29
- Array.prototype.slice.call(arguments).forEach(function(d) {
30
- console.log(d);
31
- });
32
- }
33
- };
4
+ const { Socket } = require('net');
5
+ const { createHmac } = require('crypto');
6
+ const { hostname } = require('os');
7
+ const { connect, createSecureContext, TLSSocket } = require('tls');
8
+ const { EventEmitter } = require('events');
9
+
10
+ const SMTPResponse = require('./response');
11
+ const SMTPError = require('./error');
12
+
13
+ /**
14
+ * @readonly
15
+ * @type {5000}
16
+ */
17
+ const TIMEOUT = 5000;
34
18
 
35
- var quotedata = function(data) {
36
- // Quote data for email.
37
- // Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
38
- // Internet CRLF end-of-line.
19
+ /**
20
+ * @readonly
21
+ * @type {25}
22
+ */
23
+ const SMTP_PORT = 25;
39
24
 
40
- return data.replace(/(?:\r\n|\n|\r(?!\n))/g, CRLF).replace(/^\./gm, '..');
41
- };
25
+ /**
26
+ * @readonly
27
+ * @type {465}
28
+ */
29
+ const SMTP_SSL_PORT = 465;
30
+
31
+ /**
32
+ * @readonly
33
+ * @type {587}
34
+ */
35
+ const SMTP_TLS_PORT = 587;
42
36
 
43
- var caller = function(callback) {
44
- if (typeof(callback) == 'function') {
45
- var args = Array.prototype.slice.call(arguments);
46
- args.shift();
37
+ /**
38
+ * @readonly
39
+ * @type {'\r\n'}
40
+ */
41
+ const CRLF = '\r\n';
47
42
 
48
- callback.apply(null, args);
49
- }
43
+ /**
44
+ * @readonly
45
+ * @enum
46
+ */
47
+ const AUTH_METHODS = {
48
+ PLAIN: /** @type {'PLAIN'} */ ('PLAIN'),
49
+ CRAM_MD5: /** @type {'CRAM-MD5'} */ ('CRAM-MD5'),
50
+ LOGIN: /** @type {'LOGIN'} */ ('LOGIN'),
51
+ XOAUTH2: /** @type {'XOAUTH2'} */ ('XOAUTH2'),
50
52
  };
51
53
 
52
- var SMTPState = {
53
- NOTCONNECTED: 0,
54
- CONNECTING: 1,
55
- CONNECTED: 2
54
+ /**
55
+ * @type {0 | 1}
56
+ */
57
+ let DEBUG = 0;
58
+
59
+ /**
60
+ * @param {...string} args the message(s) to log
61
+ * @returns {void}
62
+ */
63
+ const log = (...args) => {
64
+ if (DEBUG === 1) {
65
+ args.forEach(d => console.log(d));
66
+ }
56
67
  };
57
68
 
58
- var SMTP = function(options) {
59
- events.EventEmitter.call(this);
60
-
61
- options = options || {};
62
-
63
- this.sock = null;
64
- this.timeout = options.timeout || TIMEOUT;
65
- this.features = null;
66
- this._state = SMTPState.NOTCONNECTED;
67
- this._secure = false;
68
- this.loggedin = (options.user && options.password) ? false : true;
69
- this.domain = options.domain || os.hostname();
70
- this.host = options.host || 'localhost';
71
- this.port = options.port || (options.ssl ? SMTP_SSL_PORT : options.tls ? SMTP_TLS_PORT : SMTP_PORT);
72
- this.ssl = options.ssl || false;
73
- this.tls = options.tls || false;
74
- this.monitor = null;
75
- this.authentication = options.authentication || [AUTH_METHODS.CRAM_MD5, AUTH_METHODS.LOGIN, AUTH_METHODS.PLAIN, AUTH_METHODS.XOAUTH2];
76
-
77
- // keep these strings hidden when quicky debugging/logging
78
- this.user = function() {
79
- return options.user;
80
- };
81
- this.password = function() {
82
- return options.password;
83
- };
69
+ /**
70
+ * @param {function(...*): void} callback the function to call
71
+ * @param {...*} args the arguments to apply to the function
72
+ * @returns {void}
73
+ */
74
+ const caller = (callback, ...args) => {
75
+ if (typeof callback === 'function') {
76
+ callback.apply(null, args);
77
+ }
84
78
  };
85
79
 
86
- SMTP.prototype = {
87
- debug: function(level) {
88
- DEBUG = level;
89
- },
90
-
91
- state: function() {
92
- return this._state;
93
- },
94
-
95
- authorized: function() {
96
- return this.loggedin;
97
- },
98
-
99
- connect: function(callback, port, host, options) {
100
- options = options || {};
101
-
102
- var self = this;
103
-
104
- self.host = host || self.host;
105
- self.port = port || self.port;
106
- self.ssl = options.ssl || self.ssl;
107
-
108
- if (self._state != SMTPState.NOTCONNECTED) {
109
- self.quit(function() {
110
- self.connect(callback, port, host, options);
111
- });
112
- return;
113
- }
114
-
115
- var connected = function(err) {
116
- if (!err) {
117
- log("connected: " + self.host + ":" + self.port);
118
-
119
- if (self.ssl && !self.tls) {
120
- // if key/ca/cert was passed in, check if connection is authorized
121
- if (typeof(self.ssl) != 'boolean' && !self.sock.authorized) {
122
- self.close(true);
123
- caller(callback, SMTPError('could not establish an ssl connection', SMTPError.CONNECTIONAUTH, err));
124
- } else self._secure = true;
125
- }
126
- } else {
127
- self.close(true);
128
- caller(callback, SMTPError("could not connect", SMTPError.COULDNOTCONNECT, err));
129
- }
130
- };
131
-
132
- var response = function(err, msg) {
133
- if (err) {
134
- if (self._state === SMTPState.NOTCONNECTED && !self.sock) {
135
- return;
136
- }
137
- self.close(true);
138
- caller(callback, err);
139
- } else if (msg.code == '220') {
140
- log(msg.data);
141
-
142
- // might happen first, so no need to wait on connected()
143
- self._state = SMTPState.CONNECTED;
144
- caller(callback, null, msg.data);
145
- } else {
146
- log("response (data): " + msg.data);
147
- self.quit(function() {
148
- caller(callback, SMTPError("bad response on connection", SMTPError.BADRESPONSE, err, msg.data));
149
- });
150
- }
151
- };
152
-
153
- self._state = SMTPState.CONNECTING;
154
- log("connecting: " + self.host + ":" + self.port);
155
-
156
- if (self.ssl) {
157
- self.sock = tls.connect(self.port, self.host, self.ssl, connected);
158
- } else {
159
- self.sock = new net.Socket();
160
- self.sock.connect(self.port, self.host, connected);
161
- }
162
-
163
- self.monitor = SMTPResponse.monitor(self.sock, self.timeout, function() {
164
- self.close(true);
165
- });
166
- self.sock.once('response', response);
167
- self.sock.once('error', response); // the socket could reset or throw, so let's handle it and let the user know
168
- },
169
-
170
- send: function(str, callback) {
171
- var self = this;
172
-
173
- if (self.sock && self._state == SMTPState.CONNECTED) {
174
- log(str);
175
-
176
- var response = function(err, msg) {
177
- if (err) {
178
- caller(callback, err);
179
- } else {
180
- log(msg.data);
181
- caller(callback, null, msg);
182
- }
183
- };
184
-
185
- self.sock.once('response', response);
186
- self.sock.write(str);
187
- } else {
188
- self.close(true);
189
- caller(callback, SMTPError('no connection has been established', SMTPError.NOCONNECTION));
190
- }
191
- },
192
-
193
- command: function(cmd, callback, codes, failed) {
194
- codes = Array.isArray(codes) ? codes : typeof(codes) == 'number' ? [codes] : [250];
195
-
196
- var response = function(err, msg) {
197
- if (err) {
198
- caller(callback, err);
199
- } else {
200
- if (codes.indexOf(Number(msg.code)) != -1) {
201
- caller(callback, err, msg.data, msg.message);
202
- } else {
203
- var errorMessage = "bad response on command '" + cmd.split(' ')[0] + "'";
204
- if (msg.message) {
205
- errorMessage += ': ' + msg.message;
206
- }
207
- caller(callback, SMTPError(errorMessage, SMTPError.BADRESPONSE, null, msg.data));
208
- }
209
- }
210
- };
211
-
212
- this.send(cmd + CRLF, response);
213
- },
214
-
215
- helo: function(callback, domain) {
216
- /*
217
- * SMTP 'helo' command.
218
- * Hostname to send for self command defaults to the FQDN of the local
219
- * host.
220
- */
221
-
222
- var self = this,
223
-
224
- response = function(err, data) {
225
- if (err) {
226
- caller(callback, err);
227
- } else {
228
- self.parse_smtp_features(data);
229
- caller(callback, err, data);
230
- }
231
- };
232
-
233
- this.command("helo " + (domain || this.domain), response);
234
- },
235
-
236
- starttls: function(callback) {
237
- var self = this,
238
-
239
- response = function(err, msg) {
240
- if (err) {
241
- err.message += " while establishing a starttls session";
242
- caller(callback, err);
243
- } else {
244
- // support new API
245
- if (tls.TLSSocket) {
246
- var secured_socket = new tls.TLSSocket(self.sock, {
247
- secureContext: tls.createSecureContext ? tls.createSecureContext(self.tls) : crypto.createCredentials(self.tls),
248
- isServer: false // older versions of node (0.12), do not default to false properly...
249
- });
250
-
251
- secured_socket.on('error', function(err) {
252
- self.close(true);
253
- caller(callback, err);
254
- });
255
-
256
- self._secure = true;
257
- self.sock = secured_socket;
258
-
259
- SMTPResponse.monitor(self.sock, self.timeout, function() {
260
- self.close(true);
261
- });
262
- caller(callback, msg.data);
263
- } else {
264
- var secured_socket = null;
265
- var secured = function() {
266
- self._secure = true;
267
- self.sock = secured_socket;
268
-
269
- var error = function(err) {
270
- self.close(true);
271
- caller(callback, err);
272
- };
273
-
274
- SMTPResponse.monitor(self.sock, self.timeout, function() {
275
- self.close(true);
276
- });
277
- caller(callback, msg.data);
278
- };
279
-
280
- //secured_socket = starttls.secure(self.sock, self.tls, secured);
281
- var starttls = require('starttls');
282
- secured_socket = starttls({
283
- socket: self.sock,
284
- host: self.host,
285
- port: self.port,
286
- pair: tls.createSecurePair(
287
- tls.createSecureContext ? tls.createSecureContext(self.tls) : crypto.createCredentials(self.tls),
288
- false)
289
- }, secured).cleartext;
290
-
291
- secured_socket.on('error', function(err) {
292
- self.close(true);
293
- caller(callback, err);
294
- });
295
- }
296
- }
297
- };
298
-
299
- this.command("starttls", response, [220]);
300
- },
301
-
302
- parse_smtp_features: function(data) {
303
- var self = this;
304
-
305
- // According to RFC1869 some (badly written)
306
- // MTA's will disconnect on an ehlo. Toss an exception if
307
- // that happens -ddm
308
-
309
- data.split("\n").forEach(function(ext) {
310
- var parse = ext.match(/^(?:\d+[\-=]?)\s*?([^\s]+)(?:\s+(.*)\s*?)?$/);
311
-
312
- // To be able to communicate with as many SMTP servers as possible,
313
- // we have to take the old-style auth advertisement into account,
314
- // because:
315
- // 1) Else our SMTP feature parser gets confused.
316
- // 2) There are some servers that only advertise the auth methods we
317
- // support using the old style.
318
-
319
- if (parse) {
320
- // RFC 1869 requires a space between ehlo keyword and parameters.
321
- // It's actually stricter, in that only spaces are allowed between
322
- // parameters, but were not going to check for that here. Note
323
- // that the space isn't present if there are no parameters.
324
- self.features[parse[1].toLowerCase()] = parse[2] || true;
325
- }
326
- });
327
-
328
- return;
329
- },
330
-
331
- ehlo: function(callback, domain) {
332
- var self = this,
333
-
334
- response = function(err, data) {
335
- if (err) {
336
- caller(callback, err);
337
- } else {
338
- self.parse_smtp_features(data);
339
-
340
- if (self.tls && !self._secure) {
341
- self.starttls(function() {
342
- self.ehlo(callback, domain);
343
- });
344
- } else {
345
- caller(callback, err, data);
346
- }
347
- }
348
- };
349
-
350
- this.features = {};
351
- this.command("ehlo " + (domain || this.domain), response);
352
- },
353
-
354
- has_extn: function(opt) {
355
- return this.features[opt.toLowerCase()] === undefined;
356
- },
357
-
358
- help: function(callback, args) {
359
- // SMTP 'help' command, returns text from the server
360
- this.command(args ? "help " + args : "help", callback, [211, 214]);
361
- },
362
-
363
- rset: function(callback) {
364
- this.command("rset", callback);
365
- },
366
-
367
- noop: function(callback) {
368
- this.send("noop", callback);
369
- },
370
-
371
- mail: function(callback, from) {
372
- this.command("mail FROM:" + from, callback);
373
- },
374
-
375
- rcpt: function(callback, to) {
376
- this.command("RCPT TO:" + to, callback, [250, 251]);
377
- },
378
-
379
- data: function(callback) {
380
- this.command("data", callback, [354]);
381
- },
382
-
383
- data_end: function(callback) {
384
- this.command(CRLF + ".", callback);
385
- },
386
-
387
- message: function(data) {
388
- log(data);
389
- this.sock.write(data);
390
- },
391
-
392
- verify: function(address, callback) {
393
- // SMTP 'verify' command -- checks for address validity."""
394
- this.command("vrfy " + address, callback, [250, 251, 252]);
395
- },
396
-
397
- expn: function(address, callback) {
398
- // SMTP 'expn' command -- expands a mailing list.
399
- this.command("expn " + address, callback);
400
- },
401
-
402
- ehlo_or_helo_if_needed: function(callback, domain) {
403
- // Call self.ehlo() and/or self.helo() if needed.
404
- // If there has been no previous EHLO or HELO command self session, self
405
- // method tries ESMTP EHLO first.
406
- var self = this;
407
-
408
- if (!this.features) {
409
- var response = function(err, data) {
410
- caller(callback, err, data);
411
- };
412
-
413
- var attempt = function(err, data) {
414
- if (err) self.helo(response, domain);
415
- else caller(callback, err, data);
416
- };
417
-
418
- self.ehlo(attempt, domain);
419
- }
420
- },
421
-
422
- login: function(callback, user, password, options) {
423
- var self = this,
424
-
425
- login = {
426
- user: user ? function() {
427
- return user;
428
- } : self.user,
429
- password: password ? function() {
430
- return password;
431
- } : self.password,
432
- method: options && options.method ? options.method.toUpperCase() : ''
433
- },
434
-
435
- domain = options && options.domain ? options.domain : this.domain,
436
-
437
- initiate = function(err, data) {
438
- if (err) {
439
- caller(callback, err);
440
- return;
441
- }
442
-
443
- /*
444
- * Log in on an SMTP server that requires authentication.
445
- *
446
- * The arguments are:
447
- * - user: The user name to authenticate with.
448
- * - password: The password for the authentication.
449
- *
450
- * If there has been no previous EHLO or HELO command self session, self
451
- * method tries ESMTP EHLO first.
452
- *
453
- * This method will return normally if the authentication was successful.
454
- */
455
-
456
- var method = null,
457
-
458
- encode_cram_md5 = function(challenge) {
459
- challenge = (new Buffer(challenge, "base64")).toString("ascii");
460
-
461
- var hmac = crypto.createHmac('md5', login.password());
462
- hmac.update(challenge);
463
-
464
- return (new Buffer(login.user() + " " + hmac.digest('hex')).toString("base64"));
465
- },
466
-
467
- encode_plain = function() {
468
- return (new Buffer("\u0000" + login.user() + "\u0000" + login.password())).toString("base64");
469
- },
470
-
471
- encode_xoauth2 = function() {
472
- // console.log("user=" + login.user() + "\1auth=Bearer " + login.password()+"\1\1");
473
- // see: https://developers.google.com/gmail/xoauth2_protocol
474
- return (new Buffer("user=" + login.user() + "\u0001auth=Bearer " + login.password() + "\u0001\u0001")).toString("base64");
475
- };
476
-
477
- // List of authentication methods we support: from preferred to
478
- // less preferred methods.
479
- if (!method) {
480
- var preferred = self.authentication;
481
- var auth = "";
482
-
483
- if (self.features && self.features.auth) {
484
- if (typeof(self.features.auth) === 'string') {
485
- auth = self.features.auth;
486
- }
487
- }
488
-
489
- for (var i = 0; i < preferred.length; i++) {
490
- if (auth.indexOf(preferred[i]) != -1) {
491
- method = preferred[i];
492
- break;
493
- }
494
- }
495
- }
496
-
497
- // handle bad responses from command differently
498
- var failed = function(err, data) {
499
- self.loggedin = false;
500
- self.close(); // if auth is bad, close the connection, it won't get better by itself
501
- caller(callback, SMTPError('authorization.failed', SMTPError.AUTHFAILED, err, data));
502
- };
503
-
504
- var response = function(err, data) {
505
- if (err) {
506
- failed(err, data);
507
- } else {
508
- self.loggedin = true;
509
- caller(callback, err, data);
510
- }
511
- };
512
-
513
- var attempt = function(err, data, msg) {
514
- if (err) {
515
- failed(err, data);
516
- } else {
517
- if (method == AUTH_METHODS.CRAM_MD5) {
518
- self.command(encode_cram_md5(msg), response, [235, 503]);
519
- } else if (method == AUTH_METHODS.LOGIN) {
520
- self.command((new Buffer(login.password())).toString("base64"), response, [235, 503]);
521
- }
522
- }
523
- };
524
-
525
- var attempt_user = function(err, data, msg) {
526
- if (err) {
527
- failed(err, data);
528
- } else {
529
- if (method == AUTH_METHODS.LOGIN) {
530
- self.command((new Buffer(login.user())).toString("base64"), attempt, [334]);
531
- }
532
- }
533
- };
534
-
535
- if (method == AUTH_METHODS.CRAM_MD5) self.command("AUTH " + AUTH_METHODS.CRAM_MD5, attempt, [334]);
536
-
537
- else if (method == AUTH_METHODS.LOGIN) self.command("AUTH " + AUTH_METHODS.LOGIN, attempt_user, [334]);
538
-
539
- else if (method == AUTH_METHODS.PLAIN) self.command("AUTH " + AUTH_METHODS.PLAIN + " " + encode_plain(login.user(), login.password()), response, [235, 503]);
540
-
541
- else if (method == AUTH_METHODS.XOAUTH2) self.command("AUTH " + AUTH_METHODS.XOAUTH2 + " " + encode_xoauth2(login.user(), login.password()), response, [235, 503]);
542
-
543
- else if (!method) caller(callback, SMTPError('no form of authorization supported', SMTPError.AUTHNOTSUPPORTED, null, data));
544
- };
545
-
546
- self.ehlo_or_helo_if_needed(initiate, domain);
547
- },
548
-
549
- close: function(force) {
550
- if (this.sock) {
551
- if (force) {
552
- log("smtp connection destroyed!");
553
- this.sock.destroy();
554
- } else {
555
- log("smtp connection closed.");
556
- this.sock.end();
557
- }
558
- }
559
-
560
- if (this.monitor) {
561
- this.monitor.stop();
562
- this.monitor = null;
563
- }
564
-
565
- this._state = SMTPState.NOTCONNECTED;
566
- this._secure = false;
567
- this.sock = null;
568
- this.features = null;
569
- this.loggedin = !(this.user() && this.password());
570
- },
571
-
572
- quit: function(callback) {
573
- var self = this,
574
- response = function(err, data) {
575
- caller(callback, err, data);
576
- self.close();
577
- };
578
-
579
- this.command("quit", response, [221, 250]);
580
- }
80
+ const SMTPState = {
81
+ NOTCONNECTED: 0,
82
+ CONNECTING: 1,
83
+ CONNECTED: 2,
581
84
  };
582
85
 
583
- for (var each in events.EventEmitter.prototype) {
584
- SMTP.prototype[each] = events.EventEmitter.prototype[each];
86
+ class SMTP extends EventEmitter {
87
+ /**
88
+ * @typedef {Object} SMTPSocketOptions
89
+ * @property {string} key
90
+ * @property {string} ca
91
+ * @property {string} cert
92
+ *
93
+ * @typedef {Object} SMTPOptions
94
+ * @property {number} [timeout]
95
+ * @property {string} [user]
96
+ * @property {string} [password]
97
+ * @property {string} [domain]
98
+ * @property {string} [host]
99
+ * @property {number} [port]
100
+ * @property {boolean|SMTPSocketOptions} [ssl]
101
+ * @property {boolean|SMTPSocketOptions} [tls]
102
+ * @property {string[]} [authentication]
103
+ *
104
+ * @constructor
105
+ * @param {SMTPOptions} [options] instance options
106
+ */
107
+ constructor({
108
+ timeout,
109
+ host,
110
+ user,
111
+ password,
112
+ domain,
113
+ port,
114
+ ssl,
115
+ tls,
116
+ authentication,
117
+ } = {}) {
118
+ super();
119
+
120
+ /**
121
+ * @private
122
+ * @type {number}
123
+ */
124
+ this._state = SMTPState.NOTCONNECTED;
125
+
126
+ /**
127
+ * @private
128
+ * @type {boolean}
129
+ */
130
+ this._secure = false;
131
+
132
+ /**
133
+ * @type {Socket|TLSSocket}
134
+ */
135
+ this.sock = null;
136
+
137
+ /**
138
+ * @type {{ [i: string]: string | boolean }}
139
+ */
140
+ this.features = null;
141
+
142
+ /**
143
+ * @type {SMTPResponse.SMTPResponse}
144
+ */
145
+ this.monitor = null;
146
+
147
+ /**
148
+ * @type {string[]}
149
+ */
150
+ this.authentication = Array.isArray(authentication)
151
+ ? authentication
152
+ : [
153
+ AUTH_METHODS.CRAM_MD5,
154
+ AUTH_METHODS.LOGIN,
155
+ AUTH_METHODS.PLAIN,
156
+ AUTH_METHODS.XOAUTH2,
157
+ ];
158
+
159
+ /**
160
+ * @type {number} }
161
+ */
162
+ this.timeout = typeof timeout === 'number' ? timeout : TIMEOUT;
163
+
164
+ /**
165
+ * @type {string} }
166
+ */
167
+ this.domain = typeof domain === 'string' ? domain : hostname();
168
+
169
+ /**
170
+ * @type {string} }
171
+ */
172
+ this.host = typeof host === 'string' ? host : 'localhost';
173
+
174
+ /**
175
+ * @type {boolean|SMTPSocketOptions}
176
+ */
177
+ this.ssl =
178
+ ssl != null &&
179
+ (typeof ssl === 'boolean' ||
180
+ (typeof ssl === 'object' && Array.isArray(ssl) === false))
181
+ ? ssl
182
+ : false;
183
+
184
+ /**
185
+ * @type {boolean|SMTPSocketOptions}
186
+ */
187
+ this.tls =
188
+ tls != null &&
189
+ (typeof tls === 'boolean' ||
190
+ (typeof tls === 'object' && Array.isArray(tls) === false))
191
+ ? tls
192
+ : false;
193
+
194
+ /**
195
+ * @type {number}
196
+ */
197
+ this.port = port || (ssl ? SMTP_SSL_PORT : tls ? SMTP_TLS_PORT : SMTP_PORT);
198
+
199
+ /**
200
+ * @type {boolean}
201
+ */
202
+ this.loggedin = user && password ? false : true;
203
+
204
+ // keep these strings hidden when quicky debugging/logging
205
+ this.user = /** @returns {string} */ () => user;
206
+ this.password = /** @returns {string} */ () => password;
207
+ }
208
+
209
+ /**
210
+ * @param {0 | 1} level -
211
+ * @returns {void}
212
+ */
213
+ debug(level) {
214
+ DEBUG = level;
215
+ }
216
+
217
+ /**
218
+ * @returns {number} the current state
219
+ */
220
+ state() {
221
+ return this._state;
222
+ }
223
+
224
+ /**
225
+ * @returns {boolean} whether or not the instance is authorized
226
+ */
227
+ authorized() {
228
+ return this.loggedin;
229
+ }
230
+
231
+ /**
232
+ * @typedef {Object} ConnectOptions
233
+ * @property {boolean} [ssl]
234
+ *
235
+ * @param {function(...*): void} callback function to call after response
236
+ * @param {number} [port] the port to use for the connection
237
+ * @param {string} [host] the hostname to use for the connection
238
+ * @param {ConnectOptions} [options={}] the options
239
+ * @returns {void}
240
+ */
241
+ connect(callback, port = this.port, host = this.host, options = {}) {
242
+ this.port = port;
243
+ this.host = host;
244
+ this.ssl = options.ssl || this.ssl;
245
+
246
+ if (this._state !== SMTPState.NOTCONNECTED) {
247
+ this.quit(() =>
248
+ this.connect(
249
+ callback,
250
+ port,
251
+ host,
252
+ options
253
+ )
254
+ );
255
+ }
256
+
257
+ /**
258
+ * @returns {void}
259
+ */
260
+ const connected = () => {
261
+ log(`connected: ${this.host}:${this.port}`);
262
+
263
+ if (this.ssl && !this.tls) {
264
+ // if key/ca/cert was passed in, check if connection is authorized
265
+ if (
266
+ typeof this.ssl !== 'boolean' &&
267
+ this.sock instanceof TLSSocket &&
268
+ !this.sock.authorized
269
+ ) {
270
+ this.close(true);
271
+ caller(
272
+ callback,
273
+ SMTPError(
274
+ 'could not establish an ssl connection',
275
+ SMTPError.CONNECTIONAUTH
276
+ )
277
+ );
278
+ } else {
279
+ this._secure = true;
280
+ }
281
+ }
282
+ };
283
+
284
+ /**
285
+ * @param {Error} err err
286
+ * @returns {void}
287
+ */
288
+ const connectedErrBack = err => {
289
+ if (!err) {
290
+ connected();
291
+ } else {
292
+ this.close(true);
293
+ caller(
294
+ callback,
295
+ SMTPError('could not connect', SMTPError.COULDNOTCONNECT, err)
296
+ );
297
+ }
298
+ };
299
+
300
+ const response = (err, msg) => {
301
+ if (err) {
302
+ if (this._state === SMTPState.NOTCONNECTED && !this.sock) {
303
+ return;
304
+ }
305
+ this.close(true);
306
+ caller(callback, err);
307
+ } else if (msg.code == '220') {
308
+ log(msg.data);
309
+
310
+ // might happen first, so no need to wait on connected()
311
+ this._state = SMTPState.CONNECTED;
312
+ caller(callback, null, msg.data);
313
+ } else {
314
+ log(`response (data): ${msg.data}`);
315
+ this.quit(() => {
316
+ caller(
317
+ callback,
318
+ SMTPError(
319
+ 'bad response on connection',
320
+ SMTPError.BADRESPONSE,
321
+ err,
322
+ msg.data
323
+ )
324
+ );
325
+ });
326
+ }
327
+ };
328
+
329
+ this._state = SMTPState.CONNECTING;
330
+ log(`connecting: ${this.host}:${this.port}`);
331
+
332
+ if (this.ssl) {
333
+ this.sock = connect(
334
+ this.port,
335
+ this.host,
336
+ typeof this.ssl === 'object' ? this.ssl : {},
337
+ connected
338
+ );
339
+ } else {
340
+ this.sock = new Socket();
341
+ this.sock.connect(
342
+ this.port,
343
+ this.host,
344
+ connectedErrBack
345
+ );
346
+ }
347
+
348
+ this.monitor = SMTPResponse.monitor(this.sock, this.timeout, () =>
349
+ this.close(true)
350
+ );
351
+ this.sock.once('response', response);
352
+ this.sock.once('error', response); // the socket could reset or throw, so let's handle it and let the user know
353
+ }
354
+
355
+ /**
356
+ * @param {string} str the string to send
357
+ * @param {*} callback function to call after response
358
+ * @returns {void}
359
+ */
360
+ send(str, callback) {
361
+ if (this.sock && this._state === SMTPState.CONNECTED) {
362
+ log(str);
363
+
364
+ this.sock.once('response', (err, msg) => {
365
+ if (err) {
366
+ caller(callback, err);
367
+ } else {
368
+ log(msg.data);
369
+ caller(callback, null, msg);
370
+ }
371
+ });
372
+ this.sock.write(str);
373
+ } else {
374
+ this.close(true);
375
+ caller(
376
+ callback,
377
+ SMTPError('no connection has been established', SMTPError.NOCONNECTION)
378
+ );
379
+ }
380
+ }
381
+
382
+ /**
383
+ * @param {string} cmd command to issue
384
+ * @param {function(...*): void} callback function to call after response
385
+ * @param {(number[] | number)} [codes=[250]] array codes
386
+ * @returns {void}
387
+ */
388
+ command(cmd, callback, codes = [250]) {
389
+ const codesArray = Array.isArray(codes)
390
+ ? codes
391
+ : typeof codes === 'number'
392
+ ? [codes]
393
+ : [250];
394
+
395
+ const response = (err, msg) => {
396
+ if (err) {
397
+ caller(callback, err);
398
+ } else {
399
+ if (codesArray.indexOf(Number(msg.code)) !== -1) {
400
+ caller(callback, err, msg.data, msg.message);
401
+ } else {
402
+ const suffix = msg.message ? `: ${msg.message}` : '';
403
+ const errorMessage = `bad response on command '${
404
+ cmd.split(' ')[0]
405
+ }'${suffix}`;
406
+ caller(
407
+ callback,
408
+ SMTPError(errorMessage, SMTPError.BADRESPONSE, null, msg.data)
409
+ );
410
+ }
411
+ }
412
+ };
413
+
414
+ this.send(cmd + CRLF, response);
415
+ }
416
+
417
+ /**
418
+ * SMTP 'helo' command.
419
+ *
420
+ * Hostname to send for self command defaults to the FQDN of the local
421
+ * host.
422
+ *
423
+ * @param {function(...*): void} callback function to call after response
424
+ * @param {string} domain the domain to associate with the 'helo' request
425
+ * @returns {void}
426
+ */
427
+ helo(callback, domain) {
428
+ this.command(`helo ${domain || this.domain}`, (err, data) => {
429
+ if (err) {
430
+ caller(callback, err);
431
+ } else {
432
+ this.parse_smtp_features(data);
433
+ caller(callback, err, data);
434
+ }
435
+ });
436
+ }
437
+
438
+ /**
439
+ * @param {function(...*): void} callback function to call after response
440
+ * @returns {void}
441
+ */
442
+ starttls(callback) {
443
+ const response = (err, msg) => {
444
+ if (err) {
445
+ err.message += ' while establishing a starttls session';
446
+ caller(callback, err);
447
+ } else {
448
+ const secureContext = createSecureContext(
449
+ typeof this.tls === 'object' ? this.tls : {}
450
+ );
451
+ const secureSocket = new TLSSocket(this.sock, { secureContext });
452
+
453
+ secureSocket.on('error', err => {
454
+ this.close(true);
455
+ caller(callback, err);
456
+ });
457
+
458
+ this._secure = true;
459
+ this.sock = secureSocket;
460
+
461
+ SMTPResponse.monitor(this.sock, this.timeout, () => this.close(true));
462
+ caller(callback, msg.data);
463
+ }
464
+ };
465
+
466
+ this.command('starttls', response, [220]);
467
+ }
468
+
469
+ /**
470
+ * @param {string} data the string to parse for features
471
+ * @returns {void}
472
+ */
473
+ parse_smtp_features(data) {
474
+ // According to RFC1869 some (badly written)
475
+ // MTA's will disconnect on an ehlo. Toss an exception if
476
+ // that happens -ddm
477
+
478
+ data.split('\n').forEach(ext => {
479
+ const parse = ext.match(/^(?:\d+[-=]?)\s*?([^\s]+)(?:\s+(.*)\s*?)?$/);
480
+
481
+ // To be able to communicate with as many SMTP servers as possible,
482
+ // we have to take the old-style auth advertisement into account,
483
+ // because:
484
+ // 1) Else our SMTP feature parser gets confused.
485
+ // 2) There are some servers that only advertise the auth methods we
486
+ // support using the old style.
487
+
488
+ if (parse != null) {
489
+ // RFC 1869 requires a space between ehlo keyword and parameters.
490
+ // It's actually stricter, in that only spaces are allowed between
491
+ // parameters, but were not going to check for that here. Note
492
+ // that the space isn't present if there are no parameters.
493
+ this.features[parse[1].toLowerCase()] = parse[2] || true;
494
+ }
495
+ });
496
+ }
497
+
498
+ /**
499
+ * @param {function(...*): void} callback function to call after response
500
+ * @param {string} domain the domain to associate with the 'ehlo' request
501
+ * @returns {void}
502
+ */
503
+ ehlo(callback, domain) {
504
+ this.features = {};
505
+ this.command(`ehlo ${domain || this.domain}`, (err, data) => {
506
+ if (err) {
507
+ caller(callback, err);
508
+ } else {
509
+ this.parse_smtp_features(data);
510
+
511
+ if (this.tls && !this._secure) {
512
+ this.starttls(() => this.ehlo(callback, domain));
513
+ } else {
514
+ caller(callback, err, data);
515
+ }
516
+ }
517
+ });
518
+ }
519
+
520
+ /**
521
+ * @param {string} opt the features keyname to check
522
+ * @returns {boolean} whether the extension exists
523
+ */
524
+ has_extn(opt) {
525
+ return this.features[opt.toLowerCase()] === undefined;
526
+ }
527
+
528
+ /**
529
+ * SMTP 'help' command, returns text from the server
530
+ * @param {function(...*): void} callback function to call after response
531
+ * @param {string} domain the domain to associate with the 'help' request
532
+ * @returns {void}
533
+ */
534
+ help(callback, domain) {
535
+ this.command(domain ? `help ${domain}` : 'help', callback, [211, 214]);
536
+ }
537
+
538
+ /**
539
+ * @param {function(...*): void} callback function to call after response
540
+ * @returns {void}
541
+ */
542
+ rset(callback) {
543
+ this.command('rset', callback);
544
+ }
545
+
546
+ /**
547
+ * @param {function(...*): void} callback function to call after response
548
+ * @returns {void}
549
+ */
550
+ noop(callback) {
551
+ this.send('noop', callback);
552
+ }
553
+
554
+ /**
555
+ * @param {function(...*): void} callback function to call after response
556
+ * @param {string} from the sender
557
+ * @returns {void}
558
+ */
559
+ mail(callback, from) {
560
+ this.command(`mail FROM:${from}`, callback);
561
+ }
562
+
563
+ /**
564
+ * @param {function(...*): void} callback function to call after response
565
+ * @param {string} to the receiver
566
+ * @returns {void}
567
+ */
568
+ rcpt(callback, to) {
569
+ this.command(`RCPT TO:${to}`, callback, [250, 251]);
570
+ }
571
+
572
+ /**
573
+ * @param {function(...*): void} callback function to call after response
574
+ * @returns {void}
575
+ */
576
+ data(callback) {
577
+ this.command('data', callback, [354]);
578
+ }
579
+
580
+ /**
581
+ * @param {function(...*): void} callback function to call after response
582
+ * @returns {void}
583
+ */
584
+ data_end(callback) {
585
+ this.command(`${CRLF}.`, callback);
586
+ }
587
+
588
+ /**
589
+ * @param {string} data the message to send
590
+ * @returns {void}
591
+ */
592
+ message(data) {
593
+ log(data);
594
+ this.sock.write(data);
595
+ }
596
+
597
+ /**
598
+ * SMTP 'verify' command -- checks for address validity.
599
+ *
600
+ * @param {string} address the address to validate
601
+ * @param {function(...*): void} callback function to call after response
602
+ * @returns {void}
603
+ */
604
+ verify(address, callback) {
605
+ this.command(`vrfy ${address}`, callback, [250, 251, 252]);
606
+ }
607
+
608
+ /**
609
+ * SMTP 'expn' command -- expands a mailing list.
610
+ *
611
+ * @param {string} address the mailing list to expand
612
+ * @param {function(...*): void} callback function to call after response
613
+ * @returns {void}
614
+ */
615
+ expn(address, callback) {
616
+ this.command(`expn ${address}`, callback);
617
+ }
618
+
619
+ /**
620
+ * Calls this.ehlo() and, if an error occurs, this.helo().
621
+ *
622
+ * If there has been no previous EHLO or HELO command self session, self
623
+ * method tries ESMTP EHLO first.
624
+ *
625
+ * @param {function(...*): void} callback function to call after response
626
+ * @param {string} [domain] the domain to associate with the command
627
+ * @returns {void}
628
+ */
629
+ ehlo_or_helo_if_needed(callback, domain) {
630
+ // is this code callable...?
631
+ if (!this.features) {
632
+ const response = (err, data) => caller(callback, err, data);
633
+ this.ehlo((err, data) => {
634
+ if (err) {
635
+ this.helo(response, domain);
636
+ } else {
637
+ caller(callback, err, data);
638
+ }
639
+ }, domain);
640
+ }
641
+ }
642
+
643
+ /**
644
+ * Log in on an SMTP server that requires authentication.
645
+ *
646
+ * If there has been no previous EHLO or HELO command self session, self
647
+ * method tries ESMTP EHLO first.
648
+ *
649
+ * This method will return normally if the authentication was successful.
650
+ *
651
+ * @param {function(...*): void} callback function to call after response
652
+ * @param {string} [user] the username to authenticate with
653
+ * @param {string} [password] the password for the authentication
654
+ * @param {{ method: string, domain: string }} [options] login options
655
+ * @returns {void}
656
+ */
657
+ login(callback, user, password, options) {
658
+ const login = {
659
+ user: user ? () => user : this.user,
660
+ password: password ? () => password : this.password,
661
+ method: options && options.method ? options.method.toUpperCase() : '',
662
+ };
663
+
664
+ const domain = options && options.domain ? options.domain : this.domain;
665
+
666
+ const initiate = (err, data) => {
667
+ if (err) {
668
+ caller(callback, err);
669
+ return;
670
+ }
671
+
672
+ let method = null;
673
+
674
+ /**
675
+ * @param {string} challenge challenge
676
+ * @returns {string} base64 cram hash
677
+ */
678
+ const encode_cram_md5 = challenge => {
679
+ const hmac = createHmac('md5', login.password());
680
+ hmac.update(Buffer.from(challenge, 'base64').toString('ascii'));
681
+ return Buffer.from(`${login.user()} ${hmac.digest('hex')}`).toString(
682
+ 'base64'
683
+ );
684
+ };
685
+
686
+ /**
687
+ * @returns {string} base64 login/password
688
+ */
689
+ const encode_plain = () =>
690
+ Buffer.from(`\u0000${login.user()}\u0000${login.password()}`).toString(
691
+ 'base64'
692
+ );
693
+
694
+ /**
695
+ * @see https://developers.google.com/gmail/xoauth2_protocol
696
+ * @returns {string} base64 xoauth2 auth token
697
+ */
698
+ const encode_xoauth2 = () =>
699
+ Buffer.from(
700
+ `user=${login.user()}\u0001auth=Bearer ${login.password()}\u0001\u0001`
701
+ ).toString('base64');
702
+
703
+ // List of authentication methods we support: from preferred to
704
+ // less preferred methods.
705
+ if (!method) {
706
+ const preferred = this.authentication;
707
+ let auth = '';
708
+
709
+ if (this.features && this.features.auth) {
710
+ if (typeof this.features.auth === 'string') {
711
+ auth = this.features.auth;
712
+ }
713
+ }
714
+
715
+ for (let i = 0; i < preferred.length; i++) {
716
+ if (auth.includes(preferred[i])) {
717
+ method = preferred[i];
718
+ break;
719
+ }
720
+ }
721
+ }
722
+
723
+ /**
724
+ * handle bad responses from command differently
725
+ * @param {Error} err err
726
+ * @param {*} data data
727
+ * @returns {void}
728
+ */
729
+ const failed = (err, data) => {
730
+ this.loggedin = false;
731
+ this.close(); // if auth is bad, close the connection, it won't get better by itself
732
+ caller(
733
+ callback,
734
+ SMTPError('authorization.failed', SMTPError.AUTHFAILED, err, data)
735
+ );
736
+ };
737
+
738
+ /**
739
+ * @param {Error} err err
740
+ * @param {*} data data
741
+ * @returns {void}
742
+ */
743
+ const response = (err, data) => {
744
+ if (err) {
745
+ failed(err, data);
746
+ } else {
747
+ this.loggedin = true;
748
+ caller(callback, err, data);
749
+ }
750
+ };
751
+
752
+ /**
753
+ * @param {Error} err err
754
+ * @param {*} data data
755
+ * @param {string} msg msg
756
+ * @returns {void}
757
+ */
758
+ const attempt = (err, data, msg) => {
759
+ if (err) {
760
+ failed(err, data);
761
+ } else {
762
+ if (method === AUTH_METHODS.CRAM_MD5) {
763
+ this.command(encode_cram_md5(msg), response, [235, 503]);
764
+ } else if (method === AUTH_METHODS.LOGIN) {
765
+ this.command(
766
+ Buffer.from(login.password()).toString('base64'),
767
+ response,
768
+ [235, 503]
769
+ );
770
+ }
771
+ }
772
+ };
773
+
774
+ /**
775
+ * @param {Error} err err
776
+ * @param {*} data data
777
+ * @param {string} msg msg
778
+ * @returns {void}
779
+ */
780
+ const attempt_user = (err, data, msg) => {
781
+ if (err) {
782
+ failed(err, data);
783
+ } else {
784
+ if (method === AUTH_METHODS.LOGIN) {
785
+ this.command(
786
+ Buffer.from(login.user()).toString('base64'),
787
+ attempt,
788
+ [334]
789
+ );
790
+ }
791
+ }
792
+ };
793
+
794
+ switch (method) {
795
+ case AUTH_METHODS.CRAM_MD5:
796
+ this.command(`AUTH ${AUTH_METHODS.CRAM_MD5}`, attempt, [334]);
797
+ break;
798
+ case AUTH_METHODS.LOGIN:
799
+ this.command(`AUTH ${AUTH_METHODS.LOGIN}`, attempt_user, [334]);
800
+ break;
801
+ case AUTH_METHODS.PLAIN:
802
+ this.command(
803
+ `AUTH ${AUTH_METHODS.PLAIN} ${encode_plain()}`,
804
+ response,
805
+ [235, 503]
806
+ );
807
+ break;
808
+ case AUTH_METHODS.XOAUTH2:
809
+ this.command(
810
+ `AUTH ${AUTH_METHODS.XOAUTH2} ${encode_xoauth2()}`,
811
+ response,
812
+ [235, 503]
813
+ );
814
+ break;
815
+ default:
816
+ const msg = 'no form of authorization supported';
817
+ const err = SMTPError(msg, SMTPError.AUTHNOTSUPPORTED, null, data);
818
+ caller(callback, err);
819
+ break;
820
+ }
821
+ };
822
+
823
+ this.ehlo_or_helo_if_needed(initiate, domain);
824
+ }
825
+
826
+ /**
827
+ * @param {boolean} [force=false] whether or not to force destroy the connection
828
+ * @returns {void}
829
+ */
830
+ close(force = false) {
831
+ if (this.sock) {
832
+ if (force) {
833
+ log('smtp connection destroyed!');
834
+ this.sock.destroy();
835
+ } else {
836
+ log('smtp connection closed.');
837
+ this.sock.end();
838
+ }
839
+ }
840
+
841
+ if (this.monitor) {
842
+ this.monitor.stop();
843
+ this.monitor = null;
844
+ }
845
+
846
+ this._state = SMTPState.NOTCONNECTED;
847
+ this._secure = false;
848
+ this.sock = null;
849
+ this.features = null;
850
+ this.loggedin = !(this.user() && this.password());
851
+ }
852
+
853
+ /**
854
+ * @param {function(...*): void} [callback] function to call after response
855
+ * @returns {void}
856
+ */
857
+ quit(callback) {
858
+ this.command(
859
+ 'quit',
860
+ (err, data) => {
861
+ caller(callback, err, data);
862
+ this.close();
863
+ },
864
+ [221, 250]
865
+ );
866
+ }
585
867
  }
586
868
 
587
869
  exports.SMTP = SMTP;
588
870
  exports.state = SMTPState;
589
871
  exports.authentication = AUTH_METHODS;
872
+ exports.DEFAULT_TIMEOUT = TIMEOUT;