nodemailer 10.4.1 → 10.6.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 (47) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +25 -0
  3. package/dist/cjs/dkim/sign.js +2 -2
  4. package/dist/cjs/errors.d.ts +2 -0
  5. package/dist/cjs/errors.js +11 -1
  6. package/dist/cjs/fetch/cookies.js +4 -1
  7. package/dist/cjs/json-transport/index.js +2 -0
  8. package/dist/cjs/mailer/index.d.ts +5 -0
  9. package/dist/cjs/mailer/index.js +56 -4
  10. package/dist/cjs/mailer/mail-message.d.ts +10 -0
  11. package/dist/cjs/mime-funcs/index.d.ts +2 -1
  12. package/dist/cjs/mime-funcs/index.js +72 -2
  13. package/dist/cjs/mime-node/index.js +1 -79
  14. package/dist/cjs/package-info.d.ts +1 -1
  15. package/dist/cjs/package-info.js +1 -1
  16. package/dist/cjs/shared/index.d.ts +23 -0
  17. package/dist/cjs/shared/index.js +79 -0
  18. package/dist/cjs/smtp-connection/index.d.ts +3 -0
  19. package/dist/cjs/smtp-connection/index.js +17 -3
  20. package/dist/cjs/smtp-pool/index.d.ts +1 -0
  21. package/dist/cjs/smtp-pool/index.js +57 -6
  22. package/dist/cjs/smtp-pool/pool-resource.js +26 -4
  23. package/dist/cjs/smtp-transport/index.d.ts +1 -0
  24. package/dist/cjs/smtp-transport/index.js +47 -35
  25. package/dist/esm/dkim/sign.js +2 -2
  26. package/dist/esm/errors.d.ts +2 -0
  27. package/dist/esm/errors.js +9 -0
  28. package/dist/esm/fetch/cookies.js +4 -1
  29. package/dist/esm/json-transport/index.js +2 -0
  30. package/dist/esm/mailer/index.d.ts +5 -0
  31. package/dist/esm/mailer/index.js +56 -4
  32. package/dist/esm/mailer/mail-message.d.ts +10 -0
  33. package/dist/esm/mime-funcs/index.d.ts +2 -1
  34. package/dist/esm/mime-funcs/index.js +72 -2
  35. package/dist/esm/mime-node/index.js +1 -79
  36. package/dist/esm/package-info.d.ts +1 -1
  37. package/dist/esm/package-info.js +1 -1
  38. package/dist/esm/shared/index.d.ts +23 -0
  39. package/dist/esm/shared/index.js +78 -0
  40. package/dist/esm/smtp-connection/index.d.ts +3 -0
  41. package/dist/esm/smtp-connection/index.js +17 -3
  42. package/dist/esm/smtp-pool/index.d.ts +1 -0
  43. package/dist/esm/smtp-pool/index.js +57 -6
  44. package/dist/esm/smtp-pool/pool-resource.js +26 -4
  45. package/dist/esm/smtp-transport/index.d.ts +1 -0
  46. package/dist/esm/smtp-transport/index.js +47 -35
  47. package/package.json +11 -6
@@ -43,6 +43,7 @@ exports.recordStreamErrors = recordStreamErrors;
43
43
  exports.destroyStream = destroyStream;
44
44
  exports.unreadableStreamError = unreadableStreamError;
45
45
  exports.resolveStream = resolveStream;
46
+ exports.normalizeDomain = normalizeDomain;
46
47
  const urllib = __importStar(require("./url.js"));
47
48
  const node_util_1 = __importDefault(require("node:util"));
48
49
  const node_fs_1 = __importDefault(require("node:fs"));
@@ -54,6 +55,8 @@ Object.defineProperty(exports, "copyOwnKeys", { enumerable: true, get: function
54
55
  const node_dns_1 = __importDefault(require("node:dns"));
55
56
  const node_net_1 = __importDefault(require("node:net"));
56
57
  const node_os_1 = __importDefault(require("node:os"));
58
+ const node_url_1 = __importDefault(require("node:url"));
59
+ const punycode = __importStar(require("../punycode/index.js"));
57
60
  const node_stream_1 = require("node:stream");
58
61
  const DNS_TTL = 5 * 60 * 1000;
59
62
  const CACHE_CLEANUP_INTERVAL = 30 * 1000; // Minimum 30 seconds between cleanups
@@ -771,3 +774,79 @@ function createDefaultLogger(levels) {
771
774
  });
772
775
  return logger;
773
776
  }
