emailjs 5.0.5 → 6.0.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.
Files changed (71) hide show
  1. package/README.md +10 -5
  2. package/dist/auth-admission.d.ts +13 -0
  3. package/dist/auth-admission.js +112 -0
  4. package/dist/auth-admission.js.map +1 -0
  5. package/dist/auth-admission.test.d.ts +1 -0
  6. package/dist/auth-admission.test.js +51 -0
  7. package/dist/auth-admission.test.js.map +1 -0
  8. package/dist/auth.integration.test.js +1 -3
  9. package/dist/auth.integration.test.js.map +1 -1
  10. package/dist/client.auth-interruption.integration.test.d.ts +1 -0
  11. package/dist/client.auth-interruption.integration.test.js +152 -0
  12. package/dist/client.auth-interruption.integration.test.js.map +1 -0
  13. package/dist/client.auth-starttls.integration.test.d.ts +1 -0
  14. package/dist/client.auth-starttls.integration.test.js +58 -0
  15. package/dist/client.auth-starttls.integration.test.js.map +1 -0
  16. package/dist/client.d.ts +9 -7
  17. package/dist/client.data-ownership.test.d.ts +1 -0
  18. package/dist/client.data-ownership.test.js +221 -0
  19. package/dist/client.data-ownership.test.js.map +1 -0
  20. package/dist/client.integration.test.js +161 -21
  21. package/dist/client.integration.test.js.map +1 -1
  22. package/dist/client.js +88 -84
  23. package/dist/client.js.map +1 -1
  24. package/dist/client.test.js +177 -138
  25. package/dist/client.test.js.map +1 -1
  26. package/dist/connection.auth-ownership.test.d.ts +1 -0
  27. package/dist/connection.auth-ownership.test.js +474 -0
  28. package/dist/connection.auth-ownership.test.js.map +1 -0
  29. package/dist/connection.body-ownership.test.d.ts +1 -0
  30. package/dist/connection.body-ownership.test.js +73 -0
  31. package/dist/connection.body-ownership.test.js.map +1 -0
  32. package/dist/connection.cached-login.test.d.ts +1 -0
  33. package/dist/connection.cached-login.test.js +290 -0
  34. package/dist/connection.cached-login.test.js.map +1 -0
  35. package/dist/connection.d.ts +18 -7
  36. package/dist/connection.errors.integration.test.js +86 -32
  37. package/dist/connection.errors.integration.test.js.map +1 -1
  38. package/dist/connection.greeting-ownership.test.d.ts +1 -0
  39. package/dist/connection.greeting-ownership.test.js +76 -0
  40. package/dist/connection.greeting-ownership.test.js.map +1 -0
  41. package/dist/connection.integration.test.js +108 -41
  42. package/dist/connection.integration.test.js.map +1 -1
  43. package/dist/connection.js +312 -188
  44. package/dist/connection.js.map +1 -1
  45. package/dist/connection.login-boundaries.test.d.ts +1 -0
  46. package/dist/connection.login-boundaries.test.js +151 -0
  47. package/dist/connection.login-boundaries.test.js.map +1 -0
  48. package/dist/connection.test.js +74 -8
  49. package/dist/connection.test.js.map +1 -1
  50. package/dist/message.integration.test.js +2 -5
  51. package/dist/message.integration.test.js.map +1 -1
  52. package/dist/response.js +19 -20
  53. package/dist/response.js.map +1 -1
  54. package/dist/response.test.js +17 -2
  55. package/dist/response.test.js.map +1 -1
  56. package/dist/smtp-auth.d.ts +13 -0
  57. package/dist/smtp-auth.js +40 -0
  58. package/dist/smtp-auth.js.map +1 -0
  59. package/dist/smtp-data.d.ts +18 -0
  60. package/dist/smtp-data.js +75 -0
  61. package/dist/smtp-data.js.map +1 -0
  62. package/dist/smtp-session.d.ts +7 -0
  63. package/dist/smtp-session.js +18 -0
  64. package/dist/smtp-session.js.map +1 -0
  65. package/dist/smtp-transport.d.ts +31 -0
  66. package/dist/smtp-transport.js +143 -0
  67. package/dist/smtp-transport.js.map +1 -0
  68. package/dist/tls-upgrade.d.ts +5 -0
  69. package/dist/tls-upgrade.js +30 -0
  70. package/dist/tls-upgrade.js.map +1 -0
  71. package/package.json +1 -1
