nodemailer 10.4.0 → 10.5.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 (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +21 -0
  3. package/dist/cjs/addressparser/index.js +185 -2
  4. package/dist/cjs/dkim/sign.js +2 -2
  5. package/dist/cjs/errors.d.ts +2 -0
  6. package/dist/cjs/errors.js +11 -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 -73
  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.js +6 -0
  19. package/dist/cjs/smtp-pool/index.d.ts +1 -0
  20. package/dist/cjs/smtp-pool/index.js +57 -6
  21. package/dist/cjs/smtp-pool/pool-resource.js +26 -4
  22. package/dist/cjs/smtp-transport/index.d.ts +1 -0
  23. package/dist/cjs/smtp-transport/index.js +47 -35
  24. package/dist/cjs/well-known/services.js +7 -0
  25. package/dist/esm/addressparser/index.js +185 -2
  26. package/dist/esm/dkim/sign.js +2 -2
  27. package/dist/esm/errors.d.ts +2 -0
  28. package/dist/esm/errors.js +9 -0
  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 -73
  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.js +6 -0
  41. package/dist/esm/smtp-pool/index.d.ts +1 -0
  42. package/dist/esm/smtp-pool/index.js +57 -6
  43. package/dist/esm/smtp-pool/pool-resource.js +26 -4
  44. package/dist/esm/smtp-transport/index.d.ts +1 -0
  45. package/dist/esm/smtp-transport/index.js +47 -35
  46. package/dist/esm/well-known/services.js +7 -0
  47. package/dist/well-known/services.json +8 -0
  48. package/package.json +3 -3
@@ -46,6 +46,30 @@ class TokenList {
46
46
  this.slots[at + 2] = end;
47
47
  return this.length++;
48
48
  }
49
+ /**
50
+ * Offset of the first character of a token that is part of its value. A text run that is
51
+ * no plain slice of the field still spans the whitespace and control characters its value
52
+ * is trimmed of.
53
+ */
54
+ contentStart(index) {
55
+ let start = this.slots[index * 3 + 1];
56
+ const end = this.slots[index * 3 + 2];
57
+ while (start < end && _isDroppedCode(this.str.charCodeAt(start))) {
58
+ start++;
59
+ }
60
+ return start;
61
+ }
62
+ /**
63
+ * Offset just past the last character of a token that is part of its value
64
+ */
65
+ contentEnd(index) {
66
+ const start = this.slots[index * 3 + 1];
67
+ let end = this.slots[index * 3 + 2];
68
+ while (end > start && _isDroppedCode(this.str.charCodeAt(end - 1))) {
69
+ end--;
70
+ }
71
+ return end;
72
+ }
49
73
  /**
50
74
  * The character of an operator token, an empty string for a text run
51
75
  */
@@ -181,6 +205,44 @@ function _isSpaceCode(code) {
181
205
  code === 0x3000 ||
182
206
  code === 0xfeff);
183
207
  }