777
+ // domainToASCII and domainToUnicode are WHATWG host parsers rather than plain IDNA
778
+ // mappers, so they do more than map: they cut the host at '/', '\\', '?' and '#', drop C0
779
+ // controls, and percent-decode. Handing them 'evil.example/mail.corp.example' returns the
780
+ // deliverable 'evil.example', which would turn a value the bundled codec leaves as
781
+ // unroutable garbage into mail for a domain the sender never named. None of these
782
+ // characters are legal in a domain, so keep them away from the mapper.
783
+ const URL_PARSER_UNSAFE = /[/\\?#%\x00-\x20\x7F]/;
784
+ // RFC 1035 bounds a label at 63 octets and a domain at 253. An A-label is never shorter than
785
+ // the code points it encodes, so anything past these bounds could not have become a valid
786
+ // domain whichever way it is encoded. The bundled codec is super-linear in the length of a
787
+ // label, a 60 KB label of distinct code points took seconds to encode, several times per
788
+ // address, so it is only handed what could be a domain
789
+ const MAX_DOMAIN_LENGTH = 253;
790
+ const MAX_LABEL_LENGTH = 63;
791
+ /**
792
+ * Checks a domain against the DNS length limits, counted in code points per label and in
793
+ * total. The label separators are the ones the bundled codec splits on.
794
+ *
795
+ * @param domain Domain to check
796
+ * @return true if a label or the domain as a whole is too long to be a valid domain
797
+ */
798
+ function exceedsDomainLimits(domain) {
799
+ let total = 0;
800
+ let label = 0;
801
+ for (const char of domain) {
802
+ total++;
803
+ if (char === '.' || char === '。' || char === '.' || char === '。') {
804
+ label = 0;
805
+ }
806
+ else if (++label > MAX_LABEL_LENGTH) {
807
+ return true;
808
+ }
809
+ }
810
+ return total > MAX_DOMAIN_LENGTH;
811
+ }
812
+ /**
813
+ * Encodes a domain the way browsers, the WHATWG URL Standard and DNS facing resolvers do,
814
+ * which is with UTS-46 mapping applied before the Punycode step.
815
+ *
816
+ * The bundled codec is plain RFC 3492 and maps nothing, so it disagrees with every
817
+ * conformant parser on any domain holding a mapped or ignored code point. An invisible
818
+ * U+00AD in 'compa\u00ADny.com' encoded to 'xn--company-pka.com' where a validator reads
819
+ * 'company.com', which let an allow-listed domain be checked and a different one mailed.
820
+ *
821
+ * Anything the URL parser does not accept as a hostname, an address literal such as
822
+ * '[127.0.0.1]' included, comes back empty and falls through to the bundled codec, which
823
+ * leaves those as they were supplied apart from lowercasing them.
824
+ *
825
+ * The mapper gets the domain as supplied, since UTS-46 does its own case mapping and
826
+ * toLowerCase() differs from it: it turns U+1E9E into U+00DF where Node 20 and 22 map it
827
+ * to 'ss', and a word-final U+03A3 into U+03C2 where UTS-46 gives U+03C3. Lowercasing
828
+ * first sent 'user@stra\u1E9Ee.de', which a validator reads as strasse.de, to xn--strae-oqa.de.
829
+ *
830
+ * @param domain Domain to encode
831
+ * @param toUnicode Return the U-label form instead of the A-label form
832
+ * @return Encoded domain
833
+ */
834
+ function normalizeDomain(domain, toUnicode) {
835
+ // domainToASCII and domainToUnicode landed in Node 7, the bundled codec covers Node 6
836
+ if (typeof node_url_1.default.domainToASCII === 'function' && typeof node_url_1.default.domainToUnicode === 'function' && !URL_PARSER_UNSAFE.test(domain)) {
837
+ // The U-label form is decoded from the A-label form rather than from the input:
838
+ // Deno's domainToASCII returns an empty string for a label it cannot decode, while
839
+ // its domainToUnicode returns the label with U+FFFD in place of the bad part
840
+ const ascii = node_url_1.default.domainToASCII(domain);
841
+ const mapped = ascii && toUnicode ? node_url_1.default.domainToUnicode(ascii) : ascii;
842
+ if (mapped) {
843
+ return mapped;
844
+ }
845
+ }
846
+ domain = domain.toLowerCase();
847
+ if (exceedsDomainLimits(domain)) {
848
+ // too long to be a domain whichever way it is encoded, keep it as supplied
849
+ return domain;
850
+ }
851
+ return toUnicode ? punycode.toUnicode(domain) : punycode.toASCII(domain);
852
+ }
@@ -42,6 +42,8 @@ export interface SMTPConnectionOptions {
42
42
  greetingTimeout?: number | undefined;
43
43
  /** Time of inactivity in ms until the connection is closed, defaults to 10 minutes */
44
44
  socketTimeout?: number | undefined;
45
+ /** Time in ms to wait for the peer to close after ending the socket, defaults to 5 seconds. Set to 0 to destroy it immediately */
46
+ socketCloseTimeout?: number | undefined;
45
47
  /** Largest single server response to accept in bytes, defaults to 1 MB */
46
48
  maxResponseSize?: number | undefined;
47
49
  /** Time to wait in ms for the DNS requests to be resolved, defaults to 30 seconds */
@@ -307,6 +309,7 @@ export type SMTPConnectionResponseAction = (str: string) => void;
307
309
  * * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 30 seconds)
308
310
  * * **connectionTimeout** - how many milliseconds to wait for the connection to establish (defaults to 2 minutes)
309
311
  * * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 10 minutes)
