nodemailer 10.0.13 → 10.0.14

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 (49) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cjs/addressparser/index.d.ts +0 -1
  3. package/dist/cjs/addressparser/index.js +55 -17
  4. package/dist/cjs/dkim/message-parser.js +28 -4
  5. package/dist/cjs/dkim/sign.d.ts +1 -0
  6. package/dist/cjs/dkim/sign.js +1 -0
  7. package/dist/cjs/mailer/index.d.ts +7 -1
  8. package/dist/cjs/mime-funcs/index.d.ts +2 -1
  9. package/dist/cjs/mime-funcs/index.js +197 -83
  10. package/dist/cjs/mime-node/index.js +2 -1
  11. package/dist/cjs/nodemailer.d.ts +13 -2
  12. package/dist/cjs/package-info.d.ts +1 -1
  13. package/dist/cjs/package-info.js +1 -1
  14. package/dist/cjs/punycode/index.js +1 -0
  15. package/dist/cjs/ses-transport/index.d.ts +6 -1
  16. package/dist/cjs/shared/index.d.ts +25 -1
  17. package/dist/cjs/shared/index.js +1 -0
  18. package/dist/cjs/smtp-connection/http-proxy-client.d.ts +11 -3
  19. package/dist/cjs/smtp-connection/http-proxy-client.js +17 -7
  20. package/dist/cjs/smtp-connection/index.d.ts +1 -1
  21. package/dist/cjs/smtp-connection/index.js +15 -1
  22. package/dist/cjs/smtp-pool/index.d.ts +6 -1
  23. package/dist/cjs/smtp-transport/index.d.ts +6 -1
  24. package/dist/cjs/well-known/services.js +6 -0
  25. package/dist/esm/addressparser/index.d.ts +0 -1
  26. package/dist/esm/addressparser/index.js +55 -17
  27. package/dist/esm/dkim/message-parser.js +28 -4
  28. package/dist/esm/dkim/sign.d.ts +1 -0
  29. package/dist/esm/dkim/sign.js +1 -0
  30. package/dist/esm/mailer/index.d.ts +7 -1
  31. package/dist/esm/mime-funcs/index.d.ts +2 -1
  32. package/dist/esm/mime-funcs/index.js +197 -83
  33. package/dist/esm/mime-node/index.js +2 -1
  34. package/dist/esm/nodemailer.d.ts +13 -2
  35. package/dist/esm/package-info.d.ts +1 -1
  36. package/dist/esm/package-info.js +1 -1
  37. package/dist/esm/punycode/index.js +1 -0
  38. package/dist/esm/ses-transport/index.d.ts +6 -1
  39. package/dist/esm/shared/index.d.ts +25 -1
  40. package/dist/esm/shared/index.js +1 -0
  41. package/dist/esm/smtp-connection/http-proxy-client.d.ts +11 -3
  42. package/dist/esm/smtp-connection/http-proxy-client.js +17 -7
  43. package/dist/esm/smtp-connection/index.d.ts +1 -1
  44. package/dist/esm/smtp-connection/index.js +15 -1
  45. package/dist/esm/smtp-pool/index.d.ts +6 -1
  46. package/dist/esm/smtp-transport/index.d.ts +6 -1
  47. package/dist/esm/well-known/services.js +6 -0
  48. package/dist/well-known/services.json +7 -0
  49. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## [10.0.14](https://github.com/nodemailer/nodemailer/compare/v10.0.13...v10.0.14) (2026-10-03)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **addressparser:** keep a quoted display name that holds no "@" out of the address ([3570d26](https://github.com/nodemailer/nodemailer/commit/3570d26c7b55f6e5df50d4076046600ad3fd040b))