208
+ /**
209
+ * Checks for the whitespace RFC 5322 folding whitespace is made of: SP and HTAB, plus the
210
+ * line break a fold carries. The other characters _isSpaceCode accepts are atext under
211
+ * RFC 6532, and parsers disagree on them: mailauth keeps U+00A0 in a domain, so joining a
212
+ * domain across one names a domain that reader never sees
213
+ *
214
+ * @param code Character code
215
+ * @return true if the character is folding whitespace
216
+ */
217
+ function _isFoldingSpaceCode(code) {
218
+ return code === 0x20 || code === 0x09 || code === 0x0d || code === 0x0a;
219
+ }
220
+ /**
221
+ * Checks if every character in a stretch of the field is folding whitespace
222
+ *
223
+ * @param str The field
224
+ * @param from Offset of the first character
225
+ * @param to Offset just past the last one
226
+ * @return true if the stretch holds nothing but folding whitespace
227
+ */
228
+ function _isFoldingGap(str, from, to) {
229
+ for (let i = from; i < to; i++) {
230
+ if (!_isFoldingSpaceCode(str.charCodeAt(i))) {
231
+ return false;
232
+ }
233
+ }
234
+ return true;
235
+ }
236
+ /**
237
+ * Checks for a character the value of a text run is trimmed of, or leaves out: whitespace,
238
+ * C0 controls and DEL
239
+ *
240
+ * @param code Character code
241
+ * @return true if the character is not part of the value at the edge of a run
242
+ */
243
+ function _isDroppedCode(code) {
244
+ return code < 0x20 || code === 0x7f || _isSpaceCode(code);
245
+ }
184
246
  /**
185
247
  * The characters JS `\w` matches without the unicode flag, the set the `\b` in
186
248
  * LOOSE_TEXT_ADDR is read against. charCodeAt off either end of the string gives NaN,
@@ -231,6 +293,9 @@ const LEADING_QUOTED_STRING = /^"(?:[^"\\]|\\[\s\S])*"/;
231
293
  * The scan is by index, a pattern such as /\s+@/ backtracks over a long whitespace run that
232
294
  * no '@' follows.
233
295
  *
296
+ * The whitespace around the dots of the domain that follows is dropped as well, see
297
+ * _joinDomainDotSpacing.
298
+ *
234
299
  * @param value Value holding the '@'
235
300
  * @param at Offset of the '@', or -1
236
301
  * @return The value with the whitespace beside that '@' removed
@@ -247,7 +312,86 @@ function _joinAtSpacing(value, at) {
247
312
  while (end < value.length && _isSpaceCode(value.charCodeAt(end))) {
248
313
  end++;
249
314
  }
250
- return start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
315
+ const joined = start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
316
+ return _joinDomainDotSpacing(joined, start);
317
+ }
318
+ // The ASCII atext characters: printable, and none of the RFC 5322 specials
319
+ const ASCII_ATEXT = new Uint8Array(0x80);
320
+ for (let code = 0x21; code < 0x7f; code++) {
321
+ ASCII_ATEXT[code] = '()<>[]:;@\\,."'.indexOf(String.fromCharCode(code)) < 0 ? 1 : 0;
322
+ }
323
+ /**
324
+ * Checks if a character can be part of an atom: anything but the specials, whitespace and
325
+ * the control characters (RFC 5322 3.2.3, with non-ASCII allowed as RFC 6532 does)
326
+ *
327
+ * @param code Character code
328
+ * @return true if the character is atext
329
+ */
330
+ function _isAtextCode(code) {
331
+ return code < 0x80 ? ASCII_ATEXT[code] === 1 : !_isSpaceCode(code);
332
+ }
333
+ /**
334
+ * Drops the whitespace around the dots of the domain behind the '@' at an offset.
335
+ *
336
+ * obs-domain is atoms with CFWS around the dots (RFC 5322 4.4), so 'user@victim.example
337
+ * .allowed.example' names user@victim.example.allowed.example. Read as two runs, the domain
338
+ * ended at the whitespace and the envelope went to victim.example, a different domain than
339
+ * the one an RFC 5322 parser, and an application validating the address with one, reads
340
+ * (GHSA-3q53-mvfw-q9v8). A comment around a dot reaches here as whitespace.
341
+ *
342
+ * Only SP, HTAB and a fold count as the whitespace, see _isFoldingSpaceCode.
343
+ *
344
+ * Only a dot with an atom on both sides joins, as for a conformant parser: whitespace that
345
+ * is not beside a dot ends the domain, and so does a dot that no atom follows, which keeps
346
+ * 'user@example.com .' from becoming a domain with a trailing dot. A domain literal is left
347
+ * alone. Everything from where the domain ends is kept as it is.
348
+ *
349
+ * @param value Value holding the '@'
350
+ * @param at Offset of the '@'
351
+ * @return The value with the whitespace around the dots of that domain removed
352
+ */
353
+ function _joinDomainDotSpacing(value, at) {
354
+ const len = value.length;
355
+ // '[' is no atext, so a domain literal ends the walk before it starts
356
+ let pos = at + 1;
357
+ let spaced = false;
358
+ for (;;) {
359
+ const labelStart = pos;
360
+ while (pos < len && _isAtextCode(value.charCodeAt(pos))) {
361
+ pos++;
362
+ }
363
+ if (pos === labelStart) {
364
+ break;
365
+ }
366
+ // the dot, with the whitespace on either side of it, and the label behind it
367
+ let next = pos;
368
+ while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
369
+ next++;
370
+ }
371
+ if (value.charCodeAt(next) !== 0x2e) {
372
+ break;
373
+ }
374
+ next++;
375
+ while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
376
+ next++;
377
+ }
378
+ if (next >= len || !_isAtextCode(value.charCodeAt(next))) {
379
+ break;
380
+ }
381
+ spaced = spaced || next !== pos + 1;
382
+ pos = next;
383
+ }
384
+ if (!spaced) {
385
+ return value;
386
+ }
387
+ // every whitespace character the walk covered sits beside a dot
388
+ let domain = '';
389
+ for (let k = at + 1; k < pos; k++) {
390
+ if (!_isFoldingSpaceCode(value.charCodeAt(k))) {
391
+ domain += value.charAt(k);
392
+ }
393
+ }
394
+ return value.slice(0, at + 1) + domain + value.slice(pos);
251
395
  }
