emailjs 5.0.4 → 5.0.6

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