9
+ * **addressparser:** keep the group recursion depth out of the options object ([a680254](https://github.com/nodemailer/nodemailer/commit/a68025405a1378c82e78f64ffad27b92c1035cbe))
10
+ * **addressparser:** stop a "[" from hiding the operators after it ([5619784](https://github.com/nodemailer/nodemailer/commit/561978491d5cc33d2052a6c89a499b838b960262))
11
+ * **dkim:** trim a header field name in linear time ([c6f7a55](https://github.com/nodemailer/nodemailer/commit/c6f7a55a2978bf031b8519ebf59baddf94c032c8))
12
+ * **mime-funcs:** read and write header parameters per rfc2045 and rfc2231 ([b8ccad7](https://github.com/nodemailer/nodemailer/commit/b8ccad723a7e49a674a4d70f32eb9fe77312008d))
13
+ * search only the new bytes for the end of the proxy CONNECT response ([81efd7b](https://github.com/nodemailer/nodemailer/commit/81efd7bfc559305f900d6a22b5c56aa94556002b))
14
+
3
15
  ## [10.0.13](https://github.com/nodemailer/nodemailer/compare/v10.0.12...v10.0.13) (2026-09-30)
4
16
 
5
17
 
@@ -39,7 +39,6 @@ export type Address = MailboxAddress | GroupAddress;
39
39
  *
40
40
  * @param str Address field
41
41
  * @param options Optional options object
42
- * @param options._depth Internal recursion depth counter (do not set manually)
43
42
  * @return An array of address objects
44
43
  */
45
44
  declare function addressparser(str: string | null | undefined, options: AddressParserOptions & {
@@ -428,7 +428,7 @@ function _handleAddress(tokens, depth) {
428
428
  // Parse group members, but flatten any nested groups (RFC 5322 doesn't allow nesting)
429
429
  let groupMembers = [];
430
430
  if (data.group.length) {
431
- const parsedGroup = addressparser(data.group.join(','), { _depth: depth + 1 });
431
+ const parsedGroup = _parseAddressList(data.group.join(','), depth + 1);
432
432
  parsedGroup.forEach(member => {
433
433
  if (member.group) {
434
434
  groupMembers = groupMembers.concat(member.group);
@@ -515,7 +515,13 @@ function _handleAddress(tokens, depth) {
515
515
  // Join values with spaces
516
516
  data.text = data.text.join(' ');
517
517
  data.address = data.address.join(' ');
518
- if (addressFromQuotedText && data.text) {
518
+ if (addressFromQuotedText && data.text.indexOf('@') >= 0) {
519
+ // A quoted run with no '@' in it is a display name and nothing else, so it stays
520
+ // where it is. Moving it over anyway made a comment the mailbox was read from:
521
+ // '"Display Name" <(a comment)>' handed on 'Display Name' as the address with the
522
+ // comment as the name, and a quoted name holding a ',' or a ';' became an address
523
+ // that reads as two recipients once a consumer writes it back into a header.
524
+ //
519
525
  // The mailbox is still sitting in the text, so it moves over here and is quoted
520
526
  // before the recovery below rather than after it. Anything else the text holds
521
527
  // came along with it: a comment ends the domain but leaves the atoms behind it in
@@ -562,6 +568,7 @@ class Tokenizer {
562
568
  this.node = null;
563
569
  this.escaped = false;
564
570
  this.inDomainLiteral = false;
571
+ this.afterAt = false;
565
572
  this.list = [];
566
573
  /**
567
574
  * Operator tokens and which tokens are expected to end the sequence
@@ -605,17 +612,23 @@ class Tokenizer {
605
612
  * Checks if a character is an operator or text and acts accordingly
606
613
  *
607
614
  * @param chr Character from the address field
615
+ * @param nextChr Character following chr, null at the end of the field
608
616
  */
609
617
  checkChar(chr, nextChr) {
610
- // Track RFC 5322 domain-literals ("[" *dtext "]"). Operator characters such
611
- // as the ":" of an IPv6 address-literal (user@[IPv6:2001:db8::1]) are dtext
612
- // and must not be treated as the group delimiter while inside the brackets.
613
- // Quoted strings and comments are handled separately via operatorExpecting,
614
- // so only enter this state when no operator is open. The list separators ","
615
- // and ";" are the exception: they always end the literal (and split the
616
- // address list) so that an unclosed "[" cannot swallow later recipients.
618
+ // Track RFC 5322 domain-literals ("[" *dtext "]"). The ":" of an IPv6
619
+ // address-literal (user@[IPv6:2001:db8::1]) is dtext and must not be treated as
620
+ // the group delimiter while inside the brackets. That is the only operator the
621
+ // literal hides: letting it hide the others as well meant a "[" could turn the
622
+ // comment, quoted string or angle-addr after it into text and pick a different
623
+ // mailbox, '[ ( ] <a@victim.com> ) <b@evil.com>' yielded a@victim.com where
624
+ // RFC 5322 reads b@evil.com. A "[" also only opens a literal right after the "@"
625
+ // of an addr-spec, so the group delimiter of a display name holding one stays
626
+ // intact. Quoted strings and comments are handled separately via
627
+ // operatorExpecting, so only enter this state when no operator is open. The list
628
+ // separators "," and ";" always end the literal (and split the address list) so
629
+ // that an unclosed "[" cannot swallow later recipients.
617
630
  if (!this.escaped && !this.operatorExpecting) {
618
- if (!this.inDomainLiteral && chr === '[') {
631
+ if (!this.inDomainLiteral && chr === '[' && this.afterAt) {
619
632
  this.inDomainLiteral = true;
620
633
  }
621
634
  else if (this.inDomainLiteral && (chr === ']' || chr === ',' || chr === ';')) {
@@ -635,17 +648,24 @@ class Tokenizer {
635
648
  }
636
649
  this.list.push(this.node);
637
650
  this.node = null;
651
+ if (chr !== ')') {
652
+ // a comment is folding whitespace, it does not part the "@" from the "["
653
+ this.afterAt = false;
654
+ }
638
655
  this.operatorExpecting = '';
639
656
  this.escaped = false;
640
657
  return;
641
658
  }
642
- else if (!this.operatorExpecting && !this.inDomainLiteral && chr in this.operators) {
659
+ else if (!this.operatorExpecting && !(this.inDomainLiteral && chr === ':') && chr in this.operators) {
643
660
  this.node = {
644
661
  type: 'operator',
645
662
  value: chr
646
663
  };
647
664
  this.list.push(this.node);
648
665
  this.node = null;
666
+ if (chr !== '(') {
667
+ this.afterAt = false;
668
+ }
649
669
  this.operatorExpecting = this.operators[chr];
650
670
  this.escaped = false;
651
671
  return;
@@ -669,6 +689,11 @@ class Tokenizer {
669
689
  if (chr.charCodeAt(0) >= 0x21 || [' ', '\t'].includes(chr)) {
670
690
  // skip command bytes
671
691
  this.node.value += chr;
692
+ // text inside a quoted string or a comment is not part of an addr-spec. Tracked
693
+ // as it goes rather than read back off the value (see lastChars in _handleAddress)
694
+ if (!this.operatorExpecting && chr !== ' ' && chr !== '\t') {
695
+ this.afterAt = chr === '@';
696
+ }
672
697
  }
673
698
  this.escaped = false;
674
699
  }
@@ -679,9 +704,19 @@ class Tokenizer {
679
704
  * malicious input that could cause stack overflow.
680
705
  */
681
706
  const MAX_NESTED_GROUP_DEPTH = 50;
682
- function addressparser(str, options) {
683
- options = options || {};
684
- const depth = options._depth || 0;
707
+ /**
708
+ * Parses an address list, recursing into the groups it holds.
709
+ *
710
+ * The depth is threaded through the calls rather than carried in an options object, so a
711
+ * caller supplied one can not seed it and lift the recursion limit: `{ _depth: -1e9 }`
712
+ * bought a billion levels of nesting and turned the guard below into the stack overflow it
713
+ * is there to prevent.
714
+ *
715
+ * @param str Address field
716
+ * @param depth Current recursion depth for nested group protection
717
+ * @return An array of address objects
718
+ */
719
+ function _parseAddressList(str, depth) {
685
720
  // Prevent stack overflow from deeply nested groups (DoS protection)
686
721
  if (depth > MAX_NESTED_GROUP_DEPTH) {
687
722
  return [];
@@ -690,7 +725,7 @@ function addressparser(str, options) {
690
725
  const tokens = tokenizer.tokenize();
691
726
  const addresses = [];
692
727
  let address = [];
693
- let parsedAddresses = [];
728
+ const parsedAddresses = [];
694
729
  tokens.forEach(token => {
695
730
  if (token.type === 'operator' && (token.value === ',' || token.value === ';')) {
696
731
  if (address.length) {
@@ -731,8 +766,11 @@ function addressparser(str, options) {
731
766
  }
732
767
  }
733
768
  mergedAddresses.reverse();
734
- parsedAddresses = mergedAddresses;
735
- if (options.flatten) {
769
+ return mergedAddresses;
770
+ }
771
+ function addressparser(str, options) {
772
+ const parsedAddresses = _parseAddressList(str, 0);
773
+ if (options?.flatten) {
736
774
  const flatAddresses = [];
737
775
  const walkAddressList = (list) => {
738
776
  list.forEach(entry => {
@@ -1,6 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const node_stream_1 = require("node:stream");
4
+ /**
5
+ * Drops the SP and HTAB from both ends of a field name.
6
+ *
7
+ * An index scan rather than `/^[ \t]+|[ \t]+$/g`, which retries the trailing branch at
8
+ * every offset of a blank run that is followed by other text: the run is consumed greedily,
9
+ * `$` fails, and the engine gives the characters back one at a time before moving on to
10
+ * start the same walk one offset further in. A field name carrying a 128 KiB run of spaces
11
+ * between two atoms took about 6.7 seconds to trim, and the cost grows with its square.
12
+ *
13
+ * Not `.trim()`, which takes the other Unicode spaces along: an NBSP in front of a field
14
+ * name would come off and select the name into the signed set, where the relaxed
15
+ * canonicalization in sign.ts deliberately leaves everything but SP and HTAB alone.
16
+ *
17
+ * @param str Field name to trim
18
+ * @return The field name without the surrounding SP and HTAB
19
+ */
20
+ function _trimFieldName(str) {
21
+ let start = 0;
22
+ let end = str.length;
23
+ while (start < end && (str.charCodeAt(start) === 0x20 || str.charCodeAt(start) === 0x09)) {
24
+ start++;
25
+ }
26
+ while (end > start && (str.charCodeAt(end - 1) === 0x20 || str.charCodeAt(end - 1) === 0x09)) {
27
+ end--;
28
+ }
29
+ return str.slice(start, end);
30
+ }
4
31
  /**
5
32
  * MessageParser instance is a transform stream that separates message headers
6
33
  * from the rest of the body. Headers are emitted with the 'headers' event. Message
@@ -143,10 +170,7 @@ class MessageParser extends node_stream_1.Transform {
143
170
  return lines
144
171
  .filter(line => /[^ \t\r]/.test(line))
145
172
  .map(line => ({
146
- key: line
147
- .substr(0, line.indexOf(':'))
148
- .replace(/^[ \t]+|[ \t]+$/g, '')
149
- .toLowerCase(),
173
+ key: _trimFieldName(line.substr(0, line.indexOf(':'))).toLowerCase(),
150
174
  line
151
175
  }));
152
176
  }
@@ -36,6 +36,7 @@ export interface DKIMRelaxedHeaders {
36
36
  * Returns DKIM signature header line
37
37
  *
38
38
  * @param headers Parsed headers object from MessageParser
39
+ * @param hashAlgo Hash algorithm the body hash was calculated with, for example "sha256"
39
40
  * @param bodyHash Base64 encoded hash of the message
40
41
  * @param options DKIM options
41
42
  * @param options.domainName Domain name to be signed for
@@ -52,6 +52,7 @@ function unsupportedHashAlgoError(hashAlgo) {
52
52
  * Returns DKIM signature header line
53
53
  *
54
54
  * @param headers Parsed headers object from MessageParser
55
+ * @param hashAlgo Hash algorithm the body hash was calculated with, for example "sha256"
55
56
  * @param bodyHash Base64 encoded hash of the message
56
57
  * @param options DKIM options
57
58
  * @param options.domainName Domain name to be signed for
@@ -193,9 +193,15 @@ declare class Mail<out T = SentMessageInfo, out D extends TransportOptions = Tra
193
193
  * Sends an email using the preselected transport object
194
194
  *
195
195
  * @param data E-data description
196
- * @param callback Callback to run once the sending succeeded or failed
196
+ * @returns Promise that resolves with the result of the send
197
197
  */
198
198
  sendMail(data: SendMailOptions): Promise<T>;
199
+ /**
200
+ * Sends an email using the preselected transport object
201
+ *
202
+ * @param data E-data description
203
+ * @param callback Callback to run once the sending succeeded or failed
204
+ */
199
205
  sendMail(data: SendMailOptions, callback: SendMailCallback<T>): void;
200
206
  getVersionString(): string;
201
207
  /**
@@ -59,6 +59,7 @@ export declare function quoteString(value?: string): string;
59
59
  * no need to encode the values in any way. If the value is plaintext but has
60
60
  * longer lines then allowed, then use format=flowed
61
61
  *
62
+ * @param str Multi line string to check
62
63
  * @param lineLength Max line length to check for
63
64
  * @returns Returns true if there is at least one line longer than lineLength chars
64
65
  */
@@ -100,9 +101,9 @@ export declare function buildHeaderValue(structured: StructuredHeaderValue): str
100
101
  * title*0*=utf-8''unicode
101
102
  * title*1*=%20string
102
103
  *
104
+ * @param key Parameter name the generated keys are built from, for example title
103
105
  * @param data String to be encoded
104
106
  * @param [maxLength=50] Max length for generated chunks
105
- * @param [fromCharset='UTF-8'] Source sharacter set
106
107
  * @return A list of encoded keys and headers
107
108
  */
108
109
  export declare function buildHeaderParam(key: string, data: string | Buffer, maxLength?: number): EncodedHeaderParam[];
@@ -88,6 +88,7 @@ function quoteString(value) {
88
88
  * no need to encode the values in any way. If the value is plaintext but has
89
89
  * longer lines then allowed, then use format=flowed
90
90
  *
91
+ * @param str Multi line string to check
91
92
  * @param lineLength Max line length to check for
92
93
  * @returns Returns true if there is at least one line longer than lineLength chars
93
94
  */
@@ -234,7 +235,10 @@ function buildHeaderValue(structured) {
234
235
  }
235
236
  });
236
237
  }
237
- else if (/[\s'"\\;:/=(),<>@[\]?]|^-/.test(value)) {
238
+ else if (!value.length || /[\s'"\\;:/=(),<>@[\]?]|^-/.test(value)) {
239
+ // a parameter value is a token or a quoted-string and a token is never empty, so
240
+ // a valueless parameter such as the 'flag' of 'multipart/mixed; flag; boundary=b'
241
+ // goes out as 'flag=""' rather than as the 'flag=' that parses as neither
238
242
  paramsArray.push(param + '=' + JSON.stringify(value));
239
243
  }
240
244
  else {
@@ -256,9 +260,9 @@ function buildHeaderValue(structured) {
256
260
  * title*0*=utf-8''unicode
257
261
  * title*1*=%20string
258
262
  *
263
+ * @param key Parameter name the generated keys are built from, for example title
259
264
  * @param data String to be encoded
260
265
  * @param [maxLength=50] Max length for generated chunks
261
- * @param [fromCharset='UTF-8'] Source sharacter set
262
266
  * @return A list of encoded keys and headers
263
267
  */
264
268
  function buildHeaderParam(key, data, maxLength) {
@@ -385,6 +389,26 @@ function buildHeaderParam(key, data, maxLength) {
385
389
  value: item.line
386
390
  }));
387
391
  }
392
+ /**
393
+ * An RFC 2045 token: printable ASCII without SPACE, the control characters, DEL and the
394
+ * tspecials. A charset name is one, and the name a continuation carries is written into
395
+ * the encoded word the parameter value becomes, so it is checked against this before it
396
+ * goes in. Whitespace used to come off it only because the value was trimmed first.
397
+ */
398
+ const TOKEN = /^[^\x00-\x20\x7f()<>@,;:\\"/[\]?=]+$/;
399
+ /**
400
+ * Whether a string can be a header parameter name.
401
+ *
402
+ * A parameter name is a token, so it is never empty. A "__proto__" name would target the
403
+ * prototype chain of the params object instead of an own property of it and read back as
404
+ * Object.prototype, so it is no name either.
405
+ *
406
+ * @param name Candidate parameter name, already lowercased
407
+ * @return true when the name can be used
408
+ */
409
+ function _isParamName(name) {
410
+ return !!name && !(0, objects_js_1.isProtoKey)(name);
411
+ }
388
412
  /**
389
413
  * Parses a header value with key=value arguments into a structured
390
414
  * object.
@@ -405,134 +429,224 @@ function parseHeaderValue(str) {
405
429
  value: '',
406
430
  params: {}
407
431
  };
408
- // Parameter names come from a caller supplied contentType/contentDisposition. A
409
- // "__proto__" name would target the prototype chain of the params object instead of
410
- // an own property of it, and read back as Object.prototype, so it is dropped.
432
+ // A duplicated parameter resolves to its first occurrence, the way a duplicated header
433
+ // does. Letting the last one win disagrees with the receivers that take the first, and
434
+ // the two readings of 'boundary="b"; boundary="c"' name different delimiters. The
435
+ // continuation join below is the only writer of the name it builds, so it tests the
436
+ // name with _isParamName directly rather than taking that rule along from here.
411
437
  const setParam = (name, value) => {
412
- if (!(0, objects_js_1.isProtoKey)(name)) {
438
+ name = name.toLowerCase();
439
+ if (_isParamName(name) && !Object.prototype.hasOwnProperty.call(response.params, name)) {
413
440
  response.params[name] = value;
414
441
  }
415
442
  };
416
443
  let key = false;
417
444
  let value = '';
418
- let type = 'value';
445
+ let stage = 'value';
419
446
  let quote = false;
420
447
  let escaped = false;
421
448
  let chr;
449
+ // Whitespace seen outside a quoted string is held back until a significant character
450
+ // follows it, so the whitespace around a value is dropped without trimming spaces the
451
+ // sender quoted on purpose. Trimming the stored value instead loses the trailing space
452
+ // of 'filename*0="Annual Report "', which the next continuation section is appended to.
453
+ let pendingSpace = '';
454
+ let quoteClosed = false;
455
+ // Whitespace ahead of the first character of a value is padding and is dropped, the
456
+ // whitespace between two characters of it is content
457
+ const flushSpace = () => {
458
+ if (value.length) {
459
+ value += pendingSpace;
460
+ }
461
+ pendingSpace = '';
462
+ };
463
+ const addChr = (c) => {
464
+ flushSpace();
465
+ value += c;
466
+ };
467
+ const takeValue = () => {
468
+ const taken = value;
469
+ value = '';
470
+ pendingSpace = '';
471
+ quoteClosed = false;
472
+ return taken;
473
+ };
474
+ const storeValue = () => {
475
+ const taken = takeValue();
476
+ if (key === false) {
477
+ response.value = taken;
478
+ }
479
+ else {
480
+ setParam(key, taken);
481
+ }
482
+ };
483
+ // A parameter name with no '=' is a valueless parameter, not the start of the next one.
484
+ // Without this the name keeps growing across the ';' and swallows whatever follows, which
485
+ // is how 'multipart/mixed; flag; boundary="AAA"' lost its boundary to a parameter named
486
+ // 'flag; boundary' and left the node declaring the generated boundary beside the asked
487
+ // for one, so a receiver reading the first of the two found no delimiter it matched.
488
+ const storeEmptyKey = () => {
489
+ setParam(takeValue().trim(), '');
490
+ };
422
491
  for (let i = 0, len = str.length; i < len; i++) {
423
492
  chr = str.charAt(i);
424
- if (type === 'key') {
493
+ if (stage === 'key') {
425
494
  if (chr === '=') {
426
- key = value.trim().toLowerCase();
427
- type = 'value';
428
- value = '';
495
+ key = takeValue().trim();
496
+ stage = 'value';
497
+ continue;
498
+ }
499
+ if (chr === ';') {
500
+ storeEmptyKey();
429
501
  continue;
430
502
  }
431
503
  value += chr;
432
504
  }
433
505
  else {
506
+ if (quoteClosed && chr !== ';') {
507
+ // Nothing behind a closed quoted string reaches the value. RFC 2045 says a
508
+ // parameter value is a token or a quoted string and not both, so what follows
509
+ // one is junk and only the ';' that ends the parameter still counts. Tested
510
+ // ahead of the branches rather than beside the append at the foot of them,
511
+ // where each branch above was a way around it: a second '"' reopened quoting
512
+ // and swallowed the rest of the header, so 'boundary="AAA" "; boundary=BBB"'
513
+ // read as a single boundary of 'AAA ', and the junk of
514
+ // 'boundary="AAA" (unterminated comment' still joined the declared boundary
515
+ // through the escape branch. quoteClosed is only ever set while no quote is
516
+ // open, and this is what keeps one from being opened afterwards.
517
+ escaped = false;
518
+ continue;
519
+ }
434
520
  if (escaped) {
435
- value += chr;
521
+ addChr(chr);
436
522
  }
437
- else if (chr === '\\') {
523
+ else if (quote && chr === '\\') {
524
+ // a backslash only escapes inside a quoted string, everywhere else it is an
525
+ // ordinary character. Treating it as an escape turns the parameter value
526
+ // 'C:\Users\me\report.txt' into 'C:Usersmereport.txt'
438
527
  escaped = true;
439
528
  continue;
440
529
  }
441
530
  else if (quote && chr === quote) {
442
531
  quote = false;
532
+ quoteClosed = true;
443
533
  }
444
534
  else if (!quote && chr === '"') {
445
535
  quote = chr;
536
+ flushSpace();
446
537
  }
447
538
  else if (!quote && chr === ';') {
448
- if (key === false) {
449
- response.value = value.trim();
450
- }
451
- else {
452
- setParam(key, value.trim());
453
- }
454
- type = 'key';
455
- value = '';
539
+ storeValue();
540
+ stage = 'key';
541
+ }
542
+ else if (!quote && (chr === ' ' || chr === '\t')) {
543
+ pendingSpace += chr;
456
544
  }
457
545
  else {
458
- value += chr;
546
+ addChr(chr);
459
547
  }
460
548
  escaped = false;
461
549
  }
462
550
  }
463
- if (type === 'value') {
464
- if (key === false) {
465
- response.value = value.trim();
466
- }
467
- else {
468
- setParam(key, value.trim());
469
- }
551
+ if (stage === 'value') {
552
+ storeValue();
470
553
  }
471
- else if (value.trim()) {
472
- setParam(value.trim().toLowerCase(), '');
554
+ else {
555
+ // a key with no value, as in 'Header-Key: somevalue; key=value; emptykey'
556
+ storeEmptyKey();
473
557
  }
474
558
  // handle parameter value continuations
475
559
  // https://tools.ietf.org/html/rfc2231#section-3
476
- // preprocess values
560
+ // Sections are collected in a list and ordered below rather than written into an array
561
+ // at their own section number. An index write makes the array as long as the number the
562
+ // header asked for, and the join that follows walks all of it, so the 55 byte value
563
+ // "attachment; filename*0*=utf-8''a; filename*4000000000=b" held a core for over two
564
+ // minutes.
565
+ const continuations = new Map();
477
566
  Object.keys(response.params).forEach(key => {
478
- let actualKey, nr, match, value;
479
- if ((match = key.match(/(\*(\d+)|\*(\d+)\*|\*)$/))) {
480
- actualKey = key.substr(0, match.index);
481
- nr = Number(match[2] || match[3]) || 0;
482
- if ((0, objects_js_1.isProtoKey)(actualKey)) {
483
- // see setParam. Reading it back would yield Object.prototype, which is
484
- // an object, so the initializer below would be skipped and the write
485
- // that follows would throw out of a header build the caller can not catch
486
- delete response.params[key];
487
- return;
488
- }
489
- if (!response.params[actualKey] || typeof response.params[actualKey] !== 'object') {
490
- response.params[actualKey] = {
491
- charset: false,
492
- values: []
493
- };
494
- }
495
- value = response.params[key];
496
- if (nr === 0 && match[0].substr(-1) === '*' && (match = value.match(/^([^']*)'[^']*'(.*)$/))) {
497
- response.params[actualKey].charset = match[1] || 'iso-8859-1';
498
- value = match[2];
499
- }
500
- response.params[actualKey].values[nr] = value;
501
- // remove the old reference
502
- delete response.params[key];
567
+ const match = key.match(/(\*(\d+)|\*(\d+)\*|\*)$/);
568
+ if (!match) {
569
+ // not a continuation parameter, there is nothing to join
570
+ return;
571
+ }
572
+ const actualKey = key.substr(0, match.index);
573
+ const nr = Number(match[2] || match[3]) || 0;
574
+ // RFC 2231 section 4.1: only a section whose name ends in '*' is percent encoded
575
+ const encoded = match[0].substr(-1) === '*';
576
+ // remove the old reference
577
+ let value = response.params[key];
578
+ delete response.params[key];
579
+ if (!_isParamName(actualKey)) {
580
+ // the joined value can not be written back under this name. It is empty when the
581
+ // continuation suffix was all there was of it, as in the bare '*' of 'text/plain; a;*'
582
+ return;
583
+ }
584
+ let continuation = continuations.get(actualKey);
585
+ if (!continuation) {
586
+ continuation = { charset: false, sections: [] };
587
+ continuations.set(actualKey, continuation);
588
+ }
589
+ const charsetMatch = nr === 0 && encoded ? value.match(/^([^']*)'[^']*'(.*)$/) : null;
590
+ if (charsetMatch) {
591
+ // the charset is a token, and anything else named as one is no charset a consumer
592
+ // could resolve, so it reads as the unnamed case rather than being carried into
593
+ // the encoded word below. A "\r\n" of a prefix would otherwise reach a consumer
594
+ // of the parsed value as the charset of a word that no decoder can act on
595
+ continuation.charset = TOKEN.test(charsetMatch[1]) ? charsetMatch[1] : 'iso-8859-1';
596
+ value = charsetMatch[2];
503
597
  }
598
+ continuation.sections.push({ nr, value, encoded });
504
599
  });
505
600
  // concatenate split rfc2231 strings and convert encoded strings to mime encoded words
506
- Object.keys(response.params).forEach(key => {
507
- let value;
508
- if (response.params[key] && Array.isArray(response.params[key].values)) {
509
- value = response.params[key].values.map((val) => val || '').join('');
510
- if (response.params[key].charset) {
511
- // convert "%AB" to "=?charset?Q?=AB?="
512
- response.params[key] =
513
- '=?' +
514
- response.params[key].charset +
515
- '?Q?' +
516
- value
517
- // fix invalidly encoded chars
518
- .replace(/[=?_\s]/g, s => {
519
- const c = s.charCodeAt(0).toString(16);
520
- if (s === ' ') {
521
- return '_';
522
- }
523
- return '%' + (c.length < 2 ? '0' : '') + c;
524
- })
525
- // change from urlencoding to percent encoding
526
- .replace(/%/g, '=') +
527
- '?=';
528
- }
529
- else {
530
- response.params[key] = value;
531
- }
601
+ continuations.forEach((continuation, key) => {
602
+ if (Object.prototype.hasOwnProperty.call(response.params, key)) {
603
+ // The same name was also given as a plain parameter, which the starred keys were
604
+ // just deleted from around, so this write would be the only one in the function
605
+ // to override a name already taken. 'filename=plain.txt; filename*0=evil.txt'
606
+ // resolves to the plain parameter either way round, so the reading does not come
607
+ // down to which of the two spellings the sender put first
608
+ return;
609
+ }
610
+ continuation.sections.sort((a, b) => a.nr - b.nr);
611
+ if (!continuation.charset) {
612
+ // nothing said which charset the percent escapes of an encoded section are in,
613
+ // so every section is passed on as the text it already is
614
+ response.params[key] = continuation.sections.map(section => section.value).join('');
615
+ return;
532
616
  }
617
+ // convert "%AB" to "=?charset?Q?=AB?="
618
+ response.params[key] = '=?' + continuation.charset + '?Q?' + continuation.sections.map(_encodeContinuationSection).join('') + '?=';
533
619
  });
534
620
  return response;
535
621
  }
622
+ /**
623
+ * Renders one parameter value continuation section as the payload of a Q encoded word.
624
+ *
625
+ * A section whose name ends in '*' is percent encoded and its escapes carry the bytes of
626
+ * the value, so they only have to be rewritten into the "=AB" spelling a Q encoded word
627
+ * uses. A section without the '*' is literal text (RFC 2231 section 4.1), so its '%' is a
628
+ * '%' and is escaped along with the characters a Q encoded word can not carry bare.
629
+ * Decoding a literal section invents bytes that never appeared on the wire: it is how the
630
+ * value 'filename*0*=utf-8''safe; filename*1=%2F..%2F..%2Fetc%2Fpasswd' was emitted as a
631
+ * filename every receiving client reads back as 'safe/../../etc/passwd'.
632
+ *
633
+ * @param section One collected continuation section
634
+ * @return The section as Q encoded word payload
635
+ */
636
+ function _encodeContinuationSection(section) {
637
+ const specials = section.encoded ? /[=?_\s]/g : /[=?_\s%]/g;
638
+ return (section.value
639
+ // fix invalidly encoded chars
640
+ .replace(specials, s => {
641
+ const c = s.charCodeAt(0).toString(16);
642
+ if (s === ' ') {
643
+ return '_';
644
+ }
645
+ return '%' + (c.length < 2 ? '0' : '') + c;
646
+ })
647
+ // change from urlencoding to percent encoding
648
+ .replace(/%/g, '='));
649
+ }
536
650
  /**
537
651
  * Returns file extension for a content type string. If no suitable extensions
538
652
  * are found, 'bin' is used as the default extension