252
396
  /**
253
397
  * Drops the whitespace beside the '@' that splits the domain off a value. That is the '@'
@@ -551,6 +695,15 @@ function _collectAddressParts(tokens, from, to) {
551
695
  // whether the last text run holds nothing but quoted text so far, which is what a quoted
552
696
  // local part is until the '@' after it joins the run
553
697
  let lastTextPureQuoted = false;
698
+ // whether the last text run holds an unquoted '@', so that it runs on into a domain, and
699
+ // whether nothing but comments has come since it, see the join below
700
+ let lastTextHasAt = false;
701
+ let lastTextOpen = false;
702
+ // Where the last text run, or the last comment since it, ended in the field, and whether
703
+ // everything between it and the comments since was folding whitespace. The tokens are
704
+ // trimmed of any whitespace, so this is read off the field itself.
705
+ let gapFrom = 0;
706
+ let gapsFolding = true;
554
707
  // Last character of the run each state is currently accumulating. Reading it back off
555
708
  // the accumulator with slice(-1) makes the engine flatten the whole growing string on
556
709
  // every token, which is quadratic over an address built from many comment-joined atoms
@@ -568,18 +721,27 @@ function _collectAddressParts(tokens, from, to) {
568
721
  case '<':
569
722
  state = 'address';
570
723
  insideQuotes = false;
724
+ lastTextOpen = false;
571
725
  break;
572
726
  case '(':
573
727
  state = 'comment';
574
728
  insideQuotes = false;
729
+ gapsFolding = gapsFolding && _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
575
730
  break;
576
731
  case '"':
577
732
  insideQuotes = !insideQuotes;
578
733
  state = 'text';
734
+ lastTextOpen = false;
579
735
  break;
580
736
  default:
581
737
  state = 'text';
582
738
  insideQuotes = false;
739
+ if (value !== ')') {
740
+ lastTextOpen = false;
741
+ }
742
+ else {
743
+ gapFrom = tokens.contentEnd(i);
744
+ }
583
745
  break;
584
746
  }
585
747
  }
@@ -596,8 +758,23 @@ function _collectAddressParts(tokens, from, to) {
596
758
  // of the '@', but it cannot join two atoms into one: gluing across it would read
597
759
  // 'user@example.com(x)evil.com' as the single domain 'example.comevil.com' and
598
760
  // deliver to a domain the sender never named.
761
+ // A comment beside a dot of a domain is CFWS inside obs-domain, with or without
762
+ // folding whitespace around it, so 'user@victim.example(x).allowed.example' names
763
+ // one domain (GHSA-3q53-mvfw-q9v8). Any other whitespace in between keeps them apart.
764
+ // A ')' always leaves the walk in unquoted text, so neither needs checking here.
765
+ // Neither join across a comment takes in a second '@' once the run holds one: the
766
+ // address would then split at the last '@', and 'user@company(x).com@attacker.net',
767
+ // which an RFC 5322 parser reads as user@company.com, would go to attacker.net.
599
768
  const parts = data[state];
600
- const joins = prevNoBreak && parts.length && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@');
769
+ const secondAt = lastTextHasAt && prevOperator === ')' && value.indexOf('@') >= 0;
770
+ const joinsDomain = !secondAt &&
771
+ lastTextOpen &&
772
+ lastTextHasAt &&
773
+ prevOperator === ')' &&
774
+ (lastChars.text === '.' || value.charAt(0) === '.') &&
775
+ gapsFolding &&
776
+ _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
777
+ const joins = joinsDomain || (!secondAt && prevNoBreak && parts.length > 0 && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@'));
601
778
  if (joins) {
602
779
  const last = data[state].length - 1;
603
780
  if (state === 'text' && !insideQuotes) {
@@ -622,6 +799,12 @@ function _collectAddressParts(tokens, from, to) {
622
799
  lastTextPureQuoted = insideQuotes;
623
800
  }
624
801
  }
802
+ if (state === 'text') {
803
+ lastTextHasAt = (joins && lastTextHasAt) || (!insideQuotes && value.indexOf('@') >= 0);
804
+ lastTextOpen = true;
805
+ gapFrom = tokens.contentEnd(i);
806
+ gapsFolding = true;
807
+ }
625
808
  }
626
809
  }
627
810
  // If there is no text but a comment, replace the two. A comment is never part of a
@@ -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
  */