@@ -1,16 +1,15 @@
1
- import { createHmac } from 'crypto';
2
1
  import { EventEmitter } from 'events';
3
2
  import { Socket } from 'net';
4
3
  import { hostname } from 'os';
5
- import { connect, createSecureContext, TLSSocket } from 'tls';
4
+ import { connect, TLSSocket } from 'tls';
6
5
  import { SMTPError, SMTPErrorStates } from './error.js';
6
+ import { DataTransfer } from './smtp-data.js';
7
7
  import { SMTPResponseMonitor } from './response.js';
8
- export const AUTH_METHODS = {
9
- PLAIN: 'PLAIN',
10
- 'CRAM-MD5': 'CRAM-MD5',
11
- LOGIN: 'LOGIN',
12
- XOAUTH2: 'XOAUTH2',
13
- };
8
+ import { startSession, endSession } from './smtp-session.js';
9
+ import { SmtpTransport } from './smtp-transport.js';
10
+ import { startTlsHandshake } from './tls-upgrade.js';
11
+ import { AUTH_METHODS, authenticateWith, selectAuthMethod, } from './smtp-auth.js';
12
+ export { AUTH_METHODS };
14
13
  export const SMTPState = {
15
14
  NOTCONNECTED: 0,
16
15
  CONNECTING: 1,
@@ -37,6 +36,13 @@ const caller = (callback, ...args) => {
37
36
  callback(...args);
38
37
  }
39
38
  };