312
+ * * **socketCloseTimeout** - Time in ms to wait for the peer to close after ending the socket (defaults to 5 seconds, 0 destroys immediately)
310
313
  * * **maxResponseSize** - Largest single server response to accept in bytes (defaults to 1 MB)
311
314
  * * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds)
312
315
  * * **lmtp** - if true, uses LMTP instead of SMTP protocol
@@ -145,6 +145,7 @@ function maskAuthCommand(cmd) {
145
145
  * * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 30 seconds)
146
146
  * * **connectionTimeout** - how many milliseconds to wait for the connection to establish (defaults to 2 minutes)
147
147
  * * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 10 minutes)
148
+ * * **socketCloseTimeout** - Time in ms to wait for the peer to close after ending the socket (defaults to 5 seconds, 0 destroys immediately)
148
149
  * * **maxResponseSize** - Largest single server response to accept in bytes (defaults to 1 MB)
149
150
  * * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds)
150
151
  * * **lmtp** - if true, uses LMTP instead of SMTP protocol
@@ -287,6 +288,9 @@ class SMTPConnection extends node_events_1.EventEmitter {
287
288
  // socket object is set up but not yet connected
288
289
  this._socket = this.options.socket;
289
290
  return this._resolveAndConnect(opts, _resolved => {
291
+ if (this._destroyed || this._closing) {
292
+ return;
293
+ }
290
294
  try {
291
295
  this._socket.connect(this.port, this.host, () => {
292
296
  // a `secure` connection over a caller-provided socket must still
@@ -465,11 +469,18 @@ class SMTPConnection extends node_events_1.EventEmitter {
465
469
  return;
466
470
  }
467
471
  this._closing = true;
468
- const closeMethod = this.stage === 'init' ? 'destroy' : 'end';
472
+ // anything but a non-negative finite number keeps the default grace period
473
+ const configuredCloseTimeout = this.options.socketCloseTimeout;
474
+ const socketCloseTimeout = typeof configuredCloseTimeout === 'number' && Number.isFinite(configuredCloseTimeout) && configuredCloseTimeout >= 0
475
+ ? configuredCloseTimeout
476
+ : CLOSE_TIMEOUT;
477
+ const closeMethod = this.stage === 'init' || socketCloseTimeout === 0 ? 'destroy' : 'end';
469
478
  this.logger.debug({
470
479
  tnx: 'smtp'
471
480
  }, 'Closing connection to the server using "%s"', closeMethod);
472
- const socket = (this._socket && this._socket.socket) || this._socket;
481
+ // after STARTTLS this is the TLS socket, tear that one down and not the plain socket it
482
+ // wraps (Node 27 exposes the wrapped socket as `.socket`)
483
+ const socket = this._socket;
473
484
  // Detach any in-flight DATA stream from the socket so the source stream
474
485
  // can be garbage-collected once the socket is gone.
475
486
  if (this._currentDataStream) {
@@ -511,7 +522,7 @@ class SMTPConnection extends node_events_1.EventEmitter {
511
522
  if (closeMethod === 'end') {
512
523
  // end() only closes our side, a server that never closes its own would keep
513
524
  // the socket, and the process with it, around for good
514
- const closeTimer = setTimeout(() => socket.destroy(), CLOSE_TIMEOUT);
525
+ const closeTimer = setTimeout(() => socket.destroy(), socketCloseTimeout);
515
526
  if (typeof closeTimer.unref === 'function') {
516
527
  closeTimer.unref();
517
528
  }
@@ -1077,6 +1088,9 @@ class SMTPConnection extends node_events_1.EventEmitter {
1077
1088
  * @internal
1078
1089
  */
1079
1090
  _upgradeConnection(callback) {
1091
+ if (this._destroyed || this._closing) {
1092
+ return;
1093
+ }
1080
1094
  // RFC 3207 section 6: the client MUST discard any knowledge obtained from
1081
1095
  // the server that was not received over the TLS-protected session. Drop any
1082
1096
  // buffered input received before the handshake so a man-in-the-middle cannot
@@ -76,6 +76,7 @@ export interface SMTPPoolRateLimit {
76
76
  * @param options SMTP Connection options
77
77
  */
78
78
  declare class SMTPPool extends EventEmitter {
79
+ readonly supportsAbortSignal = true;
79
80
  options: SMTPPoolResolvedOptions;
80
81
  logger: shared.Logger;
81
82
  name: string;
@@ -56,6 +56,7 @@ const REQUEUE_MAX_DELAY = 2000;
56
56
  class SMTPPool extends node_events_1.EventEmitter {
57
57
  constructor(options) {
58
58
  super();
59
+ this.supportsAbortSignal = true;
59
60
  options = options || {};
60
61
  if (typeof options === 'string') {
61
62
  options = {
@@ -134,26 +135,74 @@ class SMTPPool extends node_events_1.EventEmitter {
134
135
  return false;
135
136
  }
136
137
  // counted until the callback runs, whichever path runs it: delivered, failed, requeued
137
- // until it gives up, or drained by close()
138
+ // until it gives up, aborted, or drained by close()
138
139
  let counted = true;
140
+ let detachSignal;
139
141
  this._pending++;
140
- this._queue.push({
142
+ const entry = {
141
143
  mail,
142
144
  requeueAttempts: 0,
143
145
  callback: (err, info) => {
144
- if (counted) {
145
- counted = false;
146
- this._pending--;
146
+ if (!counted) {
147
+ return;
147
148
  }
149
+ counted = false;
150
+ this._pending--;
151
+ detachSignal?.();
152
+ entry.resource = undefined;
148
153
  callback(err, info);
149
154
  }
150
- });
155
+ };
156
+ this._queue.push(entry);
157
+ const signal = mail.data.signal;
158
+ if (signal) {
159
+ // one listener for the original entry, retained across connection-close retries
160
+ detachSignal = this._watchAbortSignal(entry, signal, () => counted);
161
+ if (signal.aborted) {
162
+ return true;
163
+ }
164
+ }
151
165
  if (this.idling && this._queue.length >= this.options.maxConnections) {
152
166
  this.idling = false;
153
167
  }
154
168
  setImmediate(() => this._processMessages());
155
169
  return true;
156
170
  }
171
+ /**
172
+ * Fails a queued or assigned entry when its signal aborts: removes it from the queue, or
173
+ * closes the connection delivering it, so other deliveries in the pool can continue.
174
+ * Returns a function that removes the listener.
175
+ * @internal
176
+ */
177
+ _watchAbortSignal(entry, signal, isPending) {
178
+ const onAbort = () => {
179
+ if (!isPending()) {
180
+ return;
181
+ }
182
+ const index = this._queue.indexOf(entry);
183
+ if (index !== -1) {
184
+ this._queue.splice(index, 1);
185
+ }
186
+ const resource = entry.resource;
187
+ if (resource && resource.queueEntry === entry) {
188
+ // Detach before closing: the close handler must not retry this message.
189
+ resource.queueEntry = false;
190
+ resource.close();
191
+ }
192
+ try {
193
+ entry.callback(errors.createAbortError(signal));
194
+ }
195
+ finally {
196
+ // Removing a queued entry can make the pool idle again.
197
+ setImmediate(() => this._processMessages());
198
+ }
199
+ };
200
+ signal.addEventListener('abort', onAbort, { once: true });
201
+ if (signal.aborted) {
202
+ setImmediate(onAbort);
203
+ }
204
+ return () => signal.removeEventListener('abort', onAbort);
205
+ }
157
206
  /**
158
207
  * Closes the pool. Idle connections are closed at once and a connection in the middle of a
159
208
  * delivery finishes it first, unless `force` is set: then it is closed too and its message
@@ -254,6 +303,7 @@ class SMTPPool extends node_events_1.EventEmitter {
254
303
  this.emit('idle');
255
304
  }
256
305
  const entry = (connection.queueEntry = this._queue.shift());
306
+ entry.resource = connection;
257
307
  entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, '');
258
308
  connection.available = false;
259
309
  this.logger.debug({
@@ -425,6 +475,7 @@ class SMTPPool extends node_events_1.EventEmitter {
425
475
  messageId: connection.queueEntry.messageId,
426
476
  action: 'requeue'
427
477
  }, 'Re-queued message <%s> for #%s. Attempt: #%s', connection.queueEntry.messageId, connection.id, connection.queueEntry.requeueAttempts);
478
+ connection.queueEntry.resource = undefined;
428
479
  this._queue.unshift(connection.queueEntry);
429
480
  connection.queueEntry = false;
430
481
  return delay;
@@ -86,6 +86,7 @@ class PoolResource extends node_events_1.EventEmitter {
86
86
  }
87
87
  this._connection = false;
88
88
  this._connected = false;
89
+ this._closed = false;
89
90
  this.messages = 0;
90
91
  this.available = true;
91
92
  this._failed = false;
@@ -113,6 +114,10 @@ class PoolResource extends node_events_1.EventEmitter {
113
114
  // the proxy handshake, if any, counts against connectionTimeout as well
114
115
  const connectStartedAt = Date.now();
115
116
  this.pool.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
117
+ if (this._closed) {
118
+ socketOptions && socketOptions.connection?.destroy();
119
+ return;
120
+ }
116
121
  if (err) {
117
122
  // nothing was connected, so no 'close' event is coming that would free the
118
123
  // slot this resource holds in the pool, report the failure the way a failed
@@ -136,7 +141,7 @@ class PoolResource extends node_events_1.EventEmitter {
136
141
  this.connection = new index_js_1.default(options);
137
142
  this.connection._connectStartedAt = connectStartedAt;
138
143
  this.connection.on('error', (err) => {
139
- if (this._sending) {
144
+ if (this._closed || this._sending) {
140
145
  // the send callback gets the same error and decides what it means for the message
141
146
  return;
142
147
  }
@@ -150,7 +155,7 @@ class PoolResource extends node_events_1.EventEmitter {
150
155
  return;
151
156
  }
152
157
  this._fail(err);
153
- if (returned) {
158
+ if (returned || this._closed) {
154
159
  return;
155
160
  }
156
161
  returned = true;
@@ -161,7 +166,7 @@ class PoolResource extends node_events_1.EventEmitter {
161
166
  returned = true;
162
167
  });
163
168
  this.connection.connect(err => {
164
- if (returned) {
169
+ if (returned || this._closed) {
165
170
  return;
166
171
  }
167
172
  if (err) {
@@ -172,7 +177,7 @@ class PoolResource extends node_events_1.EventEmitter {
172
177
  }
173
178
  if (this.auth && (this.connection.allowsAuth || options.forceAuth)) {
174
179
  this.connection.login(this.auth, err => {
175
- if (returned) {
180
+ if (returned || this._closed) {
176
181
  return;
177
182
  }
178
183
  returned = true;
@@ -200,6 +205,9 @@ class PoolResource extends node_events_1.EventEmitter {
200
205
  * @param callback Callback function
201
206
  */
202
207
  send(mail, callback) {
208
+ if (this._closed) {
209
+ return;
210
+ }
203
211
  if (!this._connected) {
204
212
  return this.connect(err => {
205
213
  if (err) {
@@ -231,6 +239,9 @@ class PoolResource extends node_events_1.EventEmitter {
231
239
  const reused = this.messages > 0;
232
240
  const messageStream = mail.message.createReadStream();
233
241
  this.connection.send(envelope, messageStream, (err, info) => {
242
+ if (mail.data.signal?.aborted) {
243
+ return;
244
+ }
234
245
  this._sending = false;
235
246
  this.messages++;
236
247
  if (err) {
@@ -277,6 +288,9 @@ class PoolResource extends node_events_1.EventEmitter {
277
288
  * @internal
278
289
  */
279
290
  _release() {
291
+ if (this._closed) {
292
+ return;
293
+ }
280
294
  if (this.messages >= this.options.maxMessages) {
281
295
  const err = new Error('Resource exhausted');
282
296
  err.code = errors.EMAXLIMIT;
@@ -285,6 +299,9 @@ class PoolResource extends node_events_1.EventEmitter {
285
299
  return;
286
300
  }
287
301
  this.pool._checkRateLimit(() => {
302
+ if (this._closed) {
303
+ return;
304
+ }
288
305
  this.available = true;
289
306
  this._startIdleTimer();
290
307
  this.emit('available');
@@ -327,6 +344,11 @@ class PoolResource extends node_events_1.EventEmitter {
327
344
  * Closes the connection
328
345
  */
329
346
  close() {
347
+ if (this._closed) {
348
+ return;
349
+ }
350
+ this._closed = true;
351
+ this.available = false;
330
352
  this._connected = false;
331
353
  this._stopIdleTimer();
332
354
  if (this.auth && this.auth.oauth2) {
@@ -93,6 +93,7 @@ export type SMTPTransportSendCallback = ResultCallback<SMTPSentMessageInfo>;
93
93
  * @param options Connection options
94
94
  */
95
95
  declare class SMTPTransport extends EventEmitter {
96
+ readonly supportsAbortSignal = true;
96
97
  options: SMTPTransportOptions;
97
98
  logger: shared.Logger;
98
99
  name: string;
@@ -59,6 +59,7 @@ const MESSAGE_AUTH_KEYS = ['type', 'user', 'pass', 'accessToken', 'refreshToken'
59
59
  class SMTPTransport extends node_events_1.EventEmitter {
60
60
  constructor(options) {
61
61
  super();
62
+ this.supportsAbortSignal = true;
62
63
  options = options || {};
63
64
  if (typeof options === 'string') {
64
65
  options = {
@@ -153,13 +154,46 @@ class SMTPTransport extends node_events_1.EventEmitter {
153
154
  * @param callback Callback function
154
155
  */
155
156
  send(mail, callback) {
157
+ const signal = mail.data.signal;
158
+ let returned = false;
159
+ let connection;
160
+ let perCallAuth;
161
+ const cleanupPerCallAuth = () => {
162
+ if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
163
+ perCallAuth.oauth2.removeAllListeners();
164
+ }
165
+ perCallAuth = null;
166
+ };
167
+ const finish = (err, info) => {
168
+ if (returned) {
169
+ return;
170
+ }
171
+ returned = true;
172
+ signal?.removeEventListener('abort', onAbort);
173
+ cleanupPerCallAuth();
174
+ connection?.close();
175
+ callback(err, info);
176
+ };
177
+ function onAbort() {
178
+ finish(errors.createAbortError(signal));
179
+ }
180
+ if (signal) {
181
+ signal.addEventListener('abort', onAbort, { once: true });
182
+ if (signal.aborted) {
183
+ setImmediate(onAbort);
184
+ return;
185
+ }
186
+ }
156
187
  // the proxy handshake, if any, counts against connectionTimeout as well
157
188
  const connectStartedAt = Date.now();
158
189
  this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
190
+ if (returned) {
191
+ socketOptions && socketOptions.connection?.destroy();
192
+ return;
193
+ }
159
194
  if (err) {
160
- return callback(err);
195
+ return finish(err);
161
196
  }
162
- let returned = false;
163
197
  let options = this.options;
164
198
  if (socketOptions && socketOptions.connection) {
165
199
  this.logger.info({
@@ -173,24 +207,9 @@ class SMTPTransport extends node_events_1.EventEmitter {
173
207
  // only copy options if we need to modify it
174
208
  options = Object.assign(shared.assign(false, options), socketOptions);
175
209
  }
176
- const connection = new index_js_1.default(options);
177
- connection._connectStartedAt = connectStartedAt;
178
- let perCallAuth;
179
- const cleanupPerCallAuth = () => {
180
- if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
181
- perCallAuth.oauth2.removeAllListeners();
182
- }
183
- perCallAuth = null;
184
- };
185
- connection.once('error', err => {
186
- if (returned) {
187
- return;
188
- }
189
- returned = true;
190
- cleanupPerCallAuth();
191
- connection.close();
192
- return callback(err);
193
- });
210
+ const smtp = (connection = new index_js_1.default(options));
211
+ smtp._connectStartedAt = connectStartedAt;
212
+ smtp.once('error', err => finish(err));
194
213
  const sendMessage = () => {
195
214
  const envelope = mail.message.getEnvelope();
196
215
  const messageId = mail.message.messageId();
@@ -209,20 +228,17 @@ class SMTPTransport extends node_events_1.EventEmitter {
209
228
  tnx: 'send',
210
229
  messageId
211
230
  }, 'Sending message %s to <%s>', messageId, recipients.join(', '));
212
- connection.send(envelope, mail.message.createReadStream(), (err, info) => {
231
+ smtp.send(envelope, mail.message.createReadStream(), (err, info) => {
213
232
  if (returned) {
214
233
  // the connection error handler has already reported this send
215
234
  return;
216
235
  }
217
- returned = true;
218
- cleanupPerCallAuth();
219
- connection.close();
220
236
  if (err) {
221
237
  this.logger.error({
222
238
  err,
223
239
  tnx: 'send'
224
240
  }, 'Send error for %s: %s', messageId, err.message);
225
- return callback(err);
241
+ return finish(err);
226
242
  }
227
243
  info.envelope = {
228
244
  from: envelope.from,
@@ -230,7 +246,7 @@ class SMTPTransport extends node_events_1.EventEmitter {
230
246
  };
231
247
  info.messageId = messageId;
232
248
  try {
233
- return callback(null, info);
249
+ return finish(null, info);
234
250
  }
235
251
  catch (E) {
236
252
  this.logger.error({
@@ -240,27 +256,23 @@ class SMTPTransport extends node_events_1.EventEmitter {
240
256
  }
241
257
  });
242
258
  };
243
- connection.connect(err => {
259
+ smtp.connect(err => {
244
260
  if (returned) {
245
261
  return;
246
262
  }
247
263
  if (err) {
248
264
  // the server closed the connection before the greeting
249
- returned = true;
250
- connection.close();
251
- return callback(err);
265
+ return finish(err);
252
266
  }
253
267
  perCallAuth = this.getAuth(mail.data.auth);
254
- if (perCallAuth && (connection.allowsAuth || options.forceAuth)) {
255
- connection.login(perCallAuth, err => {
268
+ if (perCallAuth && (smtp.allowsAuth || options.forceAuth)) {
269
+ smtp.login(perCallAuth, err => {
256
270
  cleanupPerCallAuth();
257
271
  if (returned) {
258
272
  return;
259
273
  }
260
274
  if (err) {
261
- returned = true;
262
- connection.close();
263
- return callback(err);
275
+ return finish(err);
264
276
  }
265
277
  sendMessage();
266
278
  });
@@ -1,4 +1,4 @@
1
- import * as punycode from '../punycode/index.js';
1
+ import * as shared from '../shared/index.js';
2
2
  import * as mimeFuncs from '../mime-funcs/index.js';
3
3
  import crypto from 'node:crypto';
4
4
  import * as errors from '../errors.js';
@@ -65,7 +65,7 @@ function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyH
65
65
  'v=1',
66
66
  'a=rsa-' + hashAlgo,
67
67
  'c=relaxed/relaxed',
68
- 'd=' + punycode.toASCII(cleanTagValue(domainName)),
68
+ 'd=' + shared.normalizeDomain(cleanTagValue(domainName), false),
69
69
  'q=dns/txt',
70
70
  's=' + cleanTagValue(keySelector),
71
71
  'bh=' + bodyHash,
@@ -23,6 +23,7 @@ export declare const ERROR_CODES: {
23
23
  readonly EMESSAGE: "Message delivery error";
24
24
  readonly EOTP: "Invalid one-time passcode data (otp option)";
25
25
  readonly ESTREAM: "Stream processing error";
26
+ readonly EABORT: "Message sending aborted";
26
27
  readonly EAUTH: "Authentication failed";
27
28
  readonly ENOAUTH: "Authentication credentials not provided";
28
29
  readonly EOAUTH2: "OAuth2 token generation or refresh error";
@@ -51,6 +52,7 @@ export declare const EENVELOPE = "EENVELOPE";
51
52
  export declare const EMESSAGE = "EMESSAGE";
52
53
  export declare const EOTP = "EOTP";
53
54
  export declare const ESTREAM = "ESTREAM";
55
+ export declare const EABORT = "EABORT";
54
56
  export declare const EAUTH = "EAUTH";
55
57
  export declare const ENOAUTH = "ENOAUTH";
56
58
  export declare const EOAUTH2 = "EOAUTH2";
@@ -26,6 +26,7 @@ export const ERROR_CODES = {
26
26
  EMESSAGE: 'Message delivery error',
27
27
  EOTP: 'Invalid one-time passcode data (otp option)',
28
28
  ESTREAM: 'Stream processing error',
29
+ EABORT: 'Message sending aborted',
29
30
  // Authentication errors
30
31
  EAUTH: 'Authentication failed',
31
32
  ENOAUTH: 'Authentication credentials not provided',
@@ -55,6 +56,7 @@ export const EENVELOPE = 'EENVELOPE';
55
56
  export const EMESSAGE = 'EMESSAGE';
56
57
  export const EOTP = 'EOTP';
57
58
  export const ESTREAM = 'ESTREAM';
59
+ export const EABORT = 'EABORT';
58
60
  export const EAUTH = 'EAUTH';
59
61
  export const ENOAUTH = 'ENOAUTH';
60
62
  export const EOAUTH2 = 'EOAUTH2';
@@ -67,6 +69,13 @@ export const EPROXY = 'EPROXY';
67
69
  export const EFILEACCESS = 'EFILEACCESS';
68
70
  export const EURLACCESS = 'EURLACCESS';
69
71
  export const EFETCH = 'EFETCH';
72
+ /** Creates the error reported when a caller cancels an individual send. @internal */
73
+ export const createAbortError = (signal) => {
74
+ const err = new Error('Message sending aborted', { cause: signal.reason });
75
+ err.name = 'AbortError';
76
+ err.code = EABORT;
77
+ return err;
78
+ };
70
79
  /**
71
80
  * Tells whether the error ended the connection rather than rejected what was sent over it
72
81
  */
@@ -93,6 +93,7 @@ class Cookies {
93
93
  parse(cookieStr) {
94
94
  const cookie = {};
95
95
  let hasNameValue = false;
96
+ let hasMaxAge = false;
96
97
  (cookieStr || '')
97
98
  .toString()
98
99
  .split(';')
@@ -120,7 +121,8 @@ class Cookies {
120
121
  case 'expires': {
121
122
  const expires = new Date(value);
122
123
  // ignore date if can not parse it
123
- if (expires.toString() !== 'Invalid Date') {
124
+ if (expires.toString() !== 'Invalid Date' && !hasMaxAge) {
125
+ // Max-Age has precedence when both attributes are present (RFC 6265 5.3)
124
126
  cookie.expires = expires;
125
127
  }
126
128
  break;
@@ -137,6 +139,7 @@ class Cookies {
137
139
  break;
138
140
  case 'max-age':
139
141
  cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000);
142
+ hasMaxAge = true;
140
143
  break;
141
144
  case 'secure':
142
145
  cookie.secure = true;
@@ -48,6 +48,8 @@ class JSONTransport {
48
48
  }
49
49
  delete data.envelope;
50
50
  delete data.normalizedHeaders;
51
+ // the per-message AbortSignal is not message data
52
+ delete data.signal;
51
53
  // the message field is the object itself with skipEncoding, the
52
54
  // createTransport overload for that option types the result accordingly
53
55
  return done(null, {
@@ -112,6 +112,11 @@ export interface MailMeta {
112
112
  * declared on Transport, Transporter and Mail
113
113
  */
114
114
  export interface Transport<T = SentMessageInfo, D extends TransportOptions = TransportOptions> {
115
+ /**
116
+ * Set only if send() cancels its own work on mail.data.signal and removes its signal listener
117
+ * when finished. Without it the signal is still honored up to dispatch, then ignored.
118
+ */
119
+ supportsAbortSignal?: boolean | undefined;
115
120
  /** Transport name, used for logging */
116
121
  name: string;
117
122
  /** Transport version, used for logging */