@@ -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 */
@@ -18,6 +18,16 @@ import crypto from 'node:crypto';
18
18
  * asks a server to accept 100, so a real send is bounded far below this.
19
19
  */
20
20
  const DEFAULT_MAX_RECIPIENTS = 100000;
21
+ /**
22
+ * Duck-typed so that signals from another realm or a polyfill are accepted as well
23
+ */
24
+ function isAbortSignal(value) {
25
+ return (typeof value === 'object' &&
26
+ value !== null &&
27
+ 'aborted' in value &&
28
+ typeof value.addEventListener === 'function' &&
29
+ typeof value.removeEventListener === 'function');
30
+ }
21
31
  /**
22
32
  * Creates an object for exposing the Mail API
23
33
  *
@@ -119,11 +129,43 @@ class Mail extends EventEmitter {
119
129
  this.getSocket = false;
120
130
  }
121
131
  const mail = new MailMessage(this, data);
132
+ const signalOption = mail.data.signal;
133
+ const signal = isAbortSignal(signalOption) ? signalOption : undefined;
134
+ let settled = false;
135
+ const removeAbortListener = () => signal?.removeEventListener('abort', onAbort);
136
+ const finish = (err, info) => {
137
+ if (settled) {
138
+ return;
139
+ }
140
+ settled = true;
141
+ removeAbortListener();
142
+ if (err) {
143
+ mail.releaseStreams();
144
+ }
145
+ done(err, info);
146
+ };
122
147
  // a failed message is not going to be read anymore, release its content streams
123
148
  const fail = (err) => {
124
- mail.releaseStreams();
125
- done(err);
149
+ finish(err);
126
150
  };
151
+ function onAbort() {
152
+ fail(errors.createAbortError(signal));
153
+ }
154
+ if (signalOption !== undefined && signalOption !== null && !signal) {
155
+ const err = new Error('The signal option must be an AbortSignal');
156
+ err.code = errors.ECONFIG;
157
+ setImmediate(() => fail(err));
158
+ return promise;
159
+ }
160
+ // Mail handles a pre-aborted signal and cancellation during plugin processing for every
161
+ // transport; a transport without supportsAbortSignal ignores the signal once it is called
162
+ if (signal) {
163
+ signal.addEventListener('abort', onAbort, { once: true });
164
+ if (signal.aborted) {
165
+ setImmediate(onAbort);
166
+ return promise;
167
+ }
168
+ }
127
169
  this.logger.debug({
128
170
  tnx: 'transport',
129
171
  name: this.transporter.name,
@@ -131,6 +173,9 @@ class Mail extends EventEmitter {
131
173
  action: 'send'
132
174
  }, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version);
133
175
  this._processPlugins('compile', mail, err => {
176
+ if (settled) {
177
+ return;
178
+ }
134
179
  if (err) {
135
180
  this.logger.error({
136
181
  err,
@@ -168,6 +213,9 @@ class Mail extends EventEmitter {
168
213
  return fail(err);
169
214
  }
170
215
  this._processPlugins('stream', mail, err => {
216
+ if (settled) {
217
+ return;
218
+ }
171
219
  if (err) {
172
220
  this.logger.error({
173
221
  err,
@@ -187,16 +235,17 @@ class Mail extends EventEmitter {
187
235
  return dkim.sign(input, mail.data._dkim);
188
236
  });
189
237
  }
238
+ // The transport takes ownership of cancellation from here, including queued work.
239
+ removeAbortListener();
190
240
  this.transporter.send(mail, (...args) => {
191
241
  if (args[0]) {
192
- mail.releaseStreams();
193
242
  this.logger.error({
194
243
  err: args[0],
195
244
  tnx: 'transport',
196
245
  action: 'send'
197
246
  }, 'Send Error: %s', args[0].message);
198
247
  }
199
- done(...args);
248
+ finish(...args);
200
249
  });
201
250
  });
202
251
  });
@@ -226,6 +275,9 @@ class Mail extends EventEmitter {
226
275
  let pos = 0;
227
276
  let block = 'default';
228
277
  const processPlugins = () => {
278
+ if (mail.data.signal?.aborted) {
279
+ return callback(errors.createAbortError(mail.data.signal));
280
+ }
229
281
  let curplugins = block === 'default' ? defaultPlugins : userPlugins;
230
282
  if (pos >= curplugins.length) {
231
283
  if (block === 'default' && userPlugins.length) {
@@ -13,6 +13,16 @@ import type { SentMessageInfo } from './index.js';
13
13
  * tree is built from, the fields below are the ones the mailer reads on top of those
14
14
  */