39
+ const mailFrom = (path) => `mail FROM:${path}`;
40
+ const rcptTo = (path) => `RCPT TO:${path}`;
41
+ // A relay rejection is still a reply. Preserve transport errors such as timeouts.
42
+ function isRelayReply(err) {
43
+ return (!err ||
44
+ (err instanceof SMTPError && err.code === SMTPErrorStates.BADRESPONSE));
45
+ }
40
46
  export class SMTPConnection extends EventEmitter {
41
47
  user;
42
48
  password;
@@ -59,7 +65,24 @@ export class SMTPConnection extends EventEmitter {
59
65
  ssl = false;
60
66
  tls = false;
61
67
  port;
62
- greylistResponseTracker = new WeakSet();
68
+ activeTransport = null;
69
+ get transport() {
70
+ // Subclasses can replace sock directly instead of calling connect().
71
+ if (this.sock !== (this.activeTransport?.socket ?? null))
72
+ this.resetTransport(this.sock);
73
+ return this.activeTransport;
74
+ }
75
+ resetTransport(socket) {
76
+ // A new socket has none of its predecessor's capabilities, TLS status, or login status.
77
+ this.features = null;
78
+ this._secure = false;
79
+ this.loggedin = !(this.user() && this.password());
80
+ this.activeTransport = socket
81
+ ? new SmtpTransport(socket, (entry) => this.log(entry), (owner) => this.activeTransport === owner && this.sock === socket, (verb) => {
82
+ this.features = verb === 'HELO' ? {} : null;
83
+ })
84
+ : null;
85
+ }
63
86
  constructor({ timeout, host, user, password, domain, port, ssl, tls, logger, authentication, } = {}) {
64
87
  super();
65
88
  if (Array.isArray(authentication)) {
@@ -93,7 +116,8 @@ export class SMTPConnection extends EventEmitter {
93
116
  this.user = () => user;
94
117
  this.password = () => password;
95
118
  if (typeof logger === 'function') {
96
- this.log = logger;
119
+ // A logger receives entries, not the live connection as its receiver.
120
+ this.log = logger.bind(undefined);
97
121
  }
98
122
  }
99
123
  debug(level) {
@@ -103,17 +127,25 @@ export class SMTPConnection extends EventEmitter {
103
127
  return this._state;
104
128
  }
105
129
  authorized() {
106
- return this.loggedin;
130
+ const transport = this.transport;
131
+ return transport
132
+ ? transport.isAuthenticated || this.loggedin
133
+ : !(this.user() && this.password());
107
134
  }
108
135
  connect(callback, port = this.port, host = this.host, options = {}) {
109
136
  this.port = port;
110
137
  this.host = host;
111
138
  this.ssl = options.ssl || this.ssl;
112
139
  if (this._state !== SMTPState.NOTCONNECTED) {
113
- this.quit(() => this.connect(callback, port, host, options));
140
+ return this.quit(() => this.connect(callback, port, host, options));
114
141
  }
142
+ const interrupted = () => caller(callback, SMTPError.create('connection closed during greeting', SMTPErrorStates.CONNECTIONCLOSED));
115
143
  const connected = () => {
144
+ if (this.sock !== socket)
145
+ return;
116
146
  this.log(`connected: ${this.host}:${this.port}`);
147
+ if (this.sock !== socket)
148
+ return;
117
149
  if (this.ssl && !this.tls) {
118
150
  // if key/ca/cert was passed in, check if connection is authorized
119
151
  if (typeof this.ssl !== 'boolean' &&
@@ -122,7 +154,7 @@ export class SMTPConnection extends EventEmitter {
122
154
  // oxlint-disable-next-line typescript/no-explicit-any
123
155
  this.ssl.rejectUnauthorized !== false) {
124
156
  this.close(true);
125
- caller(callback, SMTPError.create('could not establish an ssl connection', SMTPErrorStates.CONNECTIONAUTH));
157
+ failGreeting?.(SMTPError.create('could not establish an ssl connection', SMTPErrorStates.CONNECTIONAUTH));
126
158
  }
127
159
  else {
128
160
  this._secure = true;
@@ -130,21 +162,19 @@ export class SMTPConnection extends EventEmitter {
130
162
  }
131
163
  };
132
164
  const connectedErrBack = (err) => {
165
+ if (this.sock !== socket)
166
+ return;
133
167
  if (!err) {
134
168
  connected();
135
169
  }
136
170
  else {
137
171
  this.close(true);
138
172
  this.log(err);
139
- caller(callback, SMTPError.create('could not connect', SMTPErrorStates.COULDNOTCONNECT, err));
173
+ failGreeting?.(SMTPError.create('could not connect', SMTPErrorStates.COULDNOTCONNECT, err));
140
174
  }
141
175
  };
142
176
  const response = (err, data, message) => {
143
177
  if (err) {
144
- if (this._state === SMTPState.NOTCONNECTED && !this.sock) {
145
- return;
146
- }
147
- this.close(true);
148
178
  caller(callback, err);
149
179
  }
150
180
  else {
@@ -156,46 +186,57 @@ export class SMTPConnection extends EventEmitter {
156
186
  };
157
187
  if (msg.code == '220') {
158
188
  this.log(msg.data);
189
+ if (this.sock !== socket)
190
+ return interrupted();
159
191
  // might happen first, so no need to wait on connected()
160
192
  this._state = SMTPState.CONNECTED;
161
193
  caller(callback, null, msg.data);
162
194
  }
163
195
  else {
164
196
  this.log(`response (data): ${msg.data}`);
165
- this.quit(() => {
166
- caller(callback, SMTPError.create('bad response on connection', SMTPErrorStates.BADRESPONSE, err, msg.data));
167
- });
197
+ const rejected = () => caller(callback, SMTPError.create('bad response on connection', SMTPErrorStates.BADRESPONSE, err, msg.data));
198
+ if (this.sock === socket)
199
+ this.quit(rejected);
200
+ else
201
+ rejected();
168
202
  }
169
203
  }
170
204
  };
205
+ let socket = this.sock;
171
206
  this._state = SMTPState.CONNECTING;
172
207
  this.log(`connecting: ${this.host}:${this.port}`);
173
- if (this.ssl) {
174
- this.sock = connect(this.port, this.host.trim(), typeof this.ssl === 'object' ? this.ssl : {}, connected);
208
+ if (this._state !== SMTPState.CONNECTING || this.sock !== socket)
209
+ return interrupted();
210
+ let transport;
211
+ try {
212
+ if (this.ssl) {
213
+ socket = connect(this.port, this.host.trim(), typeof this.ssl === 'object' ? this.ssl : {}, connected);
214
+ this.sock = socket;
215
+ }
216
+ else {
217
+ socket = new Socket();
218
+ this.sock = socket;
219
+ socket.connect(this.port, this.host.trim(), connectedErrBack);
220
+ }
221
+ this.resetTransport(socket);
222
+ transport = this.activeTransport;
223
+ startSession(this);
224
+ this.watchSmtpReplies(socket);
175
225
  }
176
- else {
177
- this.sock = new Socket();
178
- this.sock.connect(this.port, this.host.trim(), connectedErrBack);
226
+ catch (err) {
227
+ // Invalid dial or timeout options can fail before any reply listener exists.
228
+ if (this.sock === socket)
229
+ this.close(true);
230
+ return caller(callback, err);
179
231
  }
180
- this.monitor = new SMTPResponseMonitor(this.sock, this.timeout, () => this.close(true));
181
- this.sock.once('response', response);
182
- this.sock.once('error', response); // the socket could reset or throw, so let's handle it and let the user know
232
+ const failGreeting = transport.waitForReply(response);
233
+ if (!failGreeting)
234
+ interrupted();
183
235
  }
184
236
  send(str, callback) {
185
- if (this.sock != null && this._state === SMTPState.CONNECTED) {
186
- this.log(str);
187
- this.sock.once('response', (err, data, message) => {
188
- if (err) {
189
- caller(callback, err);
190
- }
191
- else {
192
- this.log(data);
193
- caller(callback, null, data, message);
194
- }
195
- });
196
- if (this.sock.writable) {
197
- this.sock.write(str);
198
- }
237
+ if (this.transport && this._state === SMTPState.CONNECTED) {
238
+ if (!this.transport.trySendRequest(str, (err, ...rest) => caller(callback, err, ...rest)))
239
+ caller(callback, SMTPError.create('SMTP connection is no longer writable', SMTPErrorStates.CONNECTIONCLOSED));
199
240
  }
200
241
  else {
201
242
  this.close(true);
@@ -203,6 +244,11 @@ export class SMTPConnection extends EventEmitter {
203
244
  }
204
245
  }
205
246
  command(cmd, callback, codes = [250]) {
247
+ return this.runCommand(cmd, callback, codes);
248
+ }
249
+ runCommand(cmd, callback, codes, sendRequest = (line, onReply) => this.send(line, onReply)) {
250
+ const commandTransport = this.transport;
251
+ let greylistRetryUsed = false;
206
252
  const codesArray = Array.isArray(codes)
207
253
  ? codes
208
254
  : typeof codes === 'number'
@@ -226,11 +272,17 @@ export class SMTPConnection extends EventEmitter {
226
272
  }
227
273
  else if ((code === 450 || code === 451) &&
228
274
  msg.message?.toLowerCase().includes('greylist') &&
229
- this.greylistResponseTracker.has(response) === false) {
230
- this.greylistResponseTracker.add(response);
231
- setTimeout(() => {
232
- this.send(cmd + CRLF, response);
233
- }, GREYLIST_DELAY);
275
+ !greylistRetryUsed) {
276
+ greylistRetryUsed = true;
277
+ const retry = () => {
278
+ if (commandTransport !== this.transport)
279
+ return caller(callback, SMTPError.create('connection closed before greylist retry', SMTPErrorStates.CONNECTIONCLOSED));
280
+ sendRequest(cmd + CRLF, response);
281
+ };
282
+ if (commandTransport)
283
+ commandTransport.retryAfter(GREYLIST_DELAY, retry);
284
+ else
285
+ setTimeout(retry, GREYLIST_DELAY);
234
286
  }
235
287
  else {
236
288
  const suffix = msg.message ? `: ${msg.message}` : '';
@@ -239,43 +291,97 @@ export class SMTPConnection extends EventEmitter {
239
291
  }
240
292
  }
241
293
  };
242
- this.greylistResponseTracker.delete(response);
243
- this.send(cmd + CRLF, response);
294
+ sendRequest(cmd + CRLF, response);
244
295
  }
245
296
  helo(callback, domain) {
246
- this.command(`helo ${domain || this._domain}`, (err, data) => {
297
+ this.command(`helo ${domain || this._domain}`, this.heloReply(callback));
298
+ }
299
+ heloReply(callback) {
300
+ const socket = this.sock;
301
+ return (err, data) => {
302
+ if (socket !== this.sock && isRelayReply(err))
303
+ return caller(callback, SMTPError.create('connection closed during HELO', SMTPErrorStates.CONNECTIONCLOSED));
247
304
  if (err) {
248
305
  caller(callback, err);
249
306
  }
250
307
  else {
251
- this.parse_smtp_features(data);
308
+ // HELO does not negotiate ESMTP extensions.
309
+ this.features = {};
252
310
  caller(callback, err, data);
253
311
  }
254
- });
312
+ };
255
313
  }
256
314
  starttls(callback) {
257
- const response = (err, data) => {
258
- if (this.sock == null) {
259
- throw new Error('null socket');
315
+ const plaintextSocket = this.sock;
316
+ const onStartTlsReply = (err, reply) => {
317
+ if (!plaintextSocket || this.sock !== plaintextSocket) {
318
+ return caller(callback, err ??
319
+ SMTPError.create('connection closed before STARTTLS handshake', SMTPErrorStates.CONNECTIONCLOSED));
260
320
  }
261
321
  if (err) {
262
- err.message += ' while establishing a starttls session';
263
- caller(callback, err);
322
+ this.close(true);
323
+ return caller(callback, err);
264
324
  }
265
- else {
266
- const secureContext = createSecureContext(typeof this.tls === 'object' ? this.tls : {});
267
- const secureSocket = new TLSSocket(this.sock, { secureContext });
268
- secureSocket.on('error', (err) => {
325
+ const finishUpgrade = this.transport?.beginOperation();
326
+ this.prepareForStartTlsHandshake(plaintextSocket);
327
+ const onHandshake = (err, tlsSocket) => {
328
+ if (this.sock !== tlsSocket) {
329
+ return caller(callback, err ??
330
+ SMTPError.create('connection closed during STARTTLS handshake', SMTPErrorStates.CONNECTIONCLOSED));
331
+ }
332
+ if (err) {
269
333
  this.close(true);
270
- caller(callback, err);
334
+ return caller(callback, err);
335
+ }
336
+ this.resumeSmtpOverTls(tlsSocket);
337
+ caller(callback, null, reply);
338
+ };
339
+ try {
340
+ const tlsOptions = typeof this.tls === 'object' ? this.tls : {};
341
+ this.sock = startTlsHandshake(plaintextSocket, this.host.trim(), tlsOptions, this.timeout, (err, tlsSocket) => {
342
+ try {
343
+ onHandshake(err, tlsSocket);
344
+ }
345
+ finally {
346
+ finishUpgrade?.();
347
+ }
271
348
  });
272
- this._secure = true;
273
- this.sock = secureSocket;
274
- new SMTPResponseMonitor(this.sock, this.timeout, () => this.close(true));
275
- caller(callback, err, data);
349
+ }
350
+ catch (err) {
351
+ try {
352
+ this.close(true);
353
+ caller(callback, err);
354
+ }
355
+ finally {
356
+ finishUpgrade?.();
357
+ }
276
358
  }
277
359
  };
278
- this.command('starttls', response, [220]);
360
+ this.command('starttls', onStartTlsReply, [220]);
361
+ }
362
+ prepareForStartTlsHandshake(plaintextSocket) {
363
+ this.monitor?.stop();
364
+ this.monitor = null;
365
+ plaintextSocket.setTimeout(0);
366
+ this.features = null;
367
+ this._secure = false;
368
+ this._state = SMTPState.CONNECTING;
369
+ }
370
+ resumeSmtpOverTls(tlsSocket) {
371
+ if (this.activeTransport?.socket !== tlsSocket)
372
+ this.resetTransport(tlsSocket);
373
+ this.watchSmtpReplies(tlsSocket);
374
+ this._secure = true;
375
+ this._state = SMTPState.CONNECTED;
376
+ }
377
+ watchSmtpReplies(socket) {
378
+ this.monitor = new SMTPResponseMonitor(socket, this.timeout, () => {
379
+ if (this.sock === socket)
380
+ this.close(true);
381
+ });
382
+ }
383
+ needsStartTls() {
384
+ return Boolean(this.tls) && !this._secure;
279
385
  }
280
386
  parse_smtp_features(data) {
281
387
  // According to RFC1869 some (badly written)
@@ -298,24 +404,31 @@ export class SMTPConnection extends EventEmitter {
298
404
  });
299
405
  }
300
406
  ehlo(callback, domain) {
301
- this.features = {};
407
+ const socket = this.sock;
302
408
  this.command(`ehlo ${domain || this._domain}`, (err, data) => {
409
+ if (socket !== this.sock && isRelayReply(err)) {
410
+ return caller(callback, SMTPError.create('connection closed during EHLO', SMTPErrorStates.CONNECTIONCLOSED));
411
+ }
303
412
  if (err) {
304
- caller(callback, err);
413
+ if (this.tls && socket && this.sock === socket)
414
+ this.close(true);
415
+ return caller(callback, err);
305
416
  }
306
- else {
307
- this.parse_smtp_features(data);
308
- if (this.tls && !this._secure) {
309
- this.starttls(() => this.ehlo(callback, domain));
310
- }
311
- else {
312
- caller(callback, err, data);
313
- }
417
+ if (this.needsStartTls()) {
418
+ return this.starttls((err) => {
419
+ if (err)
420
+ caller(callback, err);
421
+ else
422
+ this.ehlo(callback, domain);
423
+ });
314
424
  }
425
+ this.features = {};
426
+ this.parse_smtp_features(data);
427
+ caller(callback, null, data);
315
428
  });
316
429
  }
317
430
  has_extn(opt) {
318
- return this.features != null && this.features[opt.toLowerCase()] != null;
431
+ return this.transport != null && this.features?.[opt.toLowerCase()] != null;
319
432
  }
320
433
  help(callback, domain) {
321
434
  this.command(domain ? `help ${domain}` : 'help', callback, [211, 214]);
@@ -324,13 +437,42 @@ export class SMTPConnection extends EventEmitter {
324
437
  this.command('rset', callback);
325
438
  }
326
439
  noop(callback) {
327
- this.send('noop', callback);
440
+ this.send('noop' + CRLF, callback);
328
441
  }
329
442
  mail(callback, from) {
330
- this.command(`mail FROM:${from}`, callback);
443
+ this.command(mailFrom(from), callback);
331
444
  }
332
445
  rcpt(callback, to) {
333
- this.command(`RCPT TO:${to}`, callback, [250, 251]);
446
+ this.command(rcptTo(to), callback, [250, 251]);
447
+ }
448
+ /** @internal Submit the whole envelope on the transport which starts MAIL. */
449
+ sendEnvelope(from, recipients, done) {
450
+ const transport = this.transport;
451
+ if (!transport || this._state !== SMTPState.CONNECTED) {
452
+ return done(SMTPError.create('no connection has been established', SMTPErrorStates.NOCONNECTION));
453
+ }
454
+ const sendOnTransport = (line, reply) => {
455
+ if (!transport.trySendRequest(line, reply)) {
456
+ reply(SMTPError.create('connection closed during envelope', SMTPErrorStates.CONNECTIONCLOSED));
457
+ }
458
+ };
459
+ const paths = recipients.values();
460
+ const nextRecipient = (err) => {
461
+ if (err) {
462
+ // RSET is cleanup on this socket, not the delivery result.
463
+ return this.runCommand('rset', () => done(err), 250, sendOnTransport);
464
+ }
465
+ const next = paths.next();
466
+ if (next.done)
467
+ return done(null);
468
+ this.runCommand(rcptTo(next.value), nextRecipient, [250, 251], sendOnTransport);
469
+ };
470
+ this.runCommand(mailFrom(from), nextRecipient, 250, sendOnTransport);
471
+ }
472
+ /** @internal Bind the client's delivery to this socket before issuing DATA. */
473
+ captureDataTransfer() {
474
+ const socket = this.sock;
475
+ return new DataTransfer(this, () => this.sock === socket);
334
476
  }
335
477
  data(callback) {
336
478
  this.command('data', callback, [354]);
@@ -339,11 +481,12 @@ export class SMTPConnection extends EventEmitter {
339
481
  this.command(`${CRLF}.`, callback);
340
482
  }
341
483
  message(data) {
342
- this.log(data);
343
- if (this.sock) {
344
- this.sock.write(data);
484
+ const transport = this.transport;
485
+ if (transport) {
486
+ transport.writeBody(data);
345
487
  }
346
488
  else {
489
+ this.log(data);
347
490
  this.log('no socket to write to');
348
491
  }
349
492
  }
@@ -355,23 +498,47 @@ export class SMTPConnection extends EventEmitter {
355
498
  }
356
499
  ehlo_or_helo_if_needed(callback, domain) {
357
500
  const domainName = domain || this._domain;
358
- if (!this.features) {
359
- const response = (err, data) => caller(callback, err, data);
360
- this.ehlo((err, data) => {
361
- if (err) {
362
- this.helo(response, domainName);
363
- }
364
- else {
365
- caller(callback, err, data);
366
- }
367
- }, domainName);
368
- }
501
+ const transport = this.transport;
502
+ if (transport &&
503
+ (this._state !== SMTPState.CONNECTED || !transport.allowsGreeting))
504
+ return caller(callback, SMTPError.create('SMTP greeting not permitted during this exchange', SMTPErrorStates.ERROR));
505
+ if (transport && this.features && !this.needsStartTls())
506
+ return caller(callback, null);
507
+ this.ehlo((err, data) => {
508
+ if (err &&
509
+ transport &&
510
+ this.transport === transport &&
511
+ this._state === SMTPState.CONNECTED &&
512
+ transport.allowsGreeting &&
513
+ !this.tls) {
514
+ return this.runCommand(`helo ${domainName}`, this.heloReply(callback), [250], (line, onReply) => {
515
+ if (!transport.trySendRequest(line, onReply, { starting: 'greeting' }))
516
+ onReply(err);
517
+ });
518
+ }
519
+ caller(callback, err, data);
520
+ }, domainName);
521
+ }
522
+ // Capture the transport once; SASL continuations and retries share this sender.
523
+ createAuthLineSender(transport, interrupted) {
524
+ let firstAuthLineSent = false;
525
+ return (request, onReply) => {
526
+ if (transport?.trySendRequest(request, onReply, {
527
+ starting: firstAuthLineSent ? undefined : 'auth',
528
+ }))
529
+ firstAuthLineSent = true;
530
+ else
531
+ interrupted();
532
+ };
369
533
  }
370
534
  login(callback, user, password, options = {}) {
371
- const login = {
535
+ const transport = this.transport;
536
+ if (transport &&
537
+ (this._state !== SMTPState.CONNECTED || !transport.allowsLogin))
538
+ return caller(callback, SMTPError.create('AUTH is not permitted in the current SMTP exchange', SMTPErrorStates.AUTHFAILED));
539
+ const credentials = {
372
540
  user: user ? () => user : this.user,
373
541
  password: password ? () => password : this.password,
374
- method: options?.method?.toUpperCase() ?? '',
375
542
  };
376
543
  const domain = options?.domain || this._domain;
377
544
  const initiate = (err, data) => {
@@ -379,112 +546,69 @@ export class SMTPConnection extends EventEmitter {
379
546
  caller(callback, err);
380
547
  return;
381
548
  }
382
- let method = null;
383
- const encodeCramMd5 = (challenge) => {
384
- const hmac = createHmac('md5', login.password());
385
- hmac.update(Buffer.from(challenge, 'base64').toString('ascii'));
386
- return Buffer.from(`${login.user()} ${hmac.digest('hex')}`).toString('base64');
387
- };
388
- const encodePlain = () => Buffer.from(`\u0000${login.user()}\u0000${login.password()}`).toString('base64');
389
- const encodeXoauth2 = () => Buffer.from(`user=${login.user()}\u0001auth=Bearer ${login.password()}\u0001\u0001`).toString('base64');
390
- // List of authentication methods we support: from preferred to
391
- // less preferred methods.
392
- if (method === null) {
393
- const preferred = this.authentication;
394
- let auth = '';
395
- if (typeof this.features?.['auth'] === 'string') {
396
- auth = this.features['auth'];
397
- }
398
- for (let i = 0; i < preferred.length; i++) {
399
- if (auth.includes(preferred[i])) {
400
- method = preferred[i];
401
- break;
402
- }
403
- }
404
- }
405
- const failed = (err, data) => {
406
- this.loggedin = false;
407
- this.close(); // if auth is bad, close the connection, it won't get better by itself
408
- err.message = err.message.replace(login.password(), 'REDACTED');
409
- caller(callback, SMTPError.create('authorization.failed', SMTPErrorStates.AUTHFAILED, err, data));
549
+ const method = selectAuthMethod(this.authentication, this.features?.auth);
550
+ if (!method)
551
+ return caller(callback, SMTPError.create('no form of authorization supported', SMTPErrorStates.AUTHNOTSUPPORTED, null, data));
552
+ const authTransport = this.transport;
553
+ const reportAuthInterrupted = () => caller(callback, SMTPError.create('AUTH exchange interrupted', SMTPErrorStates.AUTHFAILED));
554
+ const sendAuthLine = this.createAuthLineSender(authTransport, reportAuthInterrupted);
555
+ const failed = (err) => {
556
+ if (this.transport === authTransport)
557
+ this.close();
558
+ // AUTH commands and replies may contain credentials. Keep only the failure category.
559
+ const sanitizedCause = err instanceof SMTPError && typeof err.code === 'number'
560
+ ? SMTPError.create('AUTH exchange failed', err.code)
561
+ : null;
562
+ caller(callback, SMTPError.create('authorization.failed', SMTPErrorStates.AUTHFAILED, sanitizedCause));
410
563
  };
411
- const response = (err, data, message) => {
412
- if (err) {
413
- failed(err, data);
414
- }
415
- else {
564
+ authenticateWith(method, credentials, (line, onChallenge) => {
565
+ this.runCommand(line, (err, reply, message) => {
566
+ if (err)
567
+ return failed(err);
568
+ if (this.transport !== authTransport)
569
+ return reportAuthInterrupted();
570
+ if (onChallenge)
571
+ return onChallenge(message);
416
572
  this.loggedin = true;
417
- caller(callback, err, data, message);
418
- }
419
- };
420
- const attempt = (err, data, msg) => {
421
- if (err) {
422
- failed(err, data);
423
- }
424
- else {
425
- if (method === AUTH_METHODS['CRAM-MD5']) {
426
- this.command(encodeCramMd5(msg), response, [235, 503]);
427
- }
428
- else if (method === AUTH_METHODS.LOGIN) {
429
- this.command(Buffer.from(login.password()).toString('base64'), response, [235, 503]);
430
- }
431
- }
432
- };
433
- const attemptUser = (err, data) => {
434
- if (err) {
435
- failed(err, data);
436
- }
437
- else {
438
- if (method === AUTH_METHODS.LOGIN) {
439
- this.command(Buffer.from(login.user()).toString('base64'), attempt, [334]);
440
- }
441
- }
442
- };
443
- switch (method) {
444
- case AUTH_METHODS['CRAM-MD5']:
445
- this.command(`AUTH ${AUTH_METHODS['CRAM-MD5']}`, attempt, [334]);
446
- break;
447
- case AUTH_METHODS.LOGIN:
448
- this.command(`AUTH ${AUTH_METHODS.LOGIN}`, attemptUser, [334]);
449
- break;
450
- case AUTH_METHODS.PLAIN:
451
- this.command(`AUTH ${AUTH_METHODS.PLAIN} ${encodePlain()}`, response, [235, 503]);
452
- break;
453
- case AUTH_METHODS.XOAUTH2:
454
- this.command(`AUTH ${AUTH_METHODS.XOAUTH2} ${encodeXoauth2()}`, response, [235, 503]);
455
- break;
456
- default:
457
- caller(callback, SMTPError.create('no form of authorization supported', SMTPErrorStates.AUTHNOTSUPPORTED, null, data));
458
- break;
459
- }
573
+ caller(callback, err, reply, message);
574
+ }, onChallenge ? 334 : 235, sendAuthLine);
575
+ });
460
576
  };
461
577
  this.ehlo_or_helo_if_needed(initiate, domain);
462
578
  }
463
579
  close(force = false) {
464
- if (this.sock) {
465
- if (force) {
580
+ const closingSocket = this.sock;
581
+ const closingMonitor = this.monitor;
582
+ const closingTransport = this.activeTransport;
583
+ // Reset the session before a logger or close listener can reconnect.
584
+ endSession(this);
585
+ this.sock = null;
586
+ this.activeTransport = null;
587
+ this.monitor = null;
588
+ this._state = SMTPState.NOTCONNECTED;
589
+ this._secure = false;
590
+ this.features = null;
591
+ this.loggedin = !(this.user() && this.password());
592
+ closingTransport?.failPendingReplies();
593
+ closingMonitor?.stop();
594
+ if (closingSocket) {
595
+ // end() flushes an open connection; it doesn't cancel a pending dial.
596
+ if (force || closingSocket.connecting) {
597
+ closingSocket.destroy();
466
598
  this.log('smtp connection destroyed!');
467
- this.sock.destroy();
468
599
  }
469
600
  else {
601
+ closingSocket.end();
470
602
  this.log('smtp connection closed.');
471
- this.sock.end();
472
603
  }
473
604
  }
474
- if (this.monitor) {
475
- this.monitor.stop();
476
- this.monitor = null;
477
- }
478
- this._state = SMTPState.NOTCONNECTED;
479
- this._secure = false;
480
- this.sock = null;
481
- this.features = null;
482
- this.loggedin = !(this.user() && this.password());
483
605
  this.emit('close');
484
606
  }
485
607
  quit(callback) {
608
+ const socket = this.sock;
486
609
  this.command('quit', (err, data) => {
487
- this.close();
610
+ if (this.sock === socket)
611
+ this.close();
488
612
  caller(callback, err, data);
489
613
  }, [221, 250]);
490
614
  }