15
15
  export interface SendMailOptions extends MailComposerOptions {
16
+ /**
17
+ * Cancel this send, including waiting for plugins or in an SMTP pool queue.
18
+ * Plugins must cooperate with the signal to stop their own work already in progress.
19
+ * Supported by SMTP, pooled SMTP and transports declaring supportsAbortSignal. Other
20
+ * transports ignore the signal once the message is handed to them; a signal that is
21
+ * already aborted, or aborts during plugin processing, still cancels the send.
22
+ * Fails with AbortError/EABORT on cancellation, ECONFIG if the value is not an AbortSignal.
23
+ * Aborting does not prove that the server has not already accepted the message.
24
+ */
25
+ signal?: AbortSignal | undefined;
16
26
  /** DKIM signing options for this message, used instead of the ones of the transporter */
17
27
  dkim?: DKIMOptions | undefined;
18
28
  /** Extra DKIM options for this message, merged over the options of the signer. The SES transport sets skipFields here, the option is not meant for callers */
@@ -74,7 +74,8 @@ export declare function hasLongerLines(str: string, lineLength: number): boolean
74
74
  */
75
75
  export declare function encodeWord(data: string | Buffer, mimeWordEncoding?: string, maxLength?: number): string;
76
76
  /**
77
- * Finds word sequences with non ascii text and converts these to mime words
77
+ * Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
78
+ * and converts these to mime words. A valid encoded-word is passed through as it is.
78
79
  *
79
80
  * @param value String to be encoded
80
81
  * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
@@ -132,8 +132,75 @@ export function encodeWord(data, mimeWordEncoding, maxLength) {
132
132
  }
133
133
  return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?=');
134
134
  }
135
+ // An encoded-word as RFC 2047 section 2 spells it: a charset token (with an optional RFC 2231
136
+ // language), B or Q, and encoded text without '?' or whitespace. None of the parts can hold the
137
+ // '?' that separates them, so the pattern never backtracks
138
+ const VALID_ENCODED_WORD = /^=\?[^\s()<>@,;:"/[\]?.=]+\?[BbQq]\?[^?\s]+\?=$/;
139
+ // What a lenient decoder reads as an encoded-word: libmime and Python decode
140
+ // '=?utf-8?Q?a b?=' across the space as well. Applied sticky at a '=?', and every part stops
141
+ // at the next '?', so it does not backtrack either
142
+ const LENIENT_ENCODED_WORD = /[=]\?[^?]*\?[BbQq]\?[^?]*\?=/y;
135
143
  /**
136
- * Finds word sequences with non ascii text and converts these to mime words
144
+ * Marks the text a receiver would read as an encoded-word when it is not one valid encoded-word
145
+ * on its own. RFC 2047 section 7 requires that a word beginning with '=?' and ending with '?='
146
+ * is a valid encoded-word, and decoders also decode a look-alike that spans whitespace, so
147
+ * '=?utf-8?X?x?=' and 'see =?utf-8?Q?a b?= here' read differently on every receiver. A valid
148
+ * encoded-word is left alone, which is what lets a caller pass a value that is already encoded,
149
+ * as most other mail libraries do.
150
+ *
151
+ * The bounds of the word around each '=?' are found once per word and reused, walking back to
152
+ * the start of a long word from every '=?' it holds would be quadratic.
153
+ *
154
+ * @param value String to look in
155
+ * @param range The first and the last offset that needs encoding so far, -1 for none
156
+ * @return The range, widened to cover the words of every invalid look-alike
157
+ */
158
+ function _markInvalidEncodedWords(value, range) {
159
+ const len = value.length;
160
+ const isSpace = (pos) => /\s/.test(value.charAt(pos));
161
+ // the word last looked at, its start and the offset just past it
162
+ let wordStart = 0;
163
+ let wordEnd = -1;
164
+ const wordAt = (pos) => {
165
+ if (pos < wordEnd) {
166
+ return;
167
+ }
168
+ // the previous word ended at whitespace, so the walk back stops before reaching it
169
+ wordStart = pos;
170
+ while (wordStart > 0 && !isSpace(wordStart - 1)) {
171
+ wordStart--;
172
+ }
173
+ wordEnd = pos;
174
+ while (wordEnd < len && !isSpace(wordEnd)) {
175
+ wordEnd++;
176
+ }
177
+ };
178
+ let pos = value.indexOf('=?');
179
+ while (pos >= 0) {
180
+ wordAt(pos);
181
+ const start = wordStart;
182
+ LENIENT_ENCODED_WORD.lastIndex = pos;
183
+ const match = LENIENT_ENCODED_WORD.exec(value);
184
+ const end = match ? pos + match[0].length : wordEnd;
185
+ if (match && end > wordEnd) {
186
+ // the look-alike runs across whitespace, on to the word it ends in
187
+ wordAt(end - 1);
188
+ }
189
+ const word = value.substring(start, wordEnd);
190
+ // without a match, a word that begins with '=?' and ends with '?=' is still invalid
191
+ const looksLike = match ? true : start === pos && word.length >= 4 && word.endsWith('?=');
192
+ const valid = start === pos && wordEnd === end && word.length <= 75 && VALID_ENCODED_WORD.test(word);
193
+ if (looksLike && !valid) {
194
+ range[0] = range[0] < 0 ? start : Math.min(range[0], start);
195
+ range[1] = Math.max(range[1], wordEnd - 1);
196
+ }
197
+ pos = value.indexOf('=?', match ? end : pos + 2);
198
+ }
199
+ return range;
200
+ }
201
+ /**
202
+ * Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
203
+ * and converts these to mime words. A valid encoded-word is passed through as it is.
137
204
  *
138
205
  * @param value String to be encoded
139
206
  * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
@@ -157,11 +224,14 @@ export function encodeWords(value, mimeWordEncoding, maxLength, encodeAll) {
157
224
  lastSpecial = i;
158
225
  }
159
226
  }
227
+ if (value.indexOf('=?') >= 0) {
228
+ [firstSpecial, lastSpecial] = _markInvalidEncodedWords(value, [firstSpecial, lastSpecial]);
229
+ }
160
230
  if (firstSpecial < 0) {
161
231
  return value;
162
232
  }
163
233
  if (encodeAll) {
164
- // if it is requested to encode everything or the string contains something that resebles encoded word, then encode everything
234
+ // the value needs encoding and it is requested to encode everything
165
235
  return encodeWord(value, mimeWordEncoding, maxLength);
166
236
  }
167
237
  // encode from the start of the word holding the first such character to the end of the