mirror of
https://github.com/dawidd6/action-send-mail.git
synced 2026-11-21 21:06:12 +07:00
Compare commits
13
Commits
v23
..
node_modules
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a20949df3b | ||
|
|
0989b5499d | ||
|
|
f06d7f3c91 | ||
|
|
aefdaa6a6c | ||
|
|
4a48500d96 | ||
|
|
c7306860e9 | ||
|
|
27bf7a883d | ||
|
|
a9703ed892 | ||
|
|
b6b2177ec4 | ||
|
|
0d58990203 | ||
|
|
f8b8145a29 | ||
|
|
b6d53adeaf | ||
|
|
67d71b1eee |
No files matched your search
+6
-6
@@ -94,9 +94,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "10.2.0",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.2.0.tgz",
|
||||
"integrity": "sha512-/XyGw6kX2stMdKGUJdAQmYAeY1FscWfdRydfd2NtK3A3KDfUUXCqZzExSNAt2xhh90X2qLCR+o2Gd48YPJcJwA==",
|
||||
"version": "10.6.1",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz",
|
||||
"integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
@@ -128,9 +128,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.29.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz",
|
||||
"integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==",
|
||||
"version": "6.29.1",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
|
||||
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
|
||||
+75
@@ -1,5 +1,80 @@
|
||||
# CHANGELOG
|
||||
|
||||
## [10.6.1](https://github.com/nodemailer/nodemailer/compare/v10.6.0...v10.6.1) (2026-11-20)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **dkim:** sign List-Unsubscribe-Post by default ([#1922](https://github.com/nodemailer/nodemailer/issues/1922)) ([f91077c](https://github.com/nodemailer/nodemailer/commit/f91077c5bbc175fbb853d3c1cf3131c30283d52b))
|
||||
* **fetch:** identify cookies by name, domain and path ([#1920](https://github.com/nodemailer/nodemailer/issues/1920)) ([91a298f](https://github.com/nodemailer/nodemailer/commit/91a298fc112017decdeb2b401238e901dd4b2256))
|
||||
|
||||
## [10.6.0](https://github.com/nodemailer/nodemailer/compare/v10.5.0...v10.6.0) (2026-11-15)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **smtp:** add configurable socketCloseTimeout ([#1916](https://github.com/nodemailer/nodemailer/issues/1916)) ([7f04d0b](https://github.com/nodemailer/nodemailer/commit/7f04d0b78e887191c89775cf4a3063462b222aad)), closes [#1915](https://github.com/nodemailer/nodemailer/issues/1915)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* let Set-Cookie Max-Age take precedence over Expires ([#1917](https://github.com/nodemailer/nodemailer/issues/1917)) ([d6d6d44](https://github.com/nodemailer/nodemailer/commit/d6d6d44f5fbdf61936032d8865a1312c89c1804e))
|
||||
* **smtp-connection:** close the TLS socket of an upgraded connection on Node 27 ([4135015](https://github.com/nodemailer/nodemailer/commit/4135015175398aaad5ac6e1866e91a758c432417))
|
||||
|
||||
## [10.5.0](https://github.com/nodemailer/nodemailer/compare/v10.4.1...v10.5.0) (2026-11-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **smtp:** support AbortSignal for individual sends ([#1911](https://github.com/nodemailer/nodemailer/issues/1911)) ([66387ed](https://github.com/nodemailer/nodemailer/commit/66387ed6f4bd26208b944b74b7329201ad77377b)), closes [#1910](https://github.com/nodemailer/nodemailer/issues/1910)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **dkim:** encode the d= domain the same way as the address headers ([#1908](https://github.com/nodemailer/nodemailer/issues/1908)) ([4ebf03f](https://github.com/nodemailer/nodemailer/commit/4ebf03fba33a96118c10afa340ce895a00549148))
|
||||
* **mime-funcs:** encode header text that would be decoded as an invalid encoded word ([#1912](https://github.com/nodemailer/nodemailer/issues/1912)) ([7a7b942](https://github.com/nodemailer/nodemailer/commit/7a7b9427b632d8785190747ae2c62e88e77bc837))
|
||||
|
||||
## [10.4.1](https://github.com/nodemailer/nodemailer/compare/v10.4.0...v10.4.1) (2026-11-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **addressparser:** read whitespace and comments around a dot of the domain as CFWS ([c2b9c41](https://github.com/nodemailer/nodemailer/commit/c2b9c41bb81b2294ebadd294ad15ff035a17d0a5))
|
||||
* **mime-node:** hand a domain to the UTS-46 mapper without lowercasing it first ([093e4dd](https://github.com/nodemailer/nodemailer/commit/093e4dd60af8a21e7f06a49c7f889291728e966a))
|
||||
|
||||
## [10.4.0](https://github.com/nodemailer/nodemailer/compare/v10.3.1...v10.4.0) (2026-11-07)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* let close({ force: true }) end pooled connections that are delivering a message ([aba943c](https://github.com/nodemailer/nodemailer/commit/aba943cf9d24493aca2a3e043df06beadc728feb))
|
||||
|
||||
## [10.3.1](https://github.com/nodemailer/nodemailer/compare/v10.3.0...v10.3.1) (2026-10-29)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* apply the otp option in MailComposer too ([1d4087f](https://github.com/nodemailer/nodemailer/commit/1d4087f358d124267bddd5eb5e11a4e22fccd3d0))
|
||||
|
||||
## [10.3.0](https://github.com/nodemailer/nodemailer/compare/v10.2.1...v10.3.0) (2026-10-29)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add the otp option for the OTP-Token header ([7789e15](https://github.com/nodemailer/nodemailer/commit/7789e1501e4f555e9754a15664aa30f1415902b9))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* encode a Content-ID header as a message id ([#1904](https://github.com/nodemailer/nodemailer/issues/1904)) ([47f2b25](https://github.com/nodemailer/nodemailer/commit/47f2b252fccc8ec6a1a5700e12c1087ae3633e17))
|
||||
|
||||
## [10.2.1](https://github.com/nodemailer/nodemailer/compare/v10.2.0...v10.2.1) (2026-10-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* drop the comments of a Content-Type or Content-Disposition value with the stripComments option ([b3052b7](https://github.com/nodemailer/nodemailer/commit/b3052b7fe2e49b51dd66d6c7814a072e885f1ac8))
|
||||
|
||||
## [10.2.0](https://github.com/nodemailer/nodemailer/compare/v10.1.7...v10.2.0) (2026-10-21)
|
||||
|
||||
|
||||
|
||||
+25
@@ -14,6 +14,31 @@ See [nodemailer.com](https://nodemailer.com/) for documentation and terms.
|
||||
|
||||
Nodemailer targets Node.js 20 and later. The ES module build also runs on [Bun](https://bun.sh/) (tested against the latest release) and on [Cloudflare Workers](https://developers.cloudflare.com/workers/) with the `nodejs_compat` compatibility flag. On Workers only the SMTP based transports apply, `sendmail` needs a child process, and the runtime does not allow turning certificate validation off, so `tls.rejectUnauthorized: false` fails there with an error.
|
||||
|
||||
## Cancelling an individual SMTP send
|
||||
|
||||
Pass an `AbortSignal` in the message options to cancel one `sendMail()` call:
|
||||
|
||||
```js
|
||||
await transporter.sendMail({
|
||||
from: 'sender@example.com',
|
||||
to: 'recipient@example.com',
|
||||
text: 'Hello',
|
||||
signal: AbortSignal.timeout(30_000)
|
||||
});
|
||||
```
|
||||
|
||||
This is supported by SMTP and pooled SMTP transports. A pre-aborted signal prevents processing; aborting later stops subsequent plugin processing, removes a queued message, or closes the SMTP connection assigned to that message. Other deliveries in the pool can continue. Both promise and callback forms report an error named `AbortError`, with `code: 'EABORT'` and the signal's reason as `cause`. The signal listener is removed when the send finishes.
|
||||
|
||||
Cancellation stops local processing; it does not prove that the SMTP server has not already accepted the message. Do not retry a cancelled send automatically on that assumption.
|
||||
|
||||
Work already started by a plugin or a custom `getSocket` hook requires that code's cooperation to stop. Nodemailer ignores late plugin completion and destroys a socket handed back after cancellation. Plugins can read `mail.data.signal` to cancel their own work.
|
||||
|
||||
Other bundled transports (stream, JSON, sendmail and SES) ignore the signal once the message is handed to them, so the message is sent normally. A signal that is already aborted, or aborts while plugins run, still cancels the send with `EABORT` on every transport, as that happens before the transport is called. A `signal` value that is not an `AbortSignal` fails the send with `ECONFIG`. Custom transports can opt in with `supportsAbortSignal: true`; their `send()` must register its abort listener synchronously, check for a pre-aborted signal, stop the work it owns, invoke its callback once, and remove the listener on completion.
|
||||
|
||||
## SMTP socket close timeout
|
||||
|
||||
When an SMTP connection closes, Nodemailer ends the socket and destroys it if the server has not closed its side within `socketCloseTimeout` milliseconds (default 5000). Set it to `0` to destroy the socket right away. This applies to SMTP and pooled SMTP, including aborted sends and `transporter.close({ force: true })`. It does not tell you whether the server accepted a message that was in flight.
|
||||
|
||||
## Having an issue?
|
||||
|
||||
#### First review the docs
|
||||
|
||||
+185
-2
@@ -48,6 +48,30 @@ class TokenList {
|
||||
this.slots[at + 2] = end;
|
||||
return this.length++;
|
||||
}
|
||||
/**
|
||||
* Offset of the first character of a token that is part of its value. A text run that is
|
||||
* no plain slice of the field still spans the whitespace and control characters its value
|
||||
* is trimmed of.
|
||||
*/
|
||||
contentStart(index) {
|
||||
let start = this.slots[index * 3 + 1];
|
||||
const end = this.slots[index * 3 + 2];
|
||||
while (start < end && _isDroppedCode(this.str.charCodeAt(start))) {
|
||||
start++;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
/**
|
||||
* Offset just past the last character of a token that is part of its value
|
||||
*/
|
||||
contentEnd(index) {
|
||||
const start = this.slots[index * 3 + 1];
|
||||
let end = this.slots[index * 3 + 2];
|
||||
while (end > start && _isDroppedCode(this.str.charCodeAt(end - 1))) {
|
||||
end--;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
/**
|
||||
* The character of an operator token, an empty string for a text run
|
||||
*/
|
||||
@@ -183,6 +207,44 @@ function _isSpaceCode(code) {
|
||||
code === 0x3000 ||
|
||||
code === 0xfeff);
|
||||
}
|
||||
/**
|
||||
* Checks for the whitespace RFC 5322 folding whitespace is made of: SP and HTAB, plus the
|
||||
* line break a fold carries. The other characters _isSpaceCode accepts are atext under
|
||||
* RFC 6532, and parsers disagree on them: mailauth keeps U+00A0 in a domain, so joining a
|
||||
* domain across one names a domain that reader never sees
|
||||
*
|
||||
* @param code Character code
|
||||
* @return true if the character is folding whitespace
|
||||
*/
|
||||
function _isFoldingSpaceCode(code) {
|
||||
return code === 0x20 || code === 0x09 || code === 0x0d || code === 0x0a;
|
||||
}
|
||||
/**
|
||||
* Checks if every character in a stretch of the field is folding whitespace
|
||||
*
|
||||
* @param str The field
|
||||
* @param from Offset of the first character
|
||||
* @param to Offset just past the last one
|
||||
* @return true if the stretch holds nothing but folding whitespace
|
||||
*/
|
||||
function _isFoldingGap(str, from, to) {
|
||||
for (let i = from; i < to; i++) {
|
||||
if (!_isFoldingSpaceCode(str.charCodeAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Checks for a character the value of a text run is trimmed of, or leaves out: whitespace,
|
||||
* C0 controls and DEL
|
||||
*
|
||||
* @param code Character code
|
||||
* @return true if the character is not part of the value at the edge of a run
|
||||
*/
|
||||
function _isDroppedCode(code) {
|
||||
return code < 0x20 || code === 0x7f || _isSpaceCode(code);
|
||||
}
|
||||
/**
|
||||
* The characters JS `\w` matches without the unicode flag, the set the `\b` in
|
||||
* LOOSE_TEXT_ADDR is read against. charCodeAt off either end of the string gives NaN,
|
||||
@@ -233,6 +295,9 @@ const LEADING_QUOTED_STRING = /^"(?:[^"\\]|\\[\s\S])*"/;
|
||||
* The scan is by index, a pattern such as /\s+@/ backtracks over a long whitespace run that
|
||||
* no '@' follows.
|
||||
*
|
||||
* The whitespace around the dots of the domain that follows is dropped as well, see
|
||||
* _joinDomainDotSpacing.
|
||||
*
|
||||
* @param value Value holding the '@'
|
||||
* @param at Offset of the '@', or -1
|
||||
* @return The value with the whitespace beside that '@' removed
|
||||
@@ -249,7 +314,86 @@ function _joinAtSpacing(value, at) {
|
||||
while (end < value.length && _isSpaceCode(value.charCodeAt(end))) {
|
||||
end++;
|
||||
}
|
||||
return start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
|
||||
const joined = start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
|
||||
return _joinDomainDotSpacing(joined, start);
|
||||
}
|
||||
// The ASCII atext characters: printable, and none of the RFC 5322 specials
|
||||
const ASCII_ATEXT = new Uint8Array(0x80);
|
||||
for (let code = 0x21; code < 0x7f; code++) {
|
||||
ASCII_ATEXT[code] = '()<>[]:;@\\,."'.indexOf(String.fromCharCode(code)) < 0 ? 1 : 0;
|
||||
}
|
||||
/**
|
||||
* Checks if a character can be part of an atom: anything but the specials, whitespace and
|
||||
* the control characters (RFC 5322 3.2.3, with non-ASCII allowed as RFC 6532 does)
|
||||
*
|
||||
* @param code Character code
|
||||
* @return true if the character is atext
|
||||
*/
|
||||
function _isAtextCode(code) {
|
||||
return code < 0x80 ? ASCII_ATEXT[code] === 1 : !_isSpaceCode(code);
|
||||
}
|
||||
/**
|
||||
* Drops the whitespace around the dots of the domain behind the '@' at an offset.
|
||||
*
|
||||
* obs-domain is atoms with CFWS around the dots (RFC 5322 4.4), so 'user@victim.example
|
||||
* .allowed.example' names user@victim.example.allowed.example. Read as two runs, the domain
|
||||
* ended at the whitespace and the envelope went to victim.example, a different domain than
|
||||
* the one an RFC 5322 parser, and an application validating the address with one, reads
|
||||
* (GHSA-3q53-mvfw-q9v8). A comment around a dot reaches here as whitespace.
|
||||
*
|
||||
* Only SP, HTAB and a fold count as the whitespace, see _isFoldingSpaceCode.
|
||||
*
|
||||
* Only a dot with an atom on both sides joins, as for a conformant parser: whitespace that
|
||||
* is not beside a dot ends the domain, and so does a dot that no atom follows, which keeps
|
||||
* 'user@example.com .' from becoming a domain with a trailing dot. A domain literal is left
|
||||
* alone. Everything from where the domain ends is kept as it is.
|
||||
*
|
||||
* @param value Value holding the '@'
|
||||
* @param at Offset of the '@'
|
||||
* @return The value with the whitespace around the dots of that domain removed
|
||||
*/
|
||||
function _joinDomainDotSpacing(value, at) {
|
||||
const len = value.length;
|
||||
// '[' is no atext, so a domain literal ends the walk before it starts
|
||||
let pos = at + 1;
|
||||
let spaced = false;
|
||||
for (;;) {
|
||||
const labelStart = pos;
|
||||
while (pos < len && _isAtextCode(value.charCodeAt(pos))) {
|
||||
pos++;
|
||||
}
|
||||
if (pos === labelStart) {
|
||||
break;
|
||||
}
|
||||
// the dot, with the whitespace on either side of it, and the label behind it
|
||||
let next = pos;
|
||||
while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
|
||||
next++;
|
||||
}
|
||||
if (value.charCodeAt(next) !== 0x2e) {
|
||||
break;
|
||||
}
|
||||
next++;
|
||||
while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
|
||||
next++;
|
||||
}
|
||||
if (next >= len || !_isAtextCode(value.charCodeAt(next))) {
|
||||
break;
|
||||
}
|
||||
spaced = spaced || next !== pos + 1;
|
||||
pos = next;
|
||||
}
|
||||
if (!spaced) {
|
||||
return value;
|
||||
}
|
||||
// every whitespace character the walk covered sits beside a dot
|
||||
let domain = '';
|
||||
for (let k = at + 1; k < pos; k++) {
|
||||
if (!_isFoldingSpaceCode(value.charCodeAt(k))) {
|
||||
domain += value.charAt(k);
|
||||
}
|
||||
}
|
||||
return value.slice(0, at + 1) + domain + value.slice(pos);
|
||||
}
|
||||
/**
|
||||
* Drops the whitespace beside the '@' that splits the domain off a value. That is the '@'
|
||||
@@ -553,6 +697,15 @@ function _collectAddressParts(tokens, from, to) {
|
||||
// whether the last text run holds nothing but quoted text so far, which is what a quoted
|
||||
// local part is until the '@' after it joins the run
|
||||
let lastTextPureQuoted = false;
|
||||
// whether the last text run holds an unquoted '@', so that it runs on into a domain, and
|
||||
// whether nothing but comments has come since it, see the join below
|
||||
let lastTextHasAt = false;
|
||||
let lastTextOpen = false;
|
||||
// Where the last text run, or the last comment since it, ended in the field, and whether
|
||||
// everything between it and the comments since was folding whitespace. The tokens are
|
||||
// trimmed of any whitespace, so this is read off the field itself.
|
||||
let gapFrom = 0;
|
||||
let gapsFolding = true;
|
||||
// Last character of the run each state is currently accumulating. Reading it back off
|
||||
// the accumulator with slice(-1) makes the engine flatten the whole growing string on
|
||||
// every token, which is quadratic over an address built from many comment-joined atoms
|
||||
@@ -570,18 +723,27 @@ function _collectAddressParts(tokens, from, to) {
|
||||
case '<':
|
||||
state = 'address';
|
||||
insideQuotes = false;
|
||||
lastTextOpen = false;
|
||||
break;
|
||||
case '(':
|
||||
state = 'comment';
|
||||
insideQuotes = false;
|
||||
gapsFolding = gapsFolding && _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
|
||||
break;
|
||||
case '"':
|
||||
insideQuotes = !insideQuotes;
|
||||
state = 'text';
|
||||
lastTextOpen = false;
|
||||
break;
|
||||
default:
|
||||
state = 'text';
|
||||
insideQuotes = false;
|
||||
if (value !== ')') {
|
||||
lastTextOpen = false;
|
||||
}
|
||||
else {
|
||||
gapFrom = tokens.contentEnd(i);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -598,8 +760,23 @@ function _collectAddressParts(tokens, from, to) {
|
||||
// of the '@', but it cannot join two atoms into one: gluing across it would read
|
||||
// 'user@example.com(x)evil.com' as the single domain 'example.comevil.com' and
|
||||
// deliver to a domain the sender never named.
|
||||
// A comment beside a dot of a domain is CFWS inside obs-domain, with or without
|
||||
// folding whitespace around it, so 'user@victim.example(x).allowed.example' names
|
||||
// one domain (GHSA-3q53-mvfw-q9v8). Any other whitespace in between keeps them apart.
|
||||
// A ')' always leaves the walk in unquoted text, so neither needs checking here.
|
||||
// Neither join across a comment takes in a second '@' once the run holds one: the
|
||||
// address would then split at the last '@', and 'user@company(x).com@attacker.net',
|
||||
// which an RFC 5322 parser reads as user@company.com, would go to attacker.net.
|
||||
const parts = data[state];
|
||||
const joins = prevNoBreak && parts.length && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@');
|
||||
const secondAt = lastTextHasAt && prevOperator === ')' && value.indexOf('@') >= 0;
|
||||
const joinsDomain = !secondAt &&
|
||||
lastTextOpen &&
|
||||
lastTextHasAt &&
|
||||
prevOperator === ')' &&
|
||||
(lastChars.text === '.' || value.charAt(0) === '.') &&
|
||||
gapsFolding &&
|
||||
_isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
|
||||
const joins = joinsDomain || (!secondAt && prevNoBreak && parts.length > 0 && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@'));
|
||||
if (joins) {
|
||||
const last = data[state].length - 1;
|
||||
if (state === 'text' && !insideQuotes) {
|
||||
@@ -624,6 +801,12 @@ function _collectAddressParts(tokens, from, to) {
|
||||
lastTextPureQuoted = insideQuotes;
|
||||
}
|
||||
}
|
||||
if (state === 'text') {
|
||||
lastTextHasAt = (joins && lastTextHasAt) || (!insideQuotes && value.indexOf('@') >= 0);
|
||||
lastTextOpen = true;
|
||||
gapFrom = tokens.contentEnd(i);
|
||||
gapsFolding = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// If there is no text but a comment, replace the two. A comment is never part of a
|
||||
|
||||
+6
-5
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const punycode = __importStar(require("../punycode/index.js"));
|
||||
const shared = __importStar(require("../shared/index.js"));
|
||||
const mimeFuncs = __importStar(require("../mime-funcs/index.js"));
|
||||
const node_crypto_1 = __importDefault(require("node:crypto"));
|
||||
const errors = __importStar(require("../errors.js"));
|
||||
@@ -62,13 +62,14 @@ function unsupportedHashAlgoError(hashAlgo) {
|
||||
*/
|
||||
function sign(headers, hashAlgo, bodyHash, options) {
|
||||
options = options || {};
|
||||
// all listed fields from RFC4871 #5.5
|
||||
// all listed fields from RFC4871 #5.5, plus List-Unsubscribe-Post: RFC 8058 only allows
|
||||
// one-click unsubscribe when the signature covers it next to List-Unsubscribe
|
||||
const defaultFieldNames = 'From:Sender:Reply-To:Subject:Date:Message-ID:To:' +
|
||||
'Cc:MIME-Version:Content-Type:Content-Transfer-Encoding:Content-ID:' +
|
||||
'Content-Description:Resent-Date:Resent-From:Resent-Sender:' +
|
||||
'Resent-To:Resent-Cc:Resent-Message-ID:In-Reply-To:References:' +
|
||||
'List-Id:List-Help:List-Unsubscribe:List-Subscribe:List-Post:' +
|
||||
'List-Owner:List-Archive';
|
||||
'List-Id:List-Help:List-Unsubscribe:List-Unsubscribe-Post:List-Subscribe:List-Post:' +
|
||||
'List-Owner:List-Archive:OTP-Token';
|
||||
const fieldNames = options.headerFieldNames || defaultFieldNames;
|
||||
const canonicalizedHeaderData = relaxedHeaders(headers, fieldNames, options.skipFields);
|
||||
const dkimHeader = generateDKIMHeader(options.domainName, options.keySelector, canonicalizedHeaderData.fieldNames, hashAlgo, bodyHash);
|
||||
@@ -103,7 +104,7 @@ function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyH
|
||||
'v=1',
|
||||
'a=rsa-' + hashAlgo,
|
||||
'c=relaxed/relaxed',
|
||||
'd=' + punycode.toASCII(cleanTagValue(domainName)),
|
||||
'd=' + shared.normalizeDomain(cleanTagValue(domainName), false),
|
||||
'q=dns/txt',
|
||||
's=' + cleanTagValue(keySelector),
|
||||
'bh=' + bodyHash,
|
||||
|
||||
+4
@@ -21,7 +21,9 @@ export declare const ERROR_CODES: {
|
||||
readonly EPROTOCOL: "Invalid SMTP server response";
|
||||
readonly EENVELOPE: "Invalid mail envelope (sender or recipients)";
|
||||
readonly EMESSAGE: "Message delivery error";
|
||||
readonly EOTP: "Invalid one-time passcode data (otp option)";
|
||||
readonly ESTREAM: "Stream processing error";
|
||||
readonly EABORT: "Message sending aborted";
|
||||
readonly EAUTH: "Authentication failed";
|
||||
readonly ENOAUTH: "Authentication credentials not provided";
|
||||
readonly EOAUTH2: "OAuth2 token generation or refresh error";
|
||||
@@ -48,7 +50,9 @@ export declare const EREQUIRETLS = "EREQUIRETLS";
|
||||
export declare const EPROTOCOL = "EPROTOCOL";
|
||||
export declare const EENVELOPE = "EENVELOPE";
|
||||
export declare const EMESSAGE = "EMESSAGE";
|
||||
export declare const EOTP = "EOTP";
|
||||
export declare const ESTREAM = "ESTREAM";
|
||||
export declare const EABORT = "EABORT";
|
||||
export declare const EAUTH = "EAUTH";
|
||||
export declare const ENOAUTH = "ENOAUTH";
|
||||
export declare const EOAUTH2 = "EOAUTH2";
|
||||
|
||||
+13
-1
@@ -10,7 +10,7 @@
|
||||
* err.code = errors.ECONNECTION;
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ERR_ACCESS_DENIED = exports.isPermanentResponseCode = exports.isTransientError = exports.EFETCH = exports.EURLACCESS = exports.EFILEACCESS = exports.EPROXY = exports.ECONFIG = exports.ESES = exports.ESENDMAIL = exports.EMAXRECIPIENTS = exports.EMAXLIMIT = exports.EOAUTH2 = exports.ENOAUTH = exports.EAUTH = exports.ESTREAM = exports.EMESSAGE = exports.EENVELOPE = exports.EPROTOCOL = exports.EREQUIRETLS = exports.ETLS = exports.EDNS = exports.ESOCKET = exports.ETIMEDOUT = exports.ECONNECTION = exports.ERROR_CODES = void 0;
|
||||
exports.ERR_ACCESS_DENIED = exports.isPermanentResponseCode = exports.isTransientError = exports.createAbortError = exports.EFETCH = exports.EURLACCESS = exports.EFILEACCESS = exports.EPROXY = exports.ECONFIG = exports.ESES = exports.ESENDMAIL = exports.EMAXRECIPIENTS = exports.EMAXLIMIT = exports.EOAUTH2 = exports.ENOAUTH = exports.EAUTH = exports.EABORT = exports.ESTREAM = exports.EOTP = exports.EMESSAGE = exports.EENVELOPE = exports.EPROTOCOL = exports.EREQUIRETLS = exports.ETLS = exports.EDNS = exports.ESOCKET = exports.ETIMEDOUT = exports.ECONNECTION = exports.ERROR_CODES = void 0;
|
||||
/**
|
||||
* Error code descriptions for documentation and debugging
|
||||
*/
|
||||
@@ -27,7 +27,9 @@ exports.ERROR_CODES = {
|
||||
EPROTOCOL: 'Invalid SMTP server response',
|
||||
EENVELOPE: 'Invalid mail envelope (sender or recipients)',
|
||||
EMESSAGE: 'Message delivery error',
|
||||
EOTP: 'Invalid one-time passcode data (otp option)',
|
||||
ESTREAM: 'Stream processing error',
|
||||
EABORT: 'Message sending aborted',
|
||||
// Authentication errors
|
||||
EAUTH: 'Authentication failed',
|
||||
ENOAUTH: 'Authentication credentials not provided',
|
||||
@@ -55,7 +57,9 @@ exports.EREQUIRETLS = 'EREQUIRETLS';
|
||||
exports.EPROTOCOL = 'EPROTOCOL';
|
||||
exports.EENVELOPE = 'EENVELOPE';
|
||||
exports.EMESSAGE = 'EMESSAGE';
|
||||
exports.EOTP = 'EOTP';
|
||||
exports.ESTREAM = 'ESTREAM';
|
||||
exports.EABORT = 'EABORT';
|
||||
exports.EAUTH = 'EAUTH';
|
||||
exports.ENOAUTH = 'ENOAUTH';
|
||||
exports.EOAUTH2 = 'EOAUTH2';
|
||||
@@ -68,6 +72,14 @@ exports.EPROXY = 'EPROXY';
|
||||
exports.EFILEACCESS = 'EFILEACCESS';
|
||||
exports.EURLACCESS = 'EURLACCESS';
|
||||
exports.EFETCH = 'EFETCH';
|
||||
/** Creates the error reported when a caller cancels an individual send. @internal */
|
||||
const createAbortError = (signal) => {
|
||||
const err = new Error('Message sending aborted', { cause: signal.reason });
|
||||
err.name = 'AbortError';
|
||||
err.code = exports.EABORT;
|
||||
return err;
|
||||
};
|
||||
exports.createAbortError = createAbortError;
|
||||
/**
|
||||
* Tells whether the error ended the connection rather than rejected what was sent over it
|
||||
*/
|
||||
|
||||
+3
-1
@@ -71,7 +71,9 @@ declare class Cookies {
|
||||
*/
|
||||
add(cookie: Cookie): boolean;
|
||||
/**
|
||||
* Checks if two cookie objects are the same
|
||||
* Checks if two cookie objects are the same cookie. A cookie is identified by its
|
||||
* name, domain and path (RFC 6265 section 5.3), the Secure and HttpOnly flags are
|
||||
* attributes of the stored cookie that an update replaces
|
||||
*
|
||||
* @param a Cookie to check against
|
||||
* @param b Cookie to check against
|
||||
|
||||
+12
-3
@@ -89,6 +89,10 @@ class Cookies {
|
||||
if (!cookie.expires) {
|
||||
cookie.expires = new Date(Date.now() + (Number(this.options.sessionTimeout || SESSION_TIMEOUT) || SESSION_TIMEOUT) * 1000);
|
||||
}
|
||||
// a non-secure url can not set a Secure cookie, nor overwrite or delete one (RFC 6265bis section 5.7)
|
||||
if (urlparts.protocol !== 'https:' && (cookie.secure || this.cookies.some(stored => stored.secure && this.compare(stored, cookie)))) {
|
||||
return false;
|
||||
}
|
||||
return this.add(cookie);
|
||||
}
|
||||
/**
|
||||
@@ -131,6 +135,7 @@ class Cookies {
|
||||
parse(cookieStr) {
|
||||
const cookie = {};
|
||||
let hasNameValue = false;
|
||||
let hasMaxAge = false;
|
||||
(cookieStr || '')
|
||||
.toString()
|
||||
.split(';')
|
||||
@@ -158,7 +163,8 @@ class Cookies {
|
||||
case 'expires': {
|
||||
const expires = new Date(value);
|
||||
// ignore date if can not parse it
|
||||
if (expires.toString() !== 'Invalid Date') {
|
||||
if (expires.toString() !== 'Invalid Date' && !hasMaxAge) {
|
||||
// Max-Age has precedence when both attributes are present (RFC 6265 5.3)
|
||||
cookie.expires = expires;
|
||||
}
|
||||
break;
|
||||
@@ -175,6 +181,7 @@ class Cookies {
|
||||
break;
|
||||
case 'max-age':
|
||||
cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000);
|
||||
hasMaxAge = true;
|
||||
break;
|
||||
case 'secure':
|
||||
cookie.secure = true;
|
||||
@@ -244,14 +251,16 @@ class Cookies {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Checks if two cookie objects are the same
|
||||
* Checks if two cookie objects are the same cookie. A cookie is identified by its
|
||||
* name, domain and path (RFC 6265 section 5.3), the Secure and HttpOnly flags are
|
||||
* attributes of the stored cookie that an update replaces
|
||||
*
|
||||
* @param a Cookie to check against
|
||||
* @param b Cookie to check against
|
||||
* @returns True, if the cookies are the same
|
||||
*/
|
||||
compare(a, b) {
|
||||
return a.name === b.name && a.path === b.path && a.domain === b.domain && a.secure === b.secure && a.httponly === b.httponly;
|
||||
return a.name === b.name && a.path === b.path && a.domain === b.domain;
|
||||
}
|
||||
/**
|
||||
* Checks if a cookie is expired
|
||||
|
||||
+2
@@ -83,6 +83,8 @@ class JSONTransport {
|
||||
}
|
||||
delete data.envelope;
|
||||
delete data.normalizedHeaders;
|
||||
// the per-message AbortSignal is not message data
|
||||
delete data.signal;
|
||||
// the message field is the object itself with skipEncoding, the
|
||||
// createTransport overload for that option types the result accordingly
|
||||
return done(null, {
|
||||
|
||||
+12
@@ -72,6 +72,16 @@ export type MailComposerListHeaderEntry = string | {
|
||||
export interface MailComposerListHeaders {
|
||||
[key: string]: MailComposerListHeaderEntry | (MailComposerListHeaderEntry | MailComposerListHeaderEntry[])[];
|
||||
}
|
||||
/**
|
||||
* The otp value: a one-time passcode and the origin it is bound to, sent as the OTP-Token
|
||||
* header (draft-goto-otp-token)
|
||||
*/
|
||||
export interface MailComposerOtp {
|
||||
/** The passcode, printable ascii */
|
||||
code: string;
|
||||
/** Origin the code is bound to, https or a loopback http origin. A full url is reduced to its origin */
|
||||
origin: string;
|
||||
}
|
||||
/**
|
||||
* Encoding for the non-ascii header values: quoted-printable ('Q', the default) or base64
|
||||
* ('B'). Only the first letter is read, so the short forms work as well
|
||||
@@ -114,6 +124,8 @@ export interface MailComposerOptions {
|
||||
headers?: MimeNodeHeaders | undefined;
|
||||
/** List-* headers, read by the mailer */
|
||||
list?: MailComposerListHeaders | undefined;
|
||||
/** One-time passcode for the OTP-Token header. An invalid value makes compile() throw an EOTP error */
|
||||
otp?: MailComposerOtp | undefined;
|
||||
/** SMTP envelope to use instead of the one generated from the headers */
|
||||
envelope?: MimeNodeEnvelopeInput | undefined;
|
||||
/** Content-Transfer-Encoding to force for the text/* nodes that do not set their own */
|
||||
|
||||
+53
@@ -39,6 +39,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const index_js_1 = __importDefault(require("../mime-node/index.js"));
|
||||
const mimeFuncs = __importStar(require("../mime-funcs/index.js"));
|
||||
const errors = __importStar(require("../errors.js"));
|
||||
const index_js_2 = require("../shared/index.js");
|
||||
/**
|
||||
* Creates the object for composing a MimeNode instance out from the mail options
|
||||
@@ -133,6 +134,10 @@ class MailComposer {
|
||||
if (this.mail.headers) {
|
||||
this.message.addHeader(this.mail.headers);
|
||||
}
|
||||
// after the custom headers, so it replaces an OTP-Token from them, the field may appear only once
|
||||
if (this.mail.otp) {
|
||||
this.message.setHeader('OTP-Token', formatOtpToken(this.mail.otp));
|
||||
}
|
||||
// Add headers to the root node, always overrides custom headers
|
||||
['from', 'sender', 'to', 'cc', 'bcc', 'reply-to', 'in-reply-to', 'references', 'subject', 'message-id', 'date'].forEach(header => {
|
||||
const key = header.replace(/-(\w)/g, (o, c) => c.toUpperCase());
|
||||
@@ -641,6 +646,54 @@ class MailComposer {
|
||||
return element;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns the value of the OTP-Token header for the otp option. The header is defined by
|
||||
* draft-goto-otp-token-01, an Internet-Draft that expires on 25 March 2027. By then check
|
||||
* for a newer revision of the draft or a published RFC, the header name and its
|
||||
* parameters are still open questions in the draft.
|
||||
*/
|
||||
function formatOtpToken(otp) {
|
||||
// a structured field String can only hold printable ascii. The code is a secret the recipient
|
||||
// compares against the one in the message body, so it is rejected rather than cleaned up
|
||||
if (typeof otp.code !== 'string' || !/^[\x20-\x7e]+$/.test(otp.code)) {
|
||||
throw otpError('The otp code must be a non-empty string of printable ASCII characters');
|
||||
}
|
||||
// a structured field String escapes the same two characters as a quoted-string
|
||||
return mimeFuncs.quoteString(otp.code) + '; origin=' + mimeFuncs.quoteString(getOtpOrigin(otp.origin));
|
||||
}
|
||||
/**
|
||||
* Returns the canonical ascii serialization of the origin the code is bound to. The draft
|
||||
* requires a potentially trustworthy origin, so only https is accepted, plus http on a
|
||||
* loopback host for local development
|
||||
*/
|
||||
function getOtpOrigin(origin) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(String(origin));
|
||||
}
|
||||
catch {
|
||||
// handled below
|
||||
}
|
||||
// the WHATWG parser lets characters such as a quote or a brace into a host, which the
|
||||
// origin grammar the draft requires (RFC 6454) does not allow, so a receiver would discard
|
||||
// the header. Only a DNS name, an IPv4 address or a bracketed IPv6 address is accepted.
|
||||
// Userinfo is refused as well, an origin never has it and it turns a value built as
|
||||
// 'https://example.com' + input into the origin of whatever host follows an "@"
|
||||
if (!url || url.username || url.password || !/^([a-z0-9_-]+\.)*[a-z0-9_-]+$|^\[[0-9a-f:.]+\]$/.test(url.hostname)) {
|
||||
throw otpError('The otp origin must be an absolute https URL');
|
||||
}
|
||||
const isLoopback = /^(localhost|.+\.localhost|127(\.\d+){3}|\[::1\])$/.test(url.hostname);
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback)) {
|
||||
throw otpError('The otp origin must be an https URL, or an http URL on a loopback host');
|
||||
}
|
||||
// the URL parser already lowercases the host, converts it to punycode and drops the default port
|
||||
return url.origin;
|
||||
}
|
||||
function otpError(message) {
|
||||
const err = new Error(message);
|
||||
err.code = errors.EOTP;
|
||||
return err;
|
||||
}
|
||||
exports.default = MailComposer;
|
||||
module.exports = exports.default;
|
||||
Object.defineProperty(module.exports, 'default', { value: exports.default, enumerable: false, writable: true, configurable: true });
|
||||
+15
-4
@@ -4,7 +4,7 @@ import DKIM, { type DKIMOptions } from '../dkim/index.js';
|
||||
import MailMessage, { type MailDefaults, type SendMailOptions } from './mail-message.js';
|
||||
import net from 'node:net';
|
||||
import type { ConnectionOptions } from 'node:tls';
|
||||
import type { MailComposerAlternative, MailComposerAttachment, MailComposerIcalEvent, MailComposerListHeaderEntry, MailComposerListHeaders, MailComposerTextEncoding } from '../mail-composer/index.js';
|
||||
import type { MailComposerAlternative, MailComposerAttachment, MailComposerIcalEvent, MailComposerListHeaderEntry, MailComposerListHeaders, MailComposerOtp, MailComposerTextEncoding } from '../mail-composer/index.js';
|
||||
import type { Callback, NodemailerError, ResultCallback } from '../errors.js';
|
||||
import type { ParsedUrl } from '../shared/url.js';
|
||||
import type { MimeNodeAddress, MimeNodeEnvelope, MimeNodeEnvelopeInput, MimeNodeHeaders, MimeNodeOptions } from '../mime-node/index.js';
|
||||
@@ -112,6 +112,11 @@ export interface MailMeta {
|
||||
* declared on Transport, Transporter and Mail
|
||||
*/
|
||||
export interface Transport<T = SentMessageInfo, D extends TransportOptions = TransportOptions> {
|
||||
/**
|
||||
* Set only if send() cancels its own work on mail.data.signal and removes its signal listener
|
||||
* when finished. Without it the signal is still honored up to dispatch, then ignored.
|
||||
*/
|
||||
supportsAbortSignal?: boolean | undefined;
|
||||
/** Transport name, used for logging */
|
||||
name: string;
|
||||
/** Transport version, used for logging */
|
||||
@@ -176,8 +181,13 @@ declare class Mail<out T = SentMessageInfo, out D extends TransportOptions = Tra
|
||||
dkim: DKIM | false;
|
||||
transporter: Transport<T, D>;
|
||||
logger: shared.Logger;
|
||||
/** Closes the transport, the pooled SMTP transport closes its connections */
|
||||
close: () => void;
|
||||
/**
|
||||
* Closes the transport, the pooled SMTP transport closes its connections. With `force` the
|
||||
* pooled transport also closes connections that are delivering a message
|
||||
*/
|
||||
close: (options?: {
|
||||
force?: boolean;
|
||||
}) => void;
|
||||
/** Tells whether the transport can take a message right away */
|
||||
isIdle: () => boolean;
|
||||
/** Checks the configuration, the SMTP transports connect and authenticate for it */
|
||||
@@ -227,11 +237,12 @@ declare namespace Mail {
|
||||
type Headers = MimeNodeHeaders;
|
||||
type ListHeader = MailComposerListHeaderEntry;
|
||||
type ListHeaders = MailComposerListHeaders;
|
||||
type Otp = MailComposerOtp;
|
||||
type Envelope = MimeNodeEnvelopeInput;
|
||||
type Connection = SocketOptions;
|
||||
type TextEncoding = MailComposerTextEncoding;
|
||||
type PluginFunction<T = SentMessageInfo> = MailPluginFunction<T>;
|
||||
}
|
||||
/** The same aliases as module level exports, for `import * as Mail` and `import Mail = require()` */
|
||||
export type { SendMailOptions as Options, MimeNodeAddress as Address, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerAlternative as AmpAttachment, MailComposerIcalEvent as IcalAttachment, MimeNodeHeaders as Headers, MailComposerListHeaderEntry as ListHeader, MailComposerListHeaders as ListHeaders, MimeNodeEnvelopeInput as Envelope, SocketOptions as Connection, MailComposerTextEncoding as TextEncoding };
|
||||
export type { SendMailOptions as Options, MimeNodeAddress as Address, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerAlternative as AmpAttachment, MailComposerIcalEvent as IcalAttachment, MimeNodeHeaders as Headers, MailComposerListHeaderEntry as ListHeader, MailComposerListHeaders as ListHeaders, MailComposerOtp as Otp, MimeNodeEnvelopeInput as Envelope, SocketOptions as Connection, MailComposerTextEncoding as TextEncoding };
|
||||
export default Mail;
|
||||
+56
-4
@@ -56,6 +56,16 @@ const node_crypto_1 = __importDefault(require("node:crypto"));
|
||||
* asks a server to accept 100, so a real send is bounded far below this.
|
||||
*/
|
||||
const DEFAULT_MAX_RECIPIENTS = 100000;
|
||||
/**
|
||||
* Duck-typed so that signals from another realm or a polyfill are accepted as well
|
||||
*/
|
||||
function isAbortSignal(value) {
|
||||
return (typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'aborted' in value &&
|
||||
typeof value.addEventListener === 'function' &&
|
||||
typeof value.removeEventListener === 'function');
|
||||
}
|
||||
/**
|
||||
* Creates an object for exposing the Mail API
|
||||
*
|
||||
@@ -157,11 +167,43 @@ class Mail extends node_events_1.EventEmitter {
|
||||
this.getSocket = false;
|
||||
}
|
||||
const mail = new mail_message_js_1.default(this, data);
|
||||
const signalOption = mail.data.signal;
|
||||
const signal = isAbortSignal(signalOption) ? signalOption : undefined;
|
||||
let settled = false;
|
||||
const removeAbortListener = () => signal?.removeEventListener('abort', onAbort);
|
||||
const finish = (err, info) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
removeAbortListener();
|
||||
if (err) {
|
||||
mail.releaseStreams();
|
||||
}
|
||||
done(err, info);
|
||||
};
|
||||
// a failed message is not going to be read anymore, release its content streams
|
||||
const fail = (err) => {
|
||||
mail.releaseStreams();
|
||||
done(err);
|
||||
finish(err);
|
||||
};
|
||||
function onAbort() {
|
||||
fail(errors.createAbortError(signal));
|
||||
}
|
||||
if (signalOption !== undefined && signalOption !== null && !signal) {
|
||||
const err = new Error('The signal option must be an AbortSignal');
|
||||
err.code = errors.ECONFIG;
|
||||
setImmediate(() => fail(err));
|
||||
return promise;
|
||||
}
|
||||
// Mail handles a pre-aborted signal and cancellation during plugin processing for every
|
||||
// transport; a transport without supportsAbortSignal ignores the signal once it is called
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
if (signal.aborted) {
|
||||
setImmediate(onAbort);
|
||||
return promise;
|
||||
}
|
||||
}
|
||||
this.logger.debug({
|
||||
tnx: 'transport',
|
||||
name: this.transporter.name,
|
||||
@@ -169,6 +211,9 @@ class Mail extends node_events_1.EventEmitter {
|
||||
action: 'send'
|
||||
}, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version);
|
||||
this._processPlugins('compile', mail, err => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
err,
|
||||
@@ -206,6 +251,9 @@ class Mail extends node_events_1.EventEmitter {
|
||||
return fail(err);
|
||||
}
|
||||
this._processPlugins('stream', mail, err => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
err,
|
||||
@@ -225,16 +273,17 @@ class Mail extends node_events_1.EventEmitter {
|
||||
return dkim.sign(input, mail.data._dkim);
|
||||
});
|
||||
}
|
||||
// The transport takes ownership of cancellation from here, including queued work.
|
||||
removeAbortListener();
|
||||
this.transporter.send(mail, (...args) => {
|
||||
if (args[0]) {
|
||||
mail.releaseStreams();
|
||||
this.logger.error({
|
||||
err: args[0],
|
||||
tnx: 'transport',
|
||||
action: 'send'
|
||||
}, 'Send Error: %s', args[0].message);
|
||||
}
|
||||
done(...args);
|
||||
finish(...args);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -264,6 +313,9 @@ class Mail extends node_events_1.EventEmitter {
|
||||
let pos = 0;
|
||||
let block = 'default';
|
||||
const processPlugins = () => {
|
||||
if (mail.data.signal?.aborted) {
|
||||
return callback(errors.createAbortError(mail.data.signal));
|
||||
}
|
||||
let curplugins = block === 'default' ? defaultPlugins : userPlugins;
|
||||
if (pos >= curplugins.length) {
|
||||
if (block === 'default' && userPlugins.length) {
|
||||
|
||||
+10
@@ -13,6 +13,16 @@ import type { SentMessageInfo } from './index.js';
|
||||
* tree is built from, the fields below are the ones the mailer reads on top of those
|
||||
*/
|
||||
export interface SendMailOptions extends MailComposerOptions {
|
||||
/**
|
||||
* Cancel this send, including waiting for plugins or in an SMTP pool queue.
|
||||
* Plugins must cooperate with the signal to stop their own work already in progress.
|
||||
* Supported by SMTP, pooled SMTP and transports declaring supportsAbortSignal. Other
|
||||
* transports ignore the signal once the message is handed to them; a signal that is
|
||||
* already aborted, or aborts during plugin processing, still cancels the send.
|
||||
* Fails with AbortError/EABORT on cancellation, ECONFIG if the value is not an AbortSignal.
|
||||
* Aborting does not prove that the server has not already accepted the message.
|
||||
*/
|
||||
signal?: AbortSignal | undefined;
|
||||
/** DKIM signing options for this message, used instead of the ones of the transporter */
|
||||
dkim?: DKIMOptions | undefined;
|
||||
/** 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 */
|
||||
|
||||
+20
-2
@@ -74,7 +74,8 @@ export declare function hasLongerLines(str: string, lineLength: number): boolean
|
||||
*/
|
||||
export declare function encodeWord(data: string | Buffer, mimeWordEncoding?: string, maxLength?: number): string;
|
||||
/**
|
||||
* Finds word sequences with non ascii text and converts these to mime words
|
||||
* Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
|
||||
* and converts these to mime words. A valid encoded-word is passed through as it is.
|
||||
*
|
||||
* @param value String to be encoded
|
||||
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
|
||||
@@ -107,6 +108,22 @@ export declare function buildHeaderValue(structured: StructuredHeaderValue): str
|
||||
* @return A list of encoded keys and headers
|
||||
*/
|
||||
export declare function buildHeaderParam(key: string, data: string | Buffer, maxLength?: number): EncodedHeaderParam[];
|
||||
/**
|
||||
* Options of parseHeaderValue()
|
||||
*/
|
||||
export interface ParseHeaderValueOptions {
|
||||
/**
|
||||
* Drop the RFC 822 comments outside quoted strings, which the MIME headers allow and
|
||||
* which are not part of the value: 'boundary=b (comment)' names the boundary 'b'. A
|
||||
* parenthesis right behind the '=' of a parameter or behind a token character of its
|
||||
* value continues the token, as it does for Python and postal-mime, so 'Invoice(1).pdf'
|
||||
* keeps its name and 'boundary=(c)b' names the boundary '(c)b'. A comment that never
|
||||
* closes runs to the end of the value, unless a parameter follows it, in which case it is
|
||||
* content and the parameter survives. Comments are kept by default for the sake of the
|
||||
* callers of this exported function, not because keeping them is ever the better reading
|
||||
*/
|
||||
stripComments?: boolean | undefined;
|
||||
}
|
||||
/**
|
||||
* Parses a header value with key=value arguments into a structured
|
||||
* object.
|
||||
@@ -120,9 +137,10 @@ export declare function buildHeaderParam(key: string, data: string | Buffer, max
|
||||
* }
|
||||
*
|
||||
* @param str Header value
|
||||
* @param options Options, see ParseHeaderValueOptions
|
||||
* @return Header value as a parsed structure
|
||||
*/
|
||||
export declare function parseHeaderValue(str: string): ParsedHeaderValue;
|
||||
export declare function parseHeaderValue(str: string, options?: ParseHeaderValueOptions): ParsedHeaderValue;
|
||||
/**
|
||||
* Returns file extension for a content type string. If no suitable extensions
|
||||
* are found, 'bin' is used as the default extension
|
||||
|
||||
+115
-3
@@ -181,8 +181,75 @@ function encodeWord(data, mimeWordEncoding, maxLength) {
|
||||
}
|
||||
return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?=');
|
||||
}
|
||||
// An encoded-word as RFC 2047 section 2 spells it: a charset token (with an optional RFC 2231
|
||||
// language), B or Q, and encoded text without '?' or whitespace. None of the parts can hold the
|
||||
// '?' that separates them, so the pattern never backtracks
|
||||
const VALID_ENCODED_WORD = /^=\?[^\s()<>@,;:"/[\]?.=]+\?[BbQq]\?[^?\s]+\?=$/;
|
||||
// What a lenient decoder reads as an encoded-word: libmime and Python decode
|
||||
// '=?utf-8?Q?a b?=' across the space as well. Applied sticky at a '=?', and every part stops
|
||||
// at the next '?', so it does not backtrack either
|
||||
const LENIENT_ENCODED_WORD = /[=]\?[^?]*\?[BbQq]\?[^?]*\?=/y;
|
||||
/**
|
||||
* Finds word sequences with non ascii text and converts these to mime words
|
||||
* Marks the text a receiver would read as an encoded-word when it is not one valid encoded-word
|
||||
* on its own. RFC 2047 section 7 requires that a word beginning with '=?' and ending with '?='
|
||||
* is a valid encoded-word, and decoders also decode a look-alike that spans whitespace, so
|
||||
* '=?utf-8?X?x?=' and 'see =?utf-8?Q?a b?= here' read differently on every receiver. A valid
|
||||
* encoded-word is left alone, which is what lets a caller pass a value that is already encoded,
|
||||
* as most other mail libraries do.
|
||||
*
|
||||
* The bounds of the word around each '=?' are found once per word and reused, walking back to
|
||||
* the start of a long word from every '=?' it holds would be quadratic.
|
||||
*
|
||||
* @param value String to look in
|
||||
* @param range The first and the last offset that needs encoding so far, -1 for none
|
||||
* @return The range, widened to cover the words of every invalid look-alike
|
||||
*/
|
||||
function _markInvalidEncodedWords(value, range) {
|
||||
const len = value.length;
|
||||
const isSpace = (pos) => /\s/.test(value.charAt(pos));
|
||||
// the word last looked at, its start and the offset just past it
|
||||
let wordStart = 0;
|
||||
let wordEnd = -1;
|
||||
const wordAt = (pos) => {
|
||||
if (pos < wordEnd) {
|
||||
return;
|
||||
}
|
||||
// the previous word ended at whitespace, so the walk back stops before reaching it
|
||||
wordStart = pos;
|
||||
while (wordStart > 0 && !isSpace(wordStart - 1)) {
|
||||
wordStart--;
|
||||
}
|
||||
wordEnd = pos;
|
||||
while (wordEnd < len && !isSpace(wordEnd)) {
|
||||
wordEnd++;
|
||||
}
|
||||
};
|
||||
let pos = value.indexOf('=?');
|
||||
while (pos >= 0) {
|
||||
wordAt(pos);
|
||||
const start = wordStart;
|
||||
LENIENT_ENCODED_WORD.lastIndex = pos;
|
||||
const match = LENIENT_ENCODED_WORD.exec(value);
|
||||
const end = match ? pos + match[0].length : wordEnd;
|
||||
if (match && end > wordEnd) {
|
||||
// the look-alike runs across whitespace, on to the word it ends in
|
||||
wordAt(end - 1);
|
||||
}
|
||||
const word = value.substring(start, wordEnd);
|
||||
// without a match, a word that begins with '=?' and ends with '?=' is still invalid
|
||||
const looksLike = match ? true : start === pos && word.length >= 4 && word.endsWith('?=');
|
||||
const valid = start === pos && wordEnd === end && word.length <= 75 && VALID_ENCODED_WORD.test(word);
|
||||
if (looksLike && !valid) {
|
||||
range[0] = range[0] < 0 ? start : Math.min(range[0], start);
|
||||
range[1] = Math.max(range[1], wordEnd - 1);
|
||||
}
|
||||
pos = value.indexOf('=?', match ? end : pos + 2);
|
||||
}
|
||||
return range;
|
||||
}
|
||||
/**
|
||||
* Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
|
||||
* and converts these to mime words. A valid encoded-word is passed through as it is.
|
||||
*
|
||||
* @param value String to be encoded
|
||||
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
|
||||
@@ -206,11 +273,14 @@ function encodeWords(value, mimeWordEncoding, maxLength, encodeAll) {
|
||||
lastSpecial = i;
|
||||
}
|
||||
}
|
||||
if (value.indexOf('=?') >= 0) {
|
||||
[firstSpecial, lastSpecial] = _markInvalidEncodedWords(value, [firstSpecial, lastSpecial]);
|
||||
}
|
||||
if (firstSpecial < 0) {
|
||||
return value;
|
||||
}
|
||||
if (encodeAll) {
|
||||
// if it is requested to encode everything or the string contains something that resebles encoded word, then encode everything
|
||||
// the value needs encoding and it is requested to encode everything
|
||||
return encodeWord(value, mimeWordEncoding, maxLength);
|
||||
}
|
||||
// encode from the start of the word holding the first such character to the end of the
|
||||
@@ -414,6 +484,26 @@ function buildHeaderParam(key, data, maxLength) {
|
||||
* goes in. Whitespace used to come off it only because the value was trimmed first.
|
||||
*/
|
||||
const TOKEN = /^[^\x00-\x20\x7f()<>@,;:\\"/[\]?=]+$/;
|
||||
/**
|
||||
* Offset of the ')' that closes the RFC 822 comment opening at `start`, or -1 when the
|
||||
* comment never closes. Comments nest, and a backslash escapes the character after it
|
||||
*/
|
||||
function _findCommentEnd(str, start) {
|
||||
let depth = 0;
|
||||
for (let i = start, len = str.length; i < len; i++) {
|
||||
const c = str.charAt(i);
|
||||
if (c === '\\') {
|
||||
i++;
|
||||
}
|
||||
else if (c === '(') {
|
||||
depth++;
|
||||
}
|
||||
else if (c === ')' && --depth === 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/**
|
||||
* Whether a string can be a header parameter name.
|
||||
*
|
||||
@@ -440,13 +530,16 @@ function _isParamName(name) {
|
||||
* }
|
||||
*
|
||||
* @param str Header value
|
||||
* @param options Options, see ParseHeaderValueOptions
|
||||
* @return Header value as a parsed structure
|
||||
*/
|
||||
function parseHeaderValue(str) {
|
||||
function parseHeaderValue(str, options) {
|
||||
const response = {
|
||||
value: '',
|
||||
params: {}
|
||||
};
|
||||
// Cleared again by an unclosed '(', see the loop
|
||||
let stripComments = !!options?.stripComments;
|
||||
// A duplicated parameter resolves to its first occurrence, the way a duplicated header
|
||||
// does. Letting the last one win disagrees with the receivers that take the first, and
|
||||
// the two readings of 'boundary="b"; boundary="c"' name different delimiters. The
|
||||
@@ -508,6 +601,25 @@ function parseHeaderValue(str) {
|
||||
};
|
||||
for (let i = 0, len = str.length; i < len; i++) {
|
||||
chr = str.charAt(i);
|
||||
// With stripComments, an RFC 822 comment stands anywhere outside a quoted string but
|
||||
// right behind a token it would continue, see ParseHeaderValueOptions. In the value
|
||||
// of a parameter, no pending whitespace means the last significant character was the
|
||||
// '=' or a character of the token
|
||||
if (stripComments && chr === '(' && !quote && !quoteClosed && !(stage === 'value' && key !== false && !pendingSpace)) {
|
||||
let end = _findCommentEnd(str, i);
|
||||
if (end < 0 && str.indexOf(';', i) < 0) {
|
||||
// a comment that never closes runs to the end of the value, unless a
|
||||
// parameter follows it, which is content then and survives
|
||||
end = len - 1;
|
||||
}
|
||||
if (end >= 0) {
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
// looking for a closing ')' again would scan a run of unclosed '(' to its end
|
||||
// once for each of them
|
||||
stripComments = false;
|
||||
}
|
||||
if (stage === 'key') {
|
||||
if (chr === '=') {
|
||||
key = takeValue().trim();
|
||||
|
||||
+16
-77
@@ -39,10 +39,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const node_crypto_1 = __importDefault(require("node:crypto"));
|
||||
const node_fs_1 = __importDefault(require("node:fs"));
|
||||
const punycode = __importStar(require("../punycode/index.js"));
|
||||
const node_stream_1 = require("node:stream");
|
||||
const shared = __importStar(require("../shared/index.js"));
|
||||
const node_url_1 = __importDefault(require("node:url"));
|
||||
const mimeFuncs = __importStar(require("../mime-funcs/index.js"));
|
||||
const qp = __importStar(require("../qp/index.js"));
|
||||
const base64 = __importStar(require("../base64/index.js"));
|
||||
@@ -93,20 +91,6 @@ function stripWhitespaceInAngleBrackets(value) {
|
||||
}
|
||||
return result + value.slice(pos);
|
||||
}
|
||||
// domainToASCII and domainToUnicode are WHATWG host parsers rather than plain IDNA
|
||||
// mappers, so they do more than map: they cut the host at '/', '\\', '?' and '#', drop C0
|
||||
// controls, and percent-decode. Handing them 'evil.example/mail.corp.example' returns the
|
||||
// deliverable 'evil.example', which would turn a value the bundled codec leaves as
|
||||
// unroutable garbage into mail for a domain the sender never named. None of these
|
||||
// characters are legal in a domain, so keep them away from the mapper.
|
||||
const URL_PARSER_UNSAFE = /[/\\?#%\x00-\x20\x7F]/;
|
||||
// RFC 1035 bounds a label at 63 octets and a domain at 253. An A-label is never shorter than
|
||||
// the code points it encodes, so anything past these bounds could not have become a valid
|
||||
// domain whichever way it is encoded. The bundled codec is super-linear in the length of a
|
||||
// label, a 60 KB label of distinct code points took seconds to encode, several times per
|
||||
// address, so it is only handed what could be a domain
|
||||
const MAX_DOMAIN_LENGTH = 253;
|
||||
const MAX_LABEL_LENGTH = 63;
|
||||
// pipeline() needs a callback to not throw, the errors it sees reach the last stream anyway
|
||||
const PIPELINE_NOOP = () => false;
|
||||
// The error a node streaming into an output that was destroyed stops with
|
||||
@@ -115,62 +99,6 @@ function abortedError() {
|
||||
err.code = errors.ESTREAM;
|
||||
return err;
|
||||
}
|
||||
/**
|
||||
* Checks a domain against the DNS length limits, counted in code points per label and in
|
||||
* total. The label separators are the ones the bundled codec splits on.
|
||||
*
|
||||
* @param domain Domain to check
|
||||
* @return true if a label or the domain as a whole is too long to be a valid domain
|
||||
*/
|
||||
function exceedsDomainLimits(domain) {
|
||||
let total = 0;
|
||||
let label = 0;
|
||||
for (const char of domain) {
|
||||
total++;
|
||||
if (char === '.' || char === '。' || char === '.' || char === '。') {
|
||||
label = 0;
|
||||
}
|
||||
else if (++label > MAX_LABEL_LENGTH) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return total > MAX_DOMAIN_LENGTH;
|
||||
}
|
||||
/**
|
||||
* Encodes a domain the way browsers, the WHATWG URL Standard and DNS facing resolvers do,
|
||||
* which is with UTS-46 mapping applied before the Punycode step.
|
||||
*
|
||||
* The bundled codec is plain RFC 3492 and maps nothing, so it disagrees with every
|
||||
* conformant parser on any domain holding a mapped or ignored code point. An invisible
|
||||
* U+00AD in 'compa\u00ADny.com' encoded to 'xn--company-pka.com' where a validator reads
|
||||
* 'company.com', which let an allow-listed domain be checked and a different one mailed.
|
||||
*
|
||||
* Anything the URL parser does not accept as a hostname, an address literal such as
|
||||
* '[127.0.0.1]' included, comes back empty and falls through to the bundled codec, which
|
||||
* leaves those as they were supplied.
|
||||
*
|
||||
* @param domain Domain to encode, already lowercased by the caller
|
||||
* @param toUnicode Return the U-label form instead of the A-label form
|
||||
* @return Encoded domain
|
||||
*/
|
||||
function normalizeDomain(domain, toUnicode) {
|
||||
// domainToASCII and domainToUnicode landed in Node 7, the bundled codec covers Node 6
|
||||
if (typeof node_url_1.default.domainToASCII === 'function' && typeof node_url_1.default.domainToUnicode === 'function' && !URL_PARSER_UNSAFE.test(domain)) {
|
||||
// The U-label form is decoded from the A-label form rather than from the input:
|
||||
// Deno's domainToASCII returns an empty string for a label it cannot decode, while
|
||||
// its domainToUnicode returns the label with U+FFFD in place of the bad part
|
||||
const ascii = node_url_1.default.domainToASCII(domain);
|
||||
const mapped = ascii && toUnicode ? node_url_1.default.domainToUnicode(ascii) : ascii;
|
||||
if (mapped) {
|
||||
return mapped;
|
||||
}
|
||||
}
|
||||
if (exceedsDomainLimits(domain)) {
|
||||
// too long to be a domain whichever way it is encoded, keep it as supplied
|
||||
return domain;
|
||||
}
|
||||
return toUnicode ? punycode.toUnicode(domain) : punycode.toASCII(domain);
|
||||
}
|
||||
/**
|
||||
* Removes the characters that must never reach a multipart delimiter line.
|
||||
*
|
||||
@@ -654,15 +582,18 @@ class MimeNode {
|
||||
return;
|
||||
}
|
||||
switch (header.key) {
|
||||
// The comments of a MIME header are not part of its value and are dropped, so a
|
||||
// caller supplied 'boundary=b (comment)' is the boundary b it names, and the
|
||||
// header goes out without the comment
|
||||
case 'Content-Disposition':
|
||||
structured = mimeFuncs.parseHeaderValue(value);
|
||||
structured = mimeFuncs.parseHeaderValue(value, { stripComments: true });
|
||||
if (this.filename) {
|
||||
structured.params.filename = this.filename;
|
||||
}
|
||||
value = mimeFuncs.buildHeaderValue(structured);
|
||||
break;
|
||||
case 'Content-Type':
|
||||
structured = mimeFuncs.parseHeaderValue(value);
|
||||
structured = mimeFuncs.parseHeaderValue(value, { stripComments: true });
|
||||
// the type token decides multipart and charset below, so clean it before
|
||||
// those run and not just on the way out, otherwise a control char makes
|
||||
// the checks miss and the header ends up claiming a type it is not set up for
|
||||
@@ -1299,7 +1230,7 @@ class MimeNode {
|
||||
.replace(/[\s\x00-\x20\x7f:]/g, '')
|
||||
.toLowerCase()
|
||||
// use uppercase words, except MIME
|
||||
.replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi, c => c.toUpperCase())
|
||||
.replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^OTP(?=-Token$)|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi, c => c.toUpperCase())
|
||||
// special case
|
||||
.replace(/^Content-Features$/i, 'Content-features');
|
||||
return key;
|
||||
@@ -1371,7 +1302,7 @@ class MimeNode {
|
||||
// values enclosed in <>
|
||||
case 'Message-ID':
|
||||
case 'In-Reply-To':
|
||||
case 'Content-Id':
|
||||
case 'Content-ID':
|
||||
// a msg-id is structured, so an encoded word inside the angle brackets would
|
||||
// be read as literal text. drop the characters that can not appear in a header
|
||||
// at all, but leave HT alone, it separates the ids of a multi id value
|
||||
@@ -1386,6 +1317,14 @@ class MimeNode {
|
||||
value = value + '>';
|
||||
}
|
||||
return value;
|
||||
// a structured field (RFC 9651) that can not be mime encoded, an encoded word would
|
||||
// turn its quoted strings into text that no structured field parser reads. Only
|
||||
// the characters that can not appear in a header at all are removed
|
||||
case 'OTP-Token':
|
||||
return (value || '')
|
||||
.toString()
|
||||
.replace(/\r?\n|\r/g, ' ')
|
||||
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
||||
// space separated list of values enclosed in <>
|
||||
case 'References': {
|
||||
const ids = [];
|
||||
@@ -1527,7 +1466,7 @@ class MimeNode {
|
||||
// symmetry on both sides of the '@' rather than being encoded to an A-label
|
||||
const smtputf8 = /[\x80-\uFFFF]/.test(user);
|
||||
try {
|
||||
encodedDomain = normalizeDomain(domain.toLowerCase(), smtputf8);
|
||||
encodedDomain = shared.normalizeDomain(domain, smtputf8);
|
||||
}
|
||||
catch (_err) {
|
||||
// keep domain as supplied
|
||||
|
||||
+1
-1
@@ -111,7 +111,7 @@ export type { Mail, MailDefaults, SentMessageInfo, Transport, TransportOptions }
|
||||
export type { SendMailOptions, Transporter } from './mailer/index.js';
|
||||
export type { NodemailerError, ErrorCode } from './errors.js';
|
||||
export type { MailMessage, MailMessageData, PluginFunction, VerifyCallback } from './mailer/index.js';
|
||||
export type { MailComposerOptions, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerIcalEvent as IcalAttachment, MailComposerListHeaders as ListHeaders } from './mail-composer/index.js';
|
||||
export type { MailComposerOptions, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerIcalEvent as IcalAttachment, MailComposerListHeaders as ListHeaders, MailComposerOtp as Otp } from './mail-composer/index.js';
|
||||
export type { MimeNodeAddress as Address, MimeNodeHeaders as Headers } from './mime-node/index.js';
|
||||
export type { SMTPConnectionOptions, SMTPConnectionAuth, SMTPEnvelope, SMTPEnvelopeDsn } from './smtp-connection/index.js';
|
||||
export type { DKIMOptions } from './dkim/index.js';
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
export declare const name = "nodemailer";
|
||||
export declare const version = "10.2.0";
|
||||
export declare const version = "10.6.1";
|
||||
export declare const homepage = "https://nodemailer.com/";
|
||||
+1
-1
@@ -3,5 +3,5 @@
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.homepage = exports.version = exports.name = void 0;
|
||||
exports.name = 'nodemailer';
|
||||
exports.version = '10.2.0';
|
||||
exports.version = '10.6.1';
|
||||
exports.homepage = 'https://nodemailer.com/';
|
||||
+23
@@ -289,3 +289,26 @@ export declare function unreadableStreamError(stream: Readable): NodemailerError
|
||||
* @param callback Callback function with (err, value)
|
||||
*/
|
||||
export declare function resolveStream(stream: Readable, callback: (err: Error | null, value?: Buffer) => void): void;
|
||||
/**
|
||||
* Encodes a domain the way browsers, the WHATWG URL Standard and DNS facing resolvers do,
|
||||
* which is with UTS-46 mapping applied before the Punycode step.
|
||||
*
|
||||
* The bundled codec is plain RFC 3492 and maps nothing, so it disagrees with every
|
||||
* conformant parser on any domain holding a mapped or ignored code point. An invisible
|
||||
* U+00AD in 'compa\u00ADny.com' encoded to 'xn--company-pka.com' where a validator reads
|
||||
* 'company.com', which let an allow-listed domain be checked and a different one mailed.
|
||||
*
|
||||
* Anything the URL parser does not accept as a hostname, an address literal such as
|
||||
* '[127.0.0.1]' included, comes back empty and falls through to the bundled codec, which
|
||||
* leaves those as they were supplied apart from lowercasing them.
|
||||
*
|
||||
* The mapper gets the domain as supplied, since UTS-46 does its own case mapping and
|
||||
* toLowerCase() differs from it: it turns U+1E9E into U+00DF where Node 20 and 22 map it
|
||||
* to 'ss', and a word-final U+03A3 into U+03C2 where UTS-46 gives U+03C3. Lowercasing
|
||||
* first sent 'user@stra\u1E9Ee.de', which a validator reads as strasse.de, to xn--strae-oqa.de.
|
||||
*
|
||||
* @param domain Domain to encode
|
||||
* @param toUnicode Return the U-label form instead of the A-label form
|
||||
* @return Encoded domain
|
||||
*/
|
||||
export declare function normalizeDomain(domain: string, toUnicode: boolean): string;
|
||||
+79
@@ -43,6 +43,7 @@ exports.recordStreamErrors = recordStreamErrors;
|
||||
exports.destroyStream = destroyStream;
|
||||
exports.unreadableStreamError = unreadableStreamError;
|
||||
exports.resolveStream = resolveStream;
|
||||
exports.normalizeDomain = normalizeDomain;
|
||||
const urllib = __importStar(require("./url.js"));
|
||||
const node_util_1 = __importDefault(require("node:util"));
|
||||
const node_fs_1 = __importDefault(require("node:fs"));
|
||||
@@ -54,6 +55,8 @@ Object.defineProperty(exports, "copyOwnKeys", { enumerable: true, get: function
|
||||
const node_dns_1 = __importDefault(require("node:dns"));
|
||||
const node_net_1 = __importDefault(require("node:net"));
|
||||
const node_os_1 = __importDefault(require("node:os"));
|
||||
const node_url_1 = __importDefault(require("node:url"));
|
||||
const punycode = __importStar(require("../punycode/index.js"));
|
||||
const node_stream_1 = require("node:stream");
|
||||
const DNS_TTL = 5 * 60 * 1000;
|
||||
const CACHE_CLEANUP_INTERVAL = 30 * 1000; // Minimum 30 seconds between cleanups
|
||||
@@ -771,3 +774,79 @@ function createDefaultLogger(levels) {
|
||||
});
|
||||
return logger;
|
||||
}
|
||||
// domainToASCII and domainToUnicode are WHATWG host parsers rather than plain IDNA
|
||||
// mappers, so they do more than map: they cut the host at '/', '\\', '?' and '#', drop C0
|
||||
// controls, and percent-decode. Handing them 'evil.example/mail.corp.example' returns the
|
||||
// deliverable 'evil.example', which would turn a value the bundled codec leaves as
|
||||
// unroutable garbage into mail for a domain the sender never named. None of these
|
||||
// characters are legal in a domain, so keep them away from the mapper.
|
||||
const URL_PARSER_UNSAFE = /[/\\?#%\x00-\x20\x7F]/;
|
||||
// RFC 1035 bounds a label at 63 octets and a domain at 253. An A-label is never shorter than
|
||||
// the code points it encodes, so anything past these bounds could not have become a valid
|
||||
// domain whichever way it is encoded. The bundled codec is super-linear in the length of a
|
||||
// label, a 60 KB label of distinct code points took seconds to encode, several times per
|
||||
// address, so it is only handed what could be a domain
|
||||
const MAX_DOMAIN_LENGTH = 253;
|
||||
const MAX_LABEL_LENGTH = 63;
|
||||
/**
|
||||
* Checks a domain against the DNS length limits, counted in code points per label and in
|
||||
* total. The label separators are the ones the bundled codec splits on.
|
||||
*
|
||||
* @param domain Domain to check
|
||||
* @return true if a label or the domain as a whole is too long to be a valid domain
|
||||
*/
|
||||
function exceedsDomainLimits(domain) {
|
||||
let total = 0;
|
||||
let label = 0;
|
||||
for (const char of domain) {
|
||||
total++;
|
||||
if (char === '.' || char === '。' || char === '.' || char === '。') {
|
||||
label = 0;
|
||||
}
|
||||
else if (++label > MAX_LABEL_LENGTH) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return total > MAX_DOMAIN_LENGTH;
|
||||
}
|
||||
/**
|
||||
* Encodes a domain the way browsers, the WHATWG URL Standard and DNS facing resolvers do,
|
||||
* which is with UTS-46 mapping applied before the Punycode step.
|
||||
*
|
||||
* The bundled codec is plain RFC 3492 and maps nothing, so it disagrees with every
|
||||
* conformant parser on any domain holding a mapped or ignored code point. An invisible
|
||||
* U+00AD in 'compa\u00ADny.com' encoded to 'xn--company-pka.com' where a validator reads
|
||||
* 'company.com', which let an allow-listed domain be checked and a different one mailed.
|
||||
*
|
||||
* Anything the URL parser does not accept as a hostname, an address literal such as
|
||||
* '[127.0.0.1]' included, comes back empty and falls through to the bundled codec, which
|
||||
* leaves those as they were supplied apart from lowercasing them.
|
||||
*
|
||||
* The mapper gets the domain as supplied, since UTS-46 does its own case mapping and
|
||||
* toLowerCase() differs from it: it turns U+1E9E into U+00DF where Node 20 and 22 map it
|
||||
* to 'ss', and a word-final U+03A3 into U+03C2 where UTS-46 gives U+03C3. Lowercasing
|
||||
* first sent 'user@stra\u1E9Ee.de', which a validator reads as strasse.de, to xn--strae-oqa.de.
|
||||
*
|
||||
* @param domain Domain to encode
|
||||
* @param toUnicode Return the U-label form instead of the A-label form
|
||||
* @return Encoded domain
|
||||
*/
|
||||
function normalizeDomain(domain, toUnicode) {
|
||||
// domainToASCII and domainToUnicode landed in Node 7, the bundled codec covers Node 6
|
||||
if (typeof node_url_1.default.domainToASCII === 'function' && typeof node_url_1.default.domainToUnicode === 'function' && !URL_PARSER_UNSAFE.test(domain)) {
|
||||
// The U-label form is decoded from the A-label form rather than from the input:
|
||||
// Deno's domainToASCII returns an empty string for a label it cannot decode, while
|
||||
// its domainToUnicode returns the label with U+FFFD in place of the bad part
|
||||
const ascii = node_url_1.default.domainToASCII(domain);
|
||||
const mapped = ascii && toUnicode ? node_url_1.default.domainToUnicode(ascii) : ascii;
|
||||
if (mapped) {
|
||||
return mapped;
|
||||
}
|
||||
}
|
||||
domain = domain.toLowerCase();
|
||||
if (exceedsDomainLimits(domain)) {
|
||||
// too long to be a domain whichever way it is encoded, keep it as supplied
|
||||
return domain;
|
||||
}
|
||||
return toUnicode ? punycode.toUnicode(domain) : punycode.toASCII(domain);
|
||||
}
|
||||
+3
@@ -42,6 +42,8 @@ export interface SMTPConnectionOptions {
|
||||
greetingTimeout?: number | undefined;
|
||||
/** Time of inactivity in ms until the connection is closed, defaults to 10 minutes */
|
||||
socketTimeout?: number | undefined;
|
||||
/** 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 */
|
||||
socketCloseTimeout?: number | undefined;
|
||||
/** Largest single server response to accept in bytes, defaults to 1 MB */
|
||||
maxResponseSize?: number | undefined;
|
||||
/** 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;
|
||||
* * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 30 seconds)
|
||||
* * **connectionTimeout** - how many milliseconds to wait for the connection to establish (defaults to 2 minutes)
|
||||
* * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 10 minutes)
|
||||
* * **socketCloseTimeout** - Time in ms to wait for the peer to close after ending the socket (defaults to 5 seconds, 0 destroys immediately)
|
||||
* * **maxResponseSize** - Largest single server response to accept in bytes (defaults to 1 MB)
|
||||
* * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds)
|
||||
* * **lmtp** - if true, uses LMTP instead of SMTP protocol
|
||||
|
||||
+17
-3
@@ -145,6 +145,7 @@ function maskAuthCommand(cmd) {
|
||||
* * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 30 seconds)
|
||||
* * **connectionTimeout** - how many milliseconds to wait for the connection to establish (defaults to 2 minutes)
|
||||
* * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 10 minutes)
|
||||
* * **socketCloseTimeout** - Time in ms to wait for the peer to close after ending the socket (defaults to 5 seconds, 0 destroys immediately)
|
||||
* * **maxResponseSize** - Largest single server response to accept in bytes (defaults to 1 MB)
|
||||
* * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds)
|
||||
* * **lmtp** - if true, uses LMTP instead of SMTP protocol
|
||||
@@ -287,6 +288,9 @@ class SMTPConnection extends node_events_1.EventEmitter {
|
||||
// socket object is set up but not yet connected
|
||||
this._socket = this.options.socket;
|
||||
return this._resolveAndConnect(opts, _resolved => {
|
||||
if (this._destroyed || this._closing) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this._socket.connect(this.port, this.host, () => {
|
||||
// a `secure` connection over a caller-provided socket must still
|
||||
@@ -465,11 +469,18 @@ class SMTPConnection extends node_events_1.EventEmitter {
|
||||
return;
|
||||
}
|
||||
this._closing = true;
|
||||
const closeMethod = this.stage === 'init' ? 'destroy' : 'end';
|
||||
// anything but a non-negative finite number keeps the default grace period
|
||||
const configuredCloseTimeout = this.options.socketCloseTimeout;
|
||||
const socketCloseTimeout = typeof configuredCloseTimeout === 'number' && Number.isFinite(configuredCloseTimeout) && configuredCloseTimeout >= 0
|
||||
? configuredCloseTimeout
|
||||
: CLOSE_TIMEOUT;
|
||||
const closeMethod = this.stage === 'init' || socketCloseTimeout === 0 ? 'destroy' : 'end';
|
||||
this.logger.debug({
|
||||
tnx: 'smtp'
|
||||
}, 'Closing connection to the server using "%s"', closeMethod);
|
||||
const socket = (this._socket && this._socket.socket) || this._socket;
|
||||
// after STARTTLS this is the TLS socket, tear that one down and not the plain socket it
|
||||
// wraps (Node 27 exposes the wrapped socket as `.socket`)
|
||||
const socket = this._socket;
|
||||
// Detach any in-flight DATA stream from the socket so the source stream
|
||||
// can be garbage-collected once the socket is gone.
|
||||
if (this._currentDataStream) {
|
||||
@@ -511,7 +522,7 @@ class SMTPConnection extends node_events_1.EventEmitter {
|
||||
if (closeMethod === 'end') {
|
||||
// end() only closes our side, a server that never closes its own would keep
|
||||
// the socket, and the process with it, around for good
|
||||
const closeTimer = setTimeout(() => socket.destroy(), CLOSE_TIMEOUT);
|
||||
const closeTimer = setTimeout(() => socket.destroy(), socketCloseTimeout);
|
||||
if (typeof closeTimer.unref === 'function') {
|
||||
closeTimer.unref();
|
||||
}
|
||||
@@ -1077,6 +1088,9 @@ class SMTPConnection extends node_events_1.EventEmitter {
|
||||
* @internal
|
||||
*/
|
||||
_upgradeConnection(callback) {
|
||||
if (this._destroyed || this._closing) {
|
||||
return;
|
||||
}
|
||||
// RFC 3207 section 6: the client MUST discard any knowledge obtained from
|
||||
// the server that was not received over the TLS-protected session. Drop any
|
||||
// buffered input received before the handshake so a man-in-the-middle cannot
|
||||
|
||||
+10
-3
@@ -76,6 +76,7 @@ export interface SMTPPoolRateLimit {
|
||||
* @param options SMTP Connection options
|
||||
*/
|
||||
declare class SMTPPool extends EventEmitter {
|
||||
readonly supportsAbortSignal = true;
|
||||
options: SMTPPoolResolvedOptions;
|
||||
logger: shared.Logger;
|
||||
name: string;
|
||||
@@ -102,10 +103,16 @@ declare class SMTPPool extends EventEmitter {
|
||||
*/
|
||||
send(mail: MailMessage<SMTPPoolSentMessageInfo>, callback: SMTPPoolSendCallback): boolean;
|
||||
/**
|
||||
* Closes all connections in the pool. If there is a message being sent, the connection
|
||||
* is closed later
|
||||
* Closes the pool. Idle connections are closed at once and a connection in the middle of a
|
||||
* delivery finishes it first, unless `force` is set: then it is closed too and its message
|
||||
* fails. `force` is for a caller that has given up on a delivery, such as one a server is
|
||||
* stalling by trickling its replies, which no socket timeout notices.
|
||||
*
|
||||
* @param options.force - Also close connections that are delivering a message
|
||||
*/
|
||||
close(): void;
|
||||
close(options?: {
|
||||
force?: boolean;
|
||||
}): void;
|
||||
/**
|
||||
* Returns true if there are free slots in the queue
|
||||
*/
|
||||
|
||||
+70
-12
@@ -56,6 +56,7 @@ const REQUEUE_MAX_DELAY = 2000;
|
||||
class SMTPPool extends node_events_1.EventEmitter {
|
||||
constructor(options) {
|
||||
super();
|
||||
this.supportsAbortSignal = true;
|
||||
options = options || {};
|
||||
if (typeof options === 'string') {
|
||||
options = {
|
||||
@@ -134,20 +135,33 @@ class SMTPPool extends node_events_1.EventEmitter {
|
||||
return false;
|
||||
}
|
||||
// counted until the callback runs, whichever path runs it: delivered, failed, requeued
|
||||
// until it gives up, or drained by close()
|
||||
// until it gives up, aborted, or drained by close()
|
||||
let counted = true;
|
||||
let detachSignal;
|
||||
this._pending++;
|
||||
this._queue.push({
|
||||
const entry = {
|
||||
mail,
|
||||
requeueAttempts: 0,
|
||||
callback: (err, info) => {
|
||||
if (counted) {
|
||||
counted = false;
|
||||
this._pending--;
|
||||
if (!counted) {
|
||||
return;
|
||||
}
|
||||
counted = false;
|
||||
this._pending--;
|
||||
detachSignal?.();
|
||||
entry.resource = undefined;
|
||||
callback(err, info);
|
||||
}
|
||||
});
|
||||
};
|
||||
this._queue.push(entry);
|
||||
const signal = mail.data.signal;
|
||||
if (signal) {
|
||||
// one listener for the original entry, retained across connection-close retries
|
||||
detachSignal = this._watchAbortSignal(entry, signal, () => counted);
|
||||
if (signal.aborted) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (this.idling && this._queue.length >= this.options.maxConnections) {
|
||||
this.idling = false;
|
||||
}
|
||||
@@ -155,10 +169,49 @@ class SMTPPool extends node_events_1.EventEmitter {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Closes all connections in the pool. If there is a message being sent, the connection
|
||||
* is closed later
|
||||
* Fails a queued or assigned entry when its signal aborts: removes it from the queue, or
|
||||
* closes the connection delivering it, so other deliveries in the pool can continue.
|
||||
* Returns a function that removes the listener.
|
||||
* @internal
|
||||
*/
|
||||
close() {
|
||||
_watchAbortSignal(entry, signal, isPending) {
|
||||
const onAbort = () => {
|
||||
if (!isPending()) {
|
||||
return;
|
||||
}
|
||||
const index = this._queue.indexOf(entry);
|
||||
if (index !== -1) {
|
||||
this._queue.splice(index, 1);
|
||||
}
|
||||
const resource = entry.resource;
|
||||
if (resource && resource.queueEntry === entry) {
|
||||
// Detach before closing: the close handler must not retry this message.
|
||||
resource.queueEntry = false;
|
||||
resource.close();
|
||||
}
|
||||
try {
|
||||
entry.callback(errors.createAbortError(signal));
|
||||
}
|
||||
finally {
|
||||
// Removing a queued entry can make the pool idle again.
|
||||
setImmediate(() => this._processMessages());
|
||||
}
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
if (signal.aborted) {
|
||||
setImmediate(onAbort);
|
||||
}
|
||||
return () => signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
/**
|
||||
* Closes the pool. Idle connections are closed at once and a connection in the middle of a
|
||||
* delivery finishes it first, unless `force` is set: then it is closed too and its message
|
||||
* fails. `force` is for a caller that has given up on a delivery, such as one a server is
|
||||
* stalling by trickling its replies, which no socket timeout notices.
|
||||
*
|
||||
* @param options.force - Also close connections that are delivering a message
|
||||
*/
|
||||
close(options) {
|
||||
let connection;
|
||||
const len = this._connections.length;
|
||||
this._closed = true;
|
||||
@@ -169,9 +222,10 @@ class SMTPPool extends node_events_1.EventEmitter {
|
||||
if (!len && !this._queue.length) {
|
||||
return;
|
||||
}
|
||||
// remove all available connections
|
||||
// remove all available connections, and with `force` the busy ones too
|
||||
const force = !!options?.force;
|
||||
for (let i = len - 1; i >= 0; i--) {
|
||||
if (this._connections[i] && this._connections[i].available) {
|
||||
if (this._connections[i] && (force || this._connections[i].available)) {
|
||||
connection = this._connections[i];
|
||||
connection.close();
|
||||
this.logger.info({
|
||||
@@ -249,6 +303,7 @@ class SMTPPool extends node_events_1.EventEmitter {
|
||||
this.emit('idle');
|
||||
}
|
||||
const entry = (connection.queueEntry = this._queue.shift());
|
||||
entry.resource = connection;
|
||||
entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, '');
|
||||
connection.available = false;
|
||||
this.logger.debug({
|
||||
@@ -356,7 +411,9 @@ class SMTPPool extends node_events_1.EventEmitter {
|
||||
setTimeout(() => {
|
||||
let delay = 0;
|
||||
if (connection.queueEntry) {
|
||||
if (this._shouldRequeuOnConnectionClose(connection.queueEntry)) {
|
||||
// a closed pool (a forced close ends a delivery on purpose) fails the
|
||||
// message rather than queueing it for a retry that would never run
|
||||
if (!this._closed && this._shouldRequeuOnConnectionClose(connection.queueEntry)) {
|
||||
delay = this._requeueEntryOnConnectionClose(connection);
|
||||
}
|
||||
else {
|
||||
@@ -418,6 +475,7 @@ class SMTPPool extends node_events_1.EventEmitter {
|
||||
messageId: connection.queueEntry.messageId,
|
||||
action: 'requeue'
|
||||
}, 'Re-queued message <%s> for #%s. Attempt: #%s', connection.queueEntry.messageId, connection.id, connection.queueEntry.requeueAttempts);
|
||||
connection.queueEntry.resource = undefined;
|
||||
this._queue.unshift(connection.queueEntry);
|
||||
connection.queueEntry = false;
|
||||
return delay;
|
||||
|
||||
+26
-4
@@ -86,6 +86,7 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
}
|
||||
this._connection = false;
|
||||
this._connected = false;
|
||||
this._closed = false;
|
||||
this.messages = 0;
|
||||
this.available = true;
|
||||
this._failed = false;
|
||||
@@ -113,6 +114,10 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
// the proxy handshake, if any, counts against connectionTimeout as well
|
||||
const connectStartedAt = Date.now();
|
||||
this.pool.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
|
||||
if (this._closed) {
|
||||
socketOptions && socketOptions.connection?.destroy();
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
// nothing was connected, so no 'close' event is coming that would free the
|
||||
// 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 {
|
||||
this.connection = new index_js_1.default(options);
|
||||
this.connection._connectStartedAt = connectStartedAt;
|
||||
this.connection.on('error', (err) => {
|
||||
if (this._sending) {
|
||||
if (this._closed || this._sending) {
|
||||
// the send callback gets the same error and decides what it means for the message
|
||||
return;
|
||||
}
|
||||
@@ -150,7 +155,7 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
return;
|
||||
}
|
||||
this._fail(err);
|
||||
if (returned) {
|
||||
if (returned || this._closed) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
@@ -161,7 +166,7 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
returned = true;
|
||||
});
|
||||
this.connection.connect(err => {
|
||||
if (returned) {
|
||||
if (returned || this._closed) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
@@ -172,7 +177,7 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
}
|
||||
if (this.auth && (this.connection.allowsAuth || options.forceAuth)) {
|
||||
this.connection.login(this.auth, err => {
|
||||
if (returned) {
|
||||
if (returned || this._closed) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
@@ -200,6 +205,9 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
* @param callback Callback function
|
||||
*/
|
||||
send(mail, callback) {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
if (!this._connected) {
|
||||
return this.connect(err => {
|
||||
if (err) {
|
||||
@@ -231,6 +239,9 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
const reused = this.messages > 0;
|
||||
const messageStream = mail.message.createReadStream();
|
||||
this.connection.send(envelope, messageStream, (err, info) => {
|
||||
if (mail.data.signal?.aborted) {
|
||||
return;
|
||||
}
|
||||
this._sending = false;
|
||||
this.messages++;
|
||||
if (err) {
|
||||
@@ -277,6 +288,9 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
* @internal
|
||||
*/
|
||||
_release() {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
if (this.messages >= this.options.maxMessages) {
|
||||
const err = new Error('Resource exhausted');
|
||||
err.code = errors.EMAXLIMIT;
|
||||
@@ -285,6 +299,9 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
return;
|
||||
}
|
||||
this.pool._checkRateLimit(() => {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
this.available = true;
|
||||
this._startIdleTimer();
|
||||
this.emit('available');
|
||||
@@ -327,6 +344,11 @@ class PoolResource extends node_events_1.EventEmitter {
|
||||
* Closes the connection
|
||||
*/
|
||||
close() {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
this._closed = true;
|
||||
this.available = false;
|
||||
this._connected = false;
|
||||
this._stopIdleTimer();
|
||||
if (this.auth && this.auth.oauth2) {
|
||||
|
||||
+1
@@ -93,6 +93,7 @@ export type SMTPTransportSendCallback = ResultCallback<SMTPSentMessageInfo>;
|
||||
* @param options Connection options
|
||||
*/
|
||||
declare class SMTPTransport extends EventEmitter {
|
||||
readonly supportsAbortSignal = true;
|
||||
options: SMTPTransportOptions;
|
||||
logger: shared.Logger;
|
||||
name: string;
|
||||
|
||||
+47
-35
@@ -59,6 +59,7 @@ const MESSAGE_AUTH_KEYS = ['type', 'user', 'pass', 'accessToken', 'refreshToken'
|
||||
class SMTPTransport extends node_events_1.EventEmitter {
|
||||
constructor(options) {
|
||||
super();
|
||||
this.supportsAbortSignal = true;
|
||||
options = options || {};
|
||||
if (typeof options === 'string') {
|
||||
options = {
|
||||
@@ -153,13 +154,46 @@ class SMTPTransport extends node_events_1.EventEmitter {
|
||||
* @param callback Callback function
|
||||
*/
|
||||
send(mail, callback) {
|
||||
const signal = mail.data.signal;
|
||||
let returned = false;
|
||||
let connection;
|
||||
let perCallAuth;
|
||||
const cleanupPerCallAuth = () => {
|
||||
if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
|
||||
perCallAuth.oauth2.removeAllListeners();
|
||||
}
|
||||
perCallAuth = null;
|
||||
};
|
||||
const finish = (err, info) => {
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
cleanupPerCallAuth();
|
||||
connection?.close();
|
||||
callback(err, info);
|
||||
};
|
||||
function onAbort() {
|
||||
finish(errors.createAbortError(signal));
|
||||
}
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
if (signal.aborted) {
|
||||
setImmediate(onAbort);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// the proxy handshake, if any, counts against connectionTimeout as well
|
||||
const connectStartedAt = Date.now();
|
||||
this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
|
||||
if (returned) {
|
||||
socketOptions && socketOptions.connection?.destroy();
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
let returned = false;
|
||||
let options = this.options;
|
||||
if (socketOptions && socketOptions.connection) {
|
||||
this.logger.info({
|
||||
@@ -173,24 +207,9 @@ class SMTPTransport extends node_events_1.EventEmitter {
|
||||
// only copy options if we need to modify it
|
||||
options = Object.assign(shared.assign(false, options), socketOptions);
|
||||
}
|
||||
const connection = new index_js_1.default(options);
|
||||
connection._connectStartedAt = connectStartedAt;
|
||||
let perCallAuth;
|
||||
const cleanupPerCallAuth = () => {
|
||||
if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
|
||||
perCallAuth.oauth2.removeAllListeners();
|
||||
}
|
||||
perCallAuth = null;
|
||||
};
|
||||
connection.once('error', err => {
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
cleanupPerCallAuth();
|
||||
connection.close();
|
||||
return callback(err);
|
||||
});
|
||||
const smtp = (connection = new index_js_1.default(options));
|
||||
smtp._connectStartedAt = connectStartedAt;
|
||||
smtp.once('error', err => finish(err));
|
||||
const sendMessage = () => {
|
||||
const envelope = mail.message.getEnvelope();
|
||||
const messageId = mail.message.messageId();
|
||||
@@ -209,20 +228,17 @@ class SMTPTransport extends node_events_1.EventEmitter {
|
||||
tnx: 'send',
|
||||
messageId
|
||||
}, 'Sending message %s to <%s>', messageId, recipients.join(', '));
|
||||
connection.send(envelope, mail.message.createReadStream(), (err, info) => {
|
||||
smtp.send(envelope, mail.message.createReadStream(), (err, info) => {
|
||||
if (returned) {
|
||||
// the connection error handler has already reported this send
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
cleanupPerCallAuth();
|
||||
connection.close();
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
err,
|
||||
tnx: 'send'
|
||||
}, 'Send error for %s: %s', messageId, err.message);
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
info.envelope = {
|
||||
from: envelope.from,
|
||||
@@ -230,7 +246,7 @@ class SMTPTransport extends node_events_1.EventEmitter {
|
||||
};
|
||||
info.messageId = messageId;
|
||||
try {
|
||||
return callback(null, info);
|
||||
return finish(null, info);
|
||||
}
|
||||
catch (E) {
|
||||
this.logger.error({
|
||||
@@ -240,27 +256,23 @@ class SMTPTransport extends node_events_1.EventEmitter {
|
||||
}
|
||||
});
|
||||
};
|
||||
connection.connect(err => {
|
||||
smtp.connect(err => {
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
// the server closed the connection before the greeting
|
||||
returned = true;
|
||||
connection.close();
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
perCallAuth = this.getAuth(mail.data.auth);
|
||||
if (perCallAuth && (connection.allowsAuth || options.forceAuth)) {
|
||||
connection.login(perCallAuth, err => {
|
||||
if (perCallAuth && (smtp.allowsAuth || options.forceAuth)) {
|
||||
smtp.login(perCallAuth, err => {
|
||||
cleanupPerCallAuth();
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
returned = true;
|
||||
connection.close();
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
sendMessage();
|
||||
});
|
||||
|
||||
+20
@@ -208,6 +208,13 @@ exports.services = {
|
||||
"host": "smtp.europe.secureserver.net",
|
||||
"port": 25
|
||||
},
|
||||
"Groundmail": {
|
||||
"description": "Groundmail",
|
||||
"host": "smtp.groundmail.dev",
|
||||
"port": 587,
|
||||
"secure": false,
|
||||
"requireTLS": true
|
||||
},
|
||||
"hot.ee": {
|
||||
"description": "Hot.ee (Estonian email provider)",
|
||||
"host": "mail.hot.ee"
|
||||
@@ -456,6 +463,12 @@ exports.services = {
|
||||
"host": "smtp-relay.brevo.com",
|
||||
"port": 587
|
||||
},
|
||||
"Sendora": {
|
||||
"description": "Sendora",
|
||||
"host": "smtp.sendora.se",
|
||||
"port": 465,
|
||||
"secure": true
|
||||
},
|
||||
"SendPulse": {
|
||||
"description": "SendPulse",
|
||||
"host": "smtp-pulse.com",
|
||||
@@ -602,6 +615,13 @@ exports.services = {
|
||||
"host": "mail.smtp2go.com",
|
||||
"port": 2525
|
||||
},
|
||||
"SpacePost": {
|
||||
"description": "SpacePost",
|
||||
"host": "smtp.spacepost.dev",
|
||||
"port": 25976,
|
||||
"secure": false,
|
||||
"requireTLS": true
|
||||
},
|
||||
"Sparkpost": {
|
||||
"description": "SparkPost",
|
||||
"aliases": [
|
||||
|
||||
+185
-2
@@ -46,6 +46,30 @@ class TokenList {
|
||||
this.slots[at + 2] = end;
|
||||
return this.length++;
|
||||
}
|
||||
/**
|
||||
* Offset of the first character of a token that is part of its value. A text run that is
|
||||
* no plain slice of the field still spans the whitespace and control characters its value
|
||||
* is trimmed of.
|
||||
*/
|
||||
contentStart(index) {
|
||||
let start = this.slots[index * 3 + 1];
|
||||
const end = this.slots[index * 3 + 2];
|
||||
while (start < end && _isDroppedCode(this.str.charCodeAt(start))) {
|
||||
start++;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
/**
|
||||
* Offset just past the last character of a token that is part of its value
|
||||
*/
|
||||
contentEnd(index) {
|
||||
const start = this.slots[index * 3 + 1];
|
||||
let end = this.slots[index * 3 + 2];
|
||||
while (end > start && _isDroppedCode(this.str.charCodeAt(end - 1))) {
|
||||
end--;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
/**
|
||||
* The character of an operator token, an empty string for a text run
|
||||
*/
|
||||
@@ -181,6 +205,44 @@ function _isSpaceCode(code) {
|
||||
code === 0x3000 ||
|
||||
code === 0xfeff);
|
||||
}
|
||||
/**
|
||||
* Checks for the whitespace RFC 5322 folding whitespace is made of: SP and HTAB, plus the
|
||||
* line break a fold carries. The other characters _isSpaceCode accepts are atext under
|
||||
* RFC 6532, and parsers disagree on them: mailauth keeps U+00A0 in a domain, so joining a
|
||||
* domain across one names a domain that reader never sees
|
||||
*
|
||||
* @param code Character code
|
||||
* @return true if the character is folding whitespace
|
||||
*/
|
||||
function _isFoldingSpaceCode(code) {
|
||||
return code === 0x20 || code === 0x09 || code === 0x0d || code === 0x0a;
|
||||
}
|
||||
/**
|
||||
* Checks if every character in a stretch of the field is folding whitespace
|
||||
*
|
||||
* @param str The field
|
||||
* @param from Offset of the first character
|
||||
* @param to Offset just past the last one
|
||||
* @return true if the stretch holds nothing but folding whitespace
|
||||
*/
|
||||
function _isFoldingGap(str, from, to) {
|
||||
for (let i = from; i < to; i++) {
|
||||
if (!_isFoldingSpaceCode(str.charCodeAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Checks for a character the value of a text run is trimmed of, or leaves out: whitespace,
|
||||
* C0 controls and DEL
|
||||
*
|
||||
* @param code Character code
|
||||
* @return true if the character is not part of the value at the edge of a run
|
||||
*/
|
||||
function _isDroppedCode(code) {
|
||||
return code < 0x20 || code === 0x7f || _isSpaceCode(code);
|
||||
}
|
||||
/**
|
||||
* The characters JS `\w` matches without the unicode flag, the set the `\b` in
|
||||
* 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])*"/;
|
||||
* The scan is by index, a pattern such as /\s+@/ backtracks over a long whitespace run that
|
||||
* no '@' follows.
|
||||
*
|
||||
* The whitespace around the dots of the domain that follows is dropped as well, see
|
||||
* _joinDomainDotSpacing.
|
||||
*
|
||||
* @param value Value holding the '@'
|
||||
* @param at Offset of the '@', or -1
|
||||
* @return The value with the whitespace beside that '@' removed
|
||||
@@ -247,7 +312,86 @@ function _joinAtSpacing(value, at) {
|
||||
while (end < value.length && _isSpaceCode(value.charCodeAt(end))) {
|
||||
end++;
|
||||
}
|
||||
return start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
|
||||
const joined = start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
|
||||
return _joinDomainDotSpacing(joined, start);
|
||||
}
|
||||
// The ASCII atext characters: printable, and none of the RFC 5322 specials
|
||||
const ASCII_ATEXT = new Uint8Array(0x80);
|
||||
for (let code = 0x21; code < 0x7f; code++) {
|
||||
ASCII_ATEXT[code] = '()<>[]:;@\\,."'.indexOf(String.fromCharCode(code)) < 0 ? 1 : 0;
|
||||
}
|
||||
/**
|
||||
* Checks if a character can be part of an atom: anything but the specials, whitespace and
|
||||
* the control characters (RFC 5322 3.2.3, with non-ASCII allowed as RFC 6532 does)
|
||||
*
|
||||
* @param code Character code
|
||||
* @return true if the character is atext
|
||||
*/
|
||||
function _isAtextCode(code) {
|
||||
return code < 0x80 ? ASCII_ATEXT[code] === 1 : !_isSpaceCode(code);
|
||||
}
|
||||
/**
|
||||
* Drops the whitespace around the dots of the domain behind the '@' at an offset.
|
||||
*
|
||||
* obs-domain is atoms with CFWS around the dots (RFC 5322 4.4), so 'user@victim.example
|
||||
* .allowed.example' names user@victim.example.allowed.example. Read as two runs, the domain
|
||||
* ended at the whitespace and the envelope went to victim.example, a different domain than
|
||||
* the one an RFC 5322 parser, and an application validating the address with one, reads
|
||||
* (GHSA-3q53-mvfw-q9v8). A comment around a dot reaches here as whitespace.
|
||||
*
|
||||
* Only SP, HTAB and a fold count as the whitespace, see _isFoldingSpaceCode.
|
||||
*
|
||||
* Only a dot with an atom on both sides joins, as for a conformant parser: whitespace that
|
||||
* is not beside a dot ends the domain, and so does a dot that no atom follows, which keeps
|
||||
* 'user@example.com .' from becoming a domain with a trailing dot. A domain literal is left
|
||||
* alone. Everything from where the domain ends is kept as it is.
|
||||
*
|
||||
* @param value Value holding the '@'
|
||||
* @param at Offset of the '@'
|
||||
* @return The value with the whitespace around the dots of that domain removed
|
||||
*/
|
||||
function _joinDomainDotSpacing(value, at) {
|
||||
const len = value.length;
|
||||
// '[' is no atext, so a domain literal ends the walk before it starts
|
||||
let pos = at + 1;
|
||||
let spaced = false;
|
||||
for (;;) {
|
||||
const labelStart = pos;
|
||||
while (pos < len && _isAtextCode(value.charCodeAt(pos))) {
|
||||
pos++;
|
||||
}
|
||||
if (pos === labelStart) {
|
||||
break;
|
||||
}
|
||||
// the dot, with the whitespace on either side of it, and the label behind it
|
||||
let next = pos;
|
||||
while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
|
||||
next++;
|
||||
}
|
||||
if (value.charCodeAt(next) !== 0x2e) {
|
||||
break;
|
||||
}
|
||||
next++;
|
||||
while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
|
||||
next++;
|
||||
}
|
||||
if (next >= len || !_isAtextCode(value.charCodeAt(next))) {
|
||||
break;
|
||||
}
|
||||
spaced = spaced || next !== pos + 1;
|
||||
pos = next;
|
||||
}
|
||||
if (!spaced) {
|
||||
return value;
|
||||
}
|
||||
// every whitespace character the walk covered sits beside a dot
|
||||
let domain = '';
|
||||
for (let k = at + 1; k < pos; k++) {
|
||||
if (!_isFoldingSpaceCode(value.charCodeAt(k))) {
|
||||
domain += value.charAt(k);
|
||||
}
|
||||
}
|
||||
return value.slice(0, at + 1) + domain + value.slice(pos);
|
||||
}
|
||||
/**
|
||||
* Drops the whitespace beside the '@' that splits the domain off a value. That is the '@'
|
||||
@@ -551,6 +695,15 @@ function _collectAddressParts(tokens, from, to) {
|
||||
// whether the last text run holds nothing but quoted text so far, which is what a quoted
|
||||
// local part is until the '@' after it joins the run
|
||||
let lastTextPureQuoted = false;
|
||||
// whether the last text run holds an unquoted '@', so that it runs on into a domain, and
|
||||
// whether nothing but comments has come since it, see the join below
|
||||
let lastTextHasAt = false;
|
||||
let lastTextOpen = false;
|
||||
// Where the last text run, or the last comment since it, ended in the field, and whether
|
||||
// everything between it and the comments since was folding whitespace. The tokens are
|
||||
// trimmed of any whitespace, so this is read off the field itself.
|
||||
let gapFrom = 0;
|
||||
let gapsFolding = true;
|
||||
// Last character of the run each state is currently accumulating. Reading it back off
|
||||
// the accumulator with slice(-1) makes the engine flatten the whole growing string on
|
||||
// every token, which is quadratic over an address built from many comment-joined atoms
|
||||
@@ -568,18 +721,27 @@ function _collectAddressParts(tokens, from, to) {
|
||||
case '<':
|
||||
state = 'address';
|
||||
insideQuotes = false;
|
||||
lastTextOpen = false;
|
||||
break;
|
||||
case '(':
|
||||
state = 'comment';
|
||||
insideQuotes = false;
|
||||
gapsFolding = gapsFolding && _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
|
||||
break;
|
||||
case '"':
|
||||
insideQuotes = !insideQuotes;
|
||||
state = 'text';
|
||||
lastTextOpen = false;
|
||||
break;
|
||||
default:
|
||||
state = 'text';
|
||||
insideQuotes = false;
|
||||
if (value !== ')') {
|
||||
lastTextOpen = false;
|
||||
}
|
||||
else {
|
||||
gapFrom = tokens.contentEnd(i);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -596,8 +758,23 @@ function _collectAddressParts(tokens, from, to) {
|
||||
// of the '@', but it cannot join two atoms into one: gluing across it would read
|
||||
// 'user@example.com(x)evil.com' as the single domain 'example.comevil.com' and
|
||||
// deliver to a domain the sender never named.
|
||||
// A comment beside a dot of a domain is CFWS inside obs-domain, with or without
|
||||
// folding whitespace around it, so 'user@victim.example(x).allowed.example' names
|
||||
// one domain (GHSA-3q53-mvfw-q9v8). Any other whitespace in between keeps them apart.
|
||||
// A ')' always leaves the walk in unquoted text, so neither needs checking here.
|
||||
// Neither join across a comment takes in a second '@' once the run holds one: the
|
||||
// address would then split at the last '@', and 'user@company(x).com@attacker.net',
|
||||
// which an RFC 5322 parser reads as user@company.com, would go to attacker.net.
|
||||
const parts = data[state];
|
||||
const joins = prevNoBreak && parts.length && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@');
|
||||
const secondAt = lastTextHasAt && prevOperator === ')' && value.indexOf('@') >= 0;
|
||||
const joinsDomain = !secondAt &&
|
||||
lastTextOpen &&
|
||||
lastTextHasAt &&
|
||||
prevOperator === ')' &&
|
||||
(lastChars.text === '.' || value.charAt(0) === '.') &&
|
||||
gapsFolding &&
|
||||
_isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
|
||||
const joins = joinsDomain || (!secondAt && prevNoBreak && parts.length > 0 && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@'));
|
||||
if (joins) {
|
||||
const last = data[state].length - 1;
|
||||
if (state === 'text' && !insideQuotes) {
|
||||
@@ -622,6 +799,12 @@ function _collectAddressParts(tokens, from, to) {
|
||||
lastTextPureQuoted = insideQuotes;
|
||||
}
|
||||
}
|
||||
if (state === 'text') {
|
||||
lastTextHasAt = (joins && lastTextHasAt) || (!insideQuotes && value.indexOf('@') >= 0);
|
||||
lastTextOpen = true;
|
||||
gapFrom = tokens.contentEnd(i);
|
||||
gapsFolding = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// If there is no text but a comment, replace the two. A comment is never part of a
|
||||
|
||||
+6
-5
@@ -1,4 +1,4 @@
|
||||
import * as punycode from '../punycode/index.js';
|
||||
import * as shared from '../shared/index.js';
|
||||
import * as mimeFuncs from '../mime-funcs/index.js';
|
||||
import crypto from 'node:crypto';
|
||||
import * as errors from '../errors.js';
|
||||
@@ -24,13 +24,14 @@ function unsupportedHashAlgoError(hashAlgo) {
|
||||
*/
|
||||
function sign(headers, hashAlgo, bodyHash, options) {
|
||||
options = options || {};
|
||||
// all listed fields from RFC4871 #5.5
|
||||
// all listed fields from RFC4871 #5.5, plus List-Unsubscribe-Post: RFC 8058 only allows
|
||||
// one-click unsubscribe when the signature covers it next to List-Unsubscribe
|
||||
const defaultFieldNames = 'From:Sender:Reply-To:Subject:Date:Message-ID:To:' +
|
||||
'Cc:MIME-Version:Content-Type:Content-Transfer-Encoding:Content-ID:' +
|
||||
'Content-Description:Resent-Date:Resent-From:Resent-Sender:' +
|
||||
'Resent-To:Resent-Cc:Resent-Message-ID:In-Reply-To:References:' +
|
||||
'List-Id:List-Help:List-Unsubscribe:List-Subscribe:List-Post:' +
|
||||
'List-Owner:List-Archive';
|
||||
'List-Id:List-Help:List-Unsubscribe:List-Unsubscribe-Post:List-Subscribe:List-Post:' +
|
||||
'List-Owner:List-Archive:OTP-Token';
|
||||
const fieldNames = options.headerFieldNames || defaultFieldNames;
|
||||
const canonicalizedHeaderData = relaxedHeaders(headers, fieldNames, options.skipFields);
|
||||
const dkimHeader = generateDKIMHeader(options.domainName, options.keySelector, canonicalizedHeaderData.fieldNames, hashAlgo, bodyHash);
|
||||
@@ -65,7 +66,7 @@ function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyH
|
||||
'v=1',
|
||||
'a=rsa-' + hashAlgo,
|
||||
'c=relaxed/relaxed',
|
||||
'd=' + punycode.toASCII(cleanTagValue(domainName)),
|
||||
'd=' + shared.normalizeDomain(cleanTagValue(domainName), false),
|
||||
'q=dns/txt',
|
||||
's=' + cleanTagValue(keySelector),
|
||||
'bh=' + bodyHash,
|
||||
|
||||
+4
@@ -21,7 +21,9 @@ export declare const ERROR_CODES: {
|
||||
readonly EPROTOCOL: "Invalid SMTP server response";
|
||||
readonly EENVELOPE: "Invalid mail envelope (sender or recipients)";
|
||||
readonly EMESSAGE: "Message delivery error";
|
||||
readonly EOTP: "Invalid one-time passcode data (otp option)";
|
||||
readonly ESTREAM: "Stream processing error";
|
||||
readonly EABORT: "Message sending aborted";
|
||||
readonly EAUTH: "Authentication failed";
|
||||
readonly ENOAUTH: "Authentication credentials not provided";
|
||||
readonly EOAUTH2: "OAuth2 token generation or refresh error";
|
||||
@@ -48,7 +50,9 @@ export declare const EREQUIRETLS = "EREQUIRETLS";
|
||||
export declare const EPROTOCOL = "EPROTOCOL";
|
||||
export declare const EENVELOPE = "EENVELOPE";
|
||||
export declare const EMESSAGE = "EMESSAGE";
|
||||
export declare const EOTP = "EOTP";
|
||||
export declare const ESTREAM = "ESTREAM";
|
||||
export declare const EABORT = "EABORT";
|
||||
export declare const EAUTH = "EAUTH";
|
||||
export declare const ENOAUTH = "ENOAUTH";
|
||||
export declare const EOAUTH2 = "EOAUTH2";
|
||||
|
||||
+11
@@ -24,7 +24,9 @@ export const ERROR_CODES = {
|
||||
EPROTOCOL: 'Invalid SMTP server response',
|
||||
EENVELOPE: 'Invalid mail envelope (sender or recipients)',
|
||||
EMESSAGE: 'Message delivery error',
|
||||
EOTP: 'Invalid one-time passcode data (otp option)',
|
||||
ESTREAM: 'Stream processing error',
|
||||
EABORT: 'Message sending aborted',
|
||||
// Authentication errors
|
||||
EAUTH: 'Authentication failed',
|
||||
ENOAUTH: 'Authentication credentials not provided',
|
||||
@@ -52,7 +54,9 @@ export const EREQUIRETLS = 'EREQUIRETLS';
|
||||
export const EPROTOCOL = 'EPROTOCOL';
|
||||
export const EENVELOPE = 'EENVELOPE';
|
||||
export const EMESSAGE = 'EMESSAGE';
|
||||
export const EOTP = 'EOTP';
|
||||
export const ESTREAM = 'ESTREAM';
|
||||
export const EABORT = 'EABORT';
|
||||
export const EAUTH = 'EAUTH';
|
||||
export const ENOAUTH = 'ENOAUTH';
|
||||
export const EOAUTH2 = 'EOAUTH2';
|
||||
@@ -65,6 +69,13 @@ export const EPROXY = 'EPROXY';
|
||||
export const EFILEACCESS = 'EFILEACCESS';
|
||||
export const EURLACCESS = 'EURLACCESS';
|
||||
export const EFETCH = 'EFETCH';
|
||||
/** Creates the error reported when a caller cancels an individual send. @internal */
|
||||
export const createAbortError = (signal) => {
|
||||
const err = new Error('Message sending aborted', { cause: signal.reason });
|
||||
err.name = 'AbortError';
|
||||
err.code = EABORT;
|
||||
return err;
|
||||
};
|
||||
/**
|
||||
* Tells whether the error ended the connection rather than rejected what was sent over it
|
||||
*/
|
||||
|
||||
+3
-1
@@ -71,7 +71,9 @@ declare class Cookies {
|
||||
*/
|
||||
add(cookie: Cookie): boolean;
|
||||
/**
|
||||
* Checks if two cookie objects are the same
|
||||
* Checks if two cookie objects are the same cookie. A cookie is identified by its
|
||||
* name, domain and path (RFC 6265 section 5.3), the Secure and HttpOnly flags are
|
||||
* attributes of the stored cookie that an update replaces
|
||||
*
|
||||
* @param a Cookie to check against
|
||||
* @param b Cookie to check against
|
||||
|
||||
+12
-3
@@ -51,6 +51,10 @@ class Cookies {
|
||||
if (!cookie.expires) {
|
||||
cookie.expires = new Date(Date.now() + (Number(this.options.sessionTimeout || SESSION_TIMEOUT) || SESSION_TIMEOUT) * 1000);
|
||||
}
|
||||
// a non-secure url can not set a Secure cookie, nor overwrite or delete one (RFC 6265bis section 5.7)
|
||||
if (urlparts.protocol !== 'https:' && (cookie.secure || this.cookies.some(stored => stored.secure && this.compare(stored, cookie)))) {
|
||||
return false;
|
||||
}
|
||||
return this.add(cookie);
|
||||
}
|
||||
/**
|
||||
@@ -93,6 +97,7 @@ class Cookies {
|
||||
parse(cookieStr) {
|
||||
const cookie = {};
|
||||
let hasNameValue = false;
|
||||
let hasMaxAge = false;
|
||||
(cookieStr || '')
|
||||
.toString()
|
||||
.split(';')
|
||||
@@ -120,7 +125,8 @@ class Cookies {
|
||||
case 'expires': {
|
||||
const expires = new Date(value);
|
||||
// ignore date if can not parse it
|
||||
if (expires.toString() !== 'Invalid Date') {
|
||||
if (expires.toString() !== 'Invalid Date' && !hasMaxAge) {
|
||||
// Max-Age has precedence when both attributes are present (RFC 6265 5.3)
|
||||
cookie.expires = expires;
|
||||
}
|
||||
break;
|
||||
@@ -137,6 +143,7 @@ class Cookies {
|
||||
break;
|
||||
case 'max-age':
|
||||
cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000);
|
||||
hasMaxAge = true;
|
||||
break;
|
||||
case 'secure':
|
||||
cookie.secure = true;
|
||||
@@ -206,14 +213,16 @@ class Cookies {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Checks if two cookie objects are the same
|
||||
* Checks if two cookie objects are the same cookie. A cookie is identified by its
|
||||
* name, domain and path (RFC 6265 section 5.3), the Secure and HttpOnly flags are
|
||||
* attributes of the stored cookie that an update replaces
|
||||
*
|
||||
* @param a Cookie to check against
|
||||
* @param b Cookie to check against
|
||||
* @returns True, if the cookies are the same
|
||||
*/
|
||||
compare(a, b) {
|
||||
return a.name === b.name && a.path === b.path && a.domain === b.domain && a.secure === b.secure && a.httponly === b.httponly;
|
||||
return a.name === b.name && a.path === b.path && a.domain === b.domain;
|
||||
}
|
||||
/**
|
||||
* Checks if a cookie is expired
|
||||
|
||||
+2
@@ -48,6 +48,8 @@ class JSONTransport {
|
||||
}
|
||||
delete data.envelope;
|
||||
delete data.normalizedHeaders;
|
||||
// the per-message AbortSignal is not message data
|
||||
delete data.signal;
|
||||
// the message field is the object itself with skipEncoding, the
|
||||
// createTransport overload for that option types the result accordingly
|
||||
return done(null, {
|
||||
|
||||
+12
@@ -72,6 +72,16 @@ export type MailComposerListHeaderEntry = string | {
|
||||
export interface MailComposerListHeaders {
|
||||
[key: string]: MailComposerListHeaderEntry | (MailComposerListHeaderEntry | MailComposerListHeaderEntry[])[];
|
||||
}
|
||||
/**
|
||||
* The otp value: a one-time passcode and the origin it is bound to, sent as the OTP-Token
|
||||
* header (draft-goto-otp-token)
|
||||
*/
|
||||
export interface MailComposerOtp {
|
||||
/** The passcode, printable ascii */
|
||||
code: string;
|
||||
/** Origin the code is bound to, https or a loopback http origin. A full url is reduced to its origin */
|
||||
origin: string;
|
||||
}
|
||||
/**
|
||||
* Encoding for the non-ascii header values: quoted-printable ('Q', the default) or base64
|
||||
* ('B'). Only the first letter is read, so the short forms work as well
|
||||
@@ -114,6 +124,8 @@ export interface MailComposerOptions {
|
||||
headers?: MimeNodeHeaders | undefined;
|
||||
/** List-* headers, read by the mailer */
|
||||
list?: MailComposerListHeaders | undefined;
|
||||
/** One-time passcode for the OTP-Token header. An invalid value makes compile() throw an EOTP error */
|
||||
otp?: MailComposerOtp | undefined;
|
||||
/** SMTP envelope to use instead of the one generated from the headers */
|
||||
envelope?: MimeNodeEnvelopeInput | undefined;
|
||||
/** Content-Transfer-Encoding to force for the text/* nodes that do not set their own */
|
||||
|
||||
+53
@@ -1,6 +1,7 @@
|
||||
/* eslint no-undefined: 0 */
|
||||
import MimeNode from '../mime-node/index.js';
|
||||
import * as mimeFuncs from '../mime-funcs/index.js';
|
||||
import * as errors from '../errors.js';
|
||||
import { parseDataURI, copyOwnKeys } from '../shared/index.js';
|
||||
/**
|
||||
* Creates the object for composing a MimeNode instance out from the mail options
|
||||
@@ -95,6 +96,10 @@ class MailComposer {
|
||||
if (this.mail.headers) {
|
||||
this.message.addHeader(this.mail.headers);
|
||||
}
|
||||
// after the custom headers, so it replaces an OTP-Token from them, the field may appear only once
|
||||
if (this.mail.otp) {
|
||||
this.message.setHeader('OTP-Token', formatOtpToken(this.mail.otp));
|
||||
}
|
||||
// Add headers to the root node, always overrides custom headers
|
||||
['from', 'sender', 'to', 'cc', 'bcc', 'reply-to', 'in-reply-to', 'references', 'subject', 'message-id', 'date'].forEach(header => {
|
||||
const key = header.replace(/-(\w)/g, (o, c) => c.toUpperCase());
|
||||
@@ -603,4 +608,52 @@ class MailComposer {
|
||||
return element;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns the value of the OTP-Token header for the otp option. The header is defined by
|
||||
* draft-goto-otp-token-01, an Internet-Draft that expires on 25 March 2027. By then check
|
||||
* for a newer revision of the draft or a published RFC, the header name and its
|
||||
* parameters are still open questions in the draft.
|
||||
*/
|
||||
function formatOtpToken(otp) {
|
||||
// a structured field String can only hold printable ascii. The code is a secret the recipient
|
||||
// compares against the one in the message body, so it is rejected rather than cleaned up
|
||||
if (typeof otp.code !== 'string' || !/^[\x20-\x7e]+$/.test(otp.code)) {
|
||||
throw otpError('The otp code must be a non-empty string of printable ASCII characters');
|
||||
}
|
||||
// a structured field String escapes the same two characters as a quoted-string
|
||||
return mimeFuncs.quoteString(otp.code) + '; origin=' + mimeFuncs.quoteString(getOtpOrigin(otp.origin));
|
||||
}
|
||||
/**
|
||||
* Returns the canonical ascii serialization of the origin the code is bound to. The draft
|
||||
* requires a potentially trustworthy origin, so only https is accepted, plus http on a
|
||||
* loopback host for local development
|
||||
*/
|
||||
function getOtpOrigin(origin) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(String(origin));
|
||||
}
|
||||
catch {
|
||||
// handled below
|
||||
}
|
||||
// the WHATWG parser lets characters such as a quote or a brace into a host, which the
|
||||
// origin grammar the draft requires (RFC 6454) does not allow, so a receiver would discard
|
||||
// the header. Only a DNS name, an IPv4 address or a bracketed IPv6 address is accepted.
|
||||
// Userinfo is refused as well, an origin never has it and it turns a value built as
|
||||
// 'https://example.com' + input into the origin of whatever host follows an "@"
|
||||
if (!url || url.username || url.password || !/^([a-z0-9_-]+\.)*[a-z0-9_-]+$|^\[[0-9a-f:.]+\]$/.test(url.hostname)) {
|
||||
throw otpError('The otp origin must be an absolute https URL');
|
||||
}
|
||||
const isLoopback = /^(localhost|.+\.localhost|127(\.\d+){3}|\[::1\])$/.test(url.hostname);
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback)) {
|
||||
throw otpError('The otp origin must be an https URL, or an http URL on a loopback host');
|
||||
}
|
||||
// the URL parser already lowercases the host, converts it to punycode and drops the default port
|
||||
return url.origin;
|
||||
}
|
||||
function otpError(message) {
|
||||
const err = new Error(message);
|
||||
err.code = errors.EOTP;
|
||||
return err;
|
||||
}
|
||||
export default MailComposer;
|
||||
+15
-4
@@ -4,7 +4,7 @@ import DKIM, { type DKIMOptions } from '../dkim/index.js';
|
||||
import MailMessage, { type MailDefaults, type SendMailOptions } from './mail-message.js';
|
||||
import net from 'node:net';
|
||||
import type { ConnectionOptions } from 'node:tls';
|
||||
import type { MailComposerAlternative, MailComposerAttachment, MailComposerIcalEvent, MailComposerListHeaderEntry, MailComposerListHeaders, MailComposerTextEncoding } from '../mail-composer/index.js';
|
||||
import type { MailComposerAlternative, MailComposerAttachment, MailComposerIcalEvent, MailComposerListHeaderEntry, MailComposerListHeaders, MailComposerOtp, MailComposerTextEncoding } from '../mail-composer/index.js';
|
||||
import type { Callback, NodemailerError, ResultCallback } from '../errors.js';
|
||||
import type { ParsedUrl } from '../shared/url.js';
|
||||
import type { MimeNodeAddress, MimeNodeEnvelope, MimeNodeEnvelopeInput, MimeNodeHeaders, MimeNodeOptions } from '../mime-node/index.js';
|
||||
@@ -112,6 +112,11 @@ export interface MailMeta {
|
||||
* declared on Transport, Transporter and Mail
|
||||
*/
|
||||
export interface Transport<T = SentMessageInfo, D extends TransportOptions = TransportOptions> {
|
||||
/**
|
||||
* Set only if send() cancels its own work on mail.data.signal and removes its signal listener
|
||||
* when finished. Without it the signal is still honored up to dispatch, then ignored.
|
||||
*/
|
||||
supportsAbortSignal?: boolean | undefined;
|
||||
/** Transport name, used for logging */
|
||||
name: string;
|
||||
/** Transport version, used for logging */
|
||||
@@ -176,8 +181,13 @@ declare class Mail<out T = SentMessageInfo, out D extends TransportOptions = Tra
|
||||
dkim: DKIM | false;
|
||||
transporter: Transport<T, D>;
|
||||
logger: shared.Logger;
|
||||
/** Closes the transport, the pooled SMTP transport closes its connections */
|
||||
close: () => void;
|
||||
/**
|
||||
* Closes the transport, the pooled SMTP transport closes its connections. With `force` the
|
||||
* pooled transport also closes connections that are delivering a message
|
||||
*/
|
||||
close: (options?: {
|
||||
force?: boolean;
|
||||
}) => void;
|
||||
/** Tells whether the transport can take a message right away */
|
||||
isIdle: () => boolean;
|
||||
/** Checks the configuration, the SMTP transports connect and authenticate for it */
|
||||
@@ -227,11 +237,12 @@ declare namespace Mail {
|
||||
type Headers = MimeNodeHeaders;
|
||||
type ListHeader = MailComposerListHeaderEntry;
|
||||
type ListHeaders = MailComposerListHeaders;
|
||||
type Otp = MailComposerOtp;
|
||||
type Envelope = MimeNodeEnvelopeInput;
|
||||
type Connection = SocketOptions;
|
||||
type TextEncoding = MailComposerTextEncoding;
|
||||
type PluginFunction<T = SentMessageInfo> = MailPluginFunction<T>;
|
||||
}
|
||||
/** The same aliases as module level exports, for `import * as Mail` and `import Mail = require()` */
|
||||
export type { SendMailOptions as Options, MimeNodeAddress as Address, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerAlternative as AmpAttachment, MailComposerIcalEvent as IcalAttachment, MimeNodeHeaders as Headers, MailComposerListHeaderEntry as ListHeader, MailComposerListHeaders as ListHeaders, MimeNodeEnvelopeInput as Envelope, SocketOptions as Connection, MailComposerTextEncoding as TextEncoding };
|
||||
export type { SendMailOptions as Options, MimeNodeAddress as Address, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerAlternative as AmpAttachment, MailComposerIcalEvent as IcalAttachment, MimeNodeHeaders as Headers, MailComposerListHeaderEntry as ListHeader, MailComposerListHeaders as ListHeaders, MailComposerOtp as Otp, MimeNodeEnvelopeInput as Envelope, SocketOptions as Connection, MailComposerTextEncoding as TextEncoding };
|
||||
export default Mail;
|
||||
+56
-4
@@ -18,6 +18,16 @@ import crypto from 'node:crypto';
|
||||
* asks a server to accept 100, so a real send is bounded far below this.
|
||||
*/
|
||||
const DEFAULT_MAX_RECIPIENTS = 100000;
|
||||
/**
|
||||
* Duck-typed so that signals from another realm or a polyfill are accepted as well
|
||||
*/
|
||||
function isAbortSignal(value) {
|
||||
return (typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'aborted' in value &&
|
||||
typeof value.addEventListener === 'function' &&
|
||||
typeof value.removeEventListener === 'function');
|
||||
}
|
||||
/**
|
||||
* Creates an object for exposing the Mail API
|
||||
*
|
||||
@@ -119,11 +129,43 @@ class Mail extends EventEmitter {
|
||||
this.getSocket = false;
|
||||
}
|
||||
const mail = new MailMessage(this, data);
|
||||
const signalOption = mail.data.signal;
|
||||
const signal = isAbortSignal(signalOption) ? signalOption : undefined;
|
||||
let settled = false;
|
||||
const removeAbortListener = () => signal?.removeEventListener('abort', onAbort);
|
||||
const finish = (err, info) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
removeAbortListener();
|
||||
if (err) {
|
||||
mail.releaseStreams();
|
||||
}
|
||||
done(err, info);
|
||||
};
|
||||
// a failed message is not going to be read anymore, release its content streams
|
||||
const fail = (err) => {
|
||||
mail.releaseStreams();
|
||||
done(err);
|
||||
finish(err);
|
||||
};
|
||||
function onAbort() {
|
||||
fail(errors.createAbortError(signal));
|
||||
}
|
||||
if (signalOption !== undefined && signalOption !== null && !signal) {
|
||||
const err = new Error('The signal option must be an AbortSignal');
|
||||
err.code = errors.ECONFIG;
|
||||
setImmediate(() => fail(err));
|
||||
return promise;
|
||||
}
|
||||
// Mail handles a pre-aborted signal and cancellation during plugin processing for every
|
||||
// transport; a transport without supportsAbortSignal ignores the signal once it is called
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
if (signal.aborted) {
|
||||
setImmediate(onAbort);
|
||||
return promise;
|
||||
}
|
||||
}
|
||||
this.logger.debug({
|
||||
tnx: 'transport',
|
||||
name: this.transporter.name,
|
||||
@@ -131,6 +173,9 @@ class Mail extends EventEmitter {
|
||||
action: 'send'
|
||||
}, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version);
|
||||
this._processPlugins('compile', mail, err => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
err,
|
||||
@@ -168,6 +213,9 @@ class Mail extends EventEmitter {
|
||||
return fail(err);
|
||||
}
|
||||
this._processPlugins('stream', mail, err => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
err,
|
||||
@@ -187,16 +235,17 @@ class Mail extends EventEmitter {
|
||||
return dkim.sign(input, mail.data._dkim);
|
||||
});
|
||||
}
|
||||
// The transport takes ownership of cancellation from here, including queued work.
|
||||
removeAbortListener();
|
||||
this.transporter.send(mail, (...args) => {
|
||||
if (args[0]) {
|
||||
mail.releaseStreams();
|
||||
this.logger.error({
|
||||
err: args[0],
|
||||
tnx: 'transport',
|
||||
action: 'send'
|
||||
}, 'Send Error: %s', args[0].message);
|
||||
}
|
||||
done(...args);
|
||||
finish(...args);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -226,6 +275,9 @@ class Mail extends EventEmitter {
|
||||
let pos = 0;
|
||||
let block = 'default';
|
||||
const processPlugins = () => {
|
||||
if (mail.data.signal?.aborted) {
|
||||
return callback(errors.createAbortError(mail.data.signal));
|
||||
}
|
||||
let curplugins = block === 'default' ? defaultPlugins : userPlugins;
|
||||
if (pos >= curplugins.length) {
|
||||
if (block === 'default' && userPlugins.length) {
|
||||
|
||||
+10
@@ -13,6 +13,16 @@ import type { SentMessageInfo } from './index.js';
|
||||
* tree is built from, the fields below are the ones the mailer reads on top of those
|
||||
*/
|
||||
export interface SendMailOptions extends MailComposerOptions {
|
||||
/**
|
||||
* Cancel this send, including waiting for plugins or in an SMTP pool queue.
|
||||
* Plugins must cooperate with the signal to stop their own work already in progress.
|
||||
* Supported by SMTP, pooled SMTP and transports declaring supportsAbortSignal. Other
|
||||
* transports ignore the signal once the message is handed to them; a signal that is
|
||||
* already aborted, or aborts during plugin processing, still cancels the send.
|
||||
* Fails with AbortError/EABORT on cancellation, ECONFIG if the value is not an AbortSignal.
|
||||
* Aborting does not prove that the server has not already accepted the message.
|
||||
*/
|
||||
signal?: AbortSignal | undefined;
|
||||
/** DKIM signing options for this message, used instead of the ones of the transporter */
|
||||
dkim?: DKIMOptions | undefined;
|
||||
/** 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 */
|
||||
|
||||
+20
-2
@@ -74,7 +74,8 @@ export declare function hasLongerLines(str: string, lineLength: number): boolean
|
||||
*/
|
||||
export declare function encodeWord(data: string | Buffer, mimeWordEncoding?: string, maxLength?: number): string;
|
||||
/**
|
||||
* Finds word sequences with non ascii text and converts these to mime words
|
||||
* Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
|
||||
* and converts these to mime words. A valid encoded-word is passed through as it is.
|
||||
*
|
||||
* @param value String to be encoded
|
||||
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
|
||||
@@ -107,6 +108,22 @@ export declare function buildHeaderValue(structured: StructuredHeaderValue): str
|
||||
* @return A list of encoded keys and headers
|
||||
*/
|
||||
export declare function buildHeaderParam(key: string, data: string | Buffer, maxLength?: number): EncodedHeaderParam[];
|
||||
/**
|
||||
* Options of parseHeaderValue()
|
||||
*/
|
||||
export interface ParseHeaderValueOptions {
|
||||
/**
|
||||
* Drop the RFC 822 comments outside quoted strings, which the MIME headers allow and
|
||||
* which are not part of the value: 'boundary=b (comment)' names the boundary 'b'. A
|
||||
* parenthesis right behind the '=' of a parameter or behind a token character of its
|
||||
* value continues the token, as it does for Python and postal-mime, so 'Invoice(1).pdf'
|
||||
* keeps its name and 'boundary=(c)b' names the boundary '(c)b'. A comment that never
|
||||
* closes runs to the end of the value, unless a parameter follows it, in which case it is
|
||||
* content and the parameter survives. Comments are kept by default for the sake of the
|
||||
* callers of this exported function, not because keeping them is ever the better reading
|
||||
*/
|
||||
stripComments?: boolean | undefined;
|
||||
}
|
||||
/**
|
||||
* Parses a header value with key=value arguments into a structured
|
||||
* object.
|
||||
@@ -120,9 +137,10 @@ export declare function buildHeaderParam(key: string, data: string | Buffer, max
|
||||
* }
|
||||
*
|
||||
* @param str Header value
|
||||
* @param options Options, see ParseHeaderValueOptions
|
||||
* @return Header value as a parsed structure
|
||||
*/
|
||||
export declare function parseHeaderValue(str: string): ParsedHeaderValue;
|
||||
export declare function parseHeaderValue(str: string, options?: ParseHeaderValueOptions): ParsedHeaderValue;
|
||||
/**
|
||||
* Returns file extension for a content type string. If no suitable extensions
|
||||
* are found, 'bin' is used as the default extension
|
||||
|
||||
+115
-3
@@ -132,8 +132,75 @@ export function encodeWord(data, mimeWordEncoding, maxLength) {
|
||||
}
|
||||
return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?=');
|
||||
}
|
||||
// An encoded-word as RFC 2047 section 2 spells it: a charset token (with an optional RFC 2231
|
||||
// language), B or Q, and encoded text without '?' or whitespace. None of the parts can hold the
|
||||
// '?' that separates them, so the pattern never backtracks
|
||||
const VALID_ENCODED_WORD = /^=\?[^\s()<>@,;:"/[\]?.=]+\?[BbQq]\?[^?\s]+\?=$/;
|
||||
// What a lenient decoder reads as an encoded-word: libmime and Python decode
|
||||
// '=?utf-8?Q?a b?=' across the space as well. Applied sticky at a '=?', and every part stops
|
||||
// at the next '?', so it does not backtrack either
|
||||
const LENIENT_ENCODED_WORD = /[=]\?[^?]*\?[BbQq]\?[^?]*\?=/y;
|
||||
/**
|
||||
* Finds word sequences with non ascii text and converts these to mime words
|
||||
* Marks the text a receiver would read as an encoded-word when it is not one valid encoded-word
|
||||
* on its own. RFC 2047 section 7 requires that a word beginning with '=?' and ending with '?='
|
||||
* is a valid encoded-word, and decoders also decode a look-alike that spans whitespace, so
|
||||
* '=?utf-8?X?x?=' and 'see =?utf-8?Q?a b?= here' read differently on every receiver. A valid
|
||||
* encoded-word is left alone, which is what lets a caller pass a value that is already encoded,
|
||||
* as most other mail libraries do.
|
||||
*
|
||||
* The bounds of the word around each '=?' are found once per word and reused, walking back to
|
||||
* the start of a long word from every '=?' it holds would be quadratic.
|
||||
*
|
||||
* @param value String to look in
|
||||
* @param range The first and the last offset that needs encoding so far, -1 for none
|
||||
* @return The range, widened to cover the words of every invalid look-alike
|
||||
*/
|
||||
function _markInvalidEncodedWords(value, range) {
|
||||
const len = value.length;
|
||||
const isSpace = (pos) => /\s/.test(value.charAt(pos));
|
||||
// the word last looked at, its start and the offset just past it
|
||||
let wordStart = 0;
|
||||
let wordEnd = -1;
|
||||
const wordAt = (pos) => {
|
||||
if (pos < wordEnd) {
|
||||
return;
|
||||
}
|
||||
// the previous word ended at whitespace, so the walk back stops before reaching it
|
||||
wordStart = pos;
|
||||
while (wordStart > 0 && !isSpace(wordStart - 1)) {
|
||||
wordStart--;
|
||||
}
|
||||
wordEnd = pos;
|
||||
while (wordEnd < len && !isSpace(wordEnd)) {
|
||||
wordEnd++;
|
||||
}
|
||||
};
|
||||
let pos = value.indexOf('=?');
|
||||
while (pos >= 0) {
|
||||
wordAt(pos);
|
||||
const start = wordStart;
|
||||
LENIENT_ENCODED_WORD.lastIndex = pos;
|
||||
const match = LENIENT_ENCODED_WORD.exec(value);
|
||||
const end = match ? pos + match[0].length : wordEnd;
|
||||
if (match && end > wordEnd) {
|
||||
// the look-alike runs across whitespace, on to the word it ends in
|
||||
wordAt(end - 1);
|
||||
}
|
||||
const word = value.substring(start, wordEnd);
|
||||
// without a match, a word that begins with '=?' and ends with '?=' is still invalid
|
||||
const looksLike = match ? true : start === pos && word.length >= 4 && word.endsWith('?=');
|
||||
const valid = start === pos && wordEnd === end && word.length <= 75 && VALID_ENCODED_WORD.test(word);
|
||||
if (looksLike && !valid) {
|
||||
range[0] = range[0] < 0 ? start : Math.min(range[0], start);
|
||||
range[1] = Math.max(range[1], wordEnd - 1);
|
||||
}
|
||||
pos = value.indexOf('=?', match ? end : pos + 2);
|
||||
}
|
||||
return range;
|
||||
}
|
||||
/**
|
||||
* Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
|
||||
* and converts these to mime words. A valid encoded-word is passed through as it is.
|
||||
*
|
||||
* @param value String to be encoded
|
||||
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
|
||||
@@ -157,11 +224,14 @@ export function encodeWords(value, mimeWordEncoding, maxLength, encodeAll) {
|
||||
lastSpecial = i;
|
||||
}
|
||||
}
|
||||
if (value.indexOf('=?') >= 0) {
|
||||
[firstSpecial, lastSpecial] = _markInvalidEncodedWords(value, [firstSpecial, lastSpecial]);
|
||||
}
|
||||
if (firstSpecial < 0) {
|
||||
return value;
|
||||
}
|
||||
if (encodeAll) {
|
||||
// if it is requested to encode everything or the string contains something that resebles encoded word, then encode everything
|
||||
// the value needs encoding and it is requested to encode everything
|
||||
return encodeWord(value, mimeWordEncoding, maxLength);
|
||||
}
|
||||
// encode from the start of the word holding the first such character to the end of the
|
||||
@@ -365,6 +435,26 @@ export function buildHeaderParam(key, data, maxLength) {
|
||||
* goes in. Whitespace used to come off it only because the value was trimmed first.
|
||||
*/
|
||||
const TOKEN = /^[^\x00-\x20\x7f()<>@,;:\\"/[\]?=]+$/;
|
||||
/**
|
||||
* Offset of the ')' that closes the RFC 822 comment opening at `start`, or -1 when the
|
||||
* comment never closes. Comments nest, and a backslash escapes the character after it
|
||||
*/
|
||||
function _findCommentEnd(str, start) {
|
||||
let depth = 0;
|
||||
for (let i = start, len = str.length; i < len; i++) {
|
||||
const c = str.charAt(i);
|
||||
if (c === '\\') {
|
||||
i++;
|
||||
}
|
||||
else if (c === '(') {
|
||||
depth++;
|
||||
}
|
||||
else if (c === ')' && --depth === 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/**
|
||||
* Whether a string can be a header parameter name.
|
||||
*
|
||||
@@ -391,13 +481,16 @@ function _isParamName(name) {
|
||||
* }
|
||||
*
|
||||
* @param str Header value
|
||||
* @param options Options, see ParseHeaderValueOptions
|
||||
* @return Header value as a parsed structure
|
||||
*/
|
||||
export function parseHeaderValue(str) {
|
||||
export function parseHeaderValue(str, options) {
|
||||
const response = {
|
||||
value: '',
|
||||
params: {}
|
||||
};
|
||||
// Cleared again by an unclosed '(', see the loop
|
||||
let stripComments = !!options?.stripComments;
|
||||
// A duplicated parameter resolves to its first occurrence, the way a duplicated header
|
||||
// does. Letting the last one win disagrees with the receivers that take the first, and
|
||||
// the two readings of 'boundary="b"; boundary="c"' name different delimiters. The
|
||||
@@ -459,6 +552,25 @@ export function parseHeaderValue(str) {
|
||||
};
|
||||
for (let i = 0, len = str.length; i < len; i++) {
|
||||
chr = str.charAt(i);
|
||||
// With stripComments, an RFC 822 comment stands anywhere outside a quoted string but
|
||||
// right behind a token it would continue, see ParseHeaderValueOptions. In the value
|
||||
// of a parameter, no pending whitespace means the last significant character was the
|
||||
// '=' or a character of the token
|
||||
if (stripComments && chr === '(' && !quote && !quoteClosed && !(stage === 'value' && key !== false && !pendingSpace)) {
|
||||
let end = _findCommentEnd(str, i);
|
||||
if (end < 0 && str.indexOf(';', i) < 0) {
|
||||
// a comment that never closes runs to the end of the value, unless a
|
||||
// parameter follows it, which is content then and survives
|
||||
end = len - 1;
|
||||
}
|
||||
if (end >= 0) {
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
// looking for a closing ')' again would scan a run of unclosed '(' to its end
|
||||
// once for each of them
|
||||
stripComments = false;
|
||||
}
|
||||
if (stage === 'key') {
|
||||
if (chr === '=') {
|
||||
key = takeValue().trim();
|
||||
|
||||
+16
-77
@@ -1,10 +1,8 @@
|
||||
/* eslint no-undefined: 0, prefer-spread: 0, no-control-regex: 0 */
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import * as punycode from '../punycode/index.js';
|
||||
import { PassThrough, finished, pipeline } from 'node:stream';
|
||||
import * as shared from '../shared/index.js';
|
||||
import urlModule from 'node:url';
|
||||
import * as mimeFuncs from '../mime-funcs/index.js';
|
||||
import * as qp from '../qp/index.js';
|
||||
import * as base64 from '../base64/index.js';
|
||||
@@ -55,20 +53,6 @@ function stripWhitespaceInAngleBrackets(value) {
|
||||
}
|
||||
return result + value.slice(pos);
|
||||
}
|
||||
// domainToASCII and domainToUnicode are WHATWG host parsers rather than plain IDNA
|
||||
// mappers, so they do more than map: they cut the host at '/', '\\', '?' and '#', drop C0
|
||||
// controls, and percent-decode. Handing them 'evil.example/mail.corp.example' returns the
|
||||
// deliverable 'evil.example', which would turn a value the bundled codec leaves as
|
||||
// unroutable garbage into mail for a domain the sender never named. None of these
|
||||
// characters are legal in a domain, so keep them away from the mapper.
|
||||
const URL_PARSER_UNSAFE = /[/\\?#%\x00-\x20\x7F]/;
|
||||
// RFC 1035 bounds a label at 63 octets and a domain at 253. An A-label is never shorter than
|
||||
// the code points it encodes, so anything past these bounds could not have become a valid
|
||||
// domain whichever way it is encoded. The bundled codec is super-linear in the length of a
|
||||
// label, a 60 KB label of distinct code points took seconds to encode, several times per
|
||||
// address, so it is only handed what could be a domain
|
||||
const MAX_DOMAIN_LENGTH = 253;
|
||||
const MAX_LABEL_LENGTH = 63;
|
||||
// pipeline() needs a callback to not throw, the errors it sees reach the last stream anyway
|
||||
const PIPELINE_NOOP = () => false;
|
||||
// The error a node streaming into an output that was destroyed stops with
|
||||
@@ -77,62 +61,6 @@ function abortedError() {
|
||||
err.code = errors.ESTREAM;
|
||||
return err;
|
||||
}
|
||||
/**
|
||||
* Checks a domain against the DNS length limits, counted in code points per label and in
|
||||
* total. The label separators are the ones the bundled codec splits on.
|
||||
*
|
||||
* @param domain Domain to check
|
||||
* @return true if a label or the domain as a whole is too long to be a valid domain
|
||||
*/
|
||||
function exceedsDomainLimits(domain) {
|
||||
let total = 0;
|
||||
let label = 0;
|
||||
for (const char of domain) {
|
||||
total++;
|
||||
if (char === '.' || char === '。' || char === '.' || char === '。') {
|
||||
label = 0;
|
||||
}
|
||||
else if (++label > MAX_LABEL_LENGTH) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return total > MAX_DOMAIN_LENGTH;
|
||||
}
|
||||
/**
|
||||
* Encodes a domain the way browsers, the WHATWG URL Standard and DNS facing resolvers do,
|
||||
* which is with UTS-46 mapping applied before the Punycode step.
|
||||
*
|
||||
* The bundled codec is plain RFC 3492 and maps nothing, so it disagrees with every
|
||||
* conformant parser on any domain holding a mapped or ignored code point. An invisible
|
||||
* U+00AD in 'compa\u00ADny.com' encoded to 'xn--company-pka.com' where a validator reads
|
||||
* 'company.com', which let an allow-listed domain be checked and a different one mailed.
|
||||
*
|
||||
* Anything the URL parser does not accept as a hostname, an address literal such as
|
||||
* '[127.0.0.1]' included, comes back empty and falls through to the bundled codec, which
|
||||
* leaves those as they were supplied.
|
||||
*
|
||||
* @param domain Domain to encode, already lowercased by the caller
|
||||
* @param toUnicode Return the U-label form instead of the A-label form
|
||||
* @return Encoded domain
|
||||
*/
|
||||
function normalizeDomain(domain, toUnicode) {
|
||||
// domainToASCII and domainToUnicode landed in Node 7, the bundled codec covers Node 6
|
||||
if (typeof urlModule.domainToASCII === 'function' && typeof urlModule.domainToUnicode === 'function' && !URL_PARSER_UNSAFE.test(domain)) {
|
||||
// The U-label form is decoded from the A-label form rather than from the input:
|
||||
// Deno's domainToASCII returns an empty string for a label it cannot decode, while
|
||||
// its domainToUnicode returns the label with U+FFFD in place of the bad part
|
||||
const ascii = urlModule.domainToASCII(domain);
|
||||
const mapped = ascii && toUnicode ? urlModule.domainToUnicode(ascii) : ascii;
|
||||
if (mapped) {
|
||||
return mapped;
|
||||
}
|
||||
}
|
||||
if (exceedsDomainLimits(domain)) {
|
||||
// too long to be a domain whichever way it is encoded, keep it as supplied
|
||||
return domain;
|
||||
}
|
||||
return toUnicode ? punycode.toUnicode(domain) : punycode.toASCII(domain);
|
||||
}
|
||||
/**
|
||||
* Removes the characters that must never reach a multipart delimiter line.
|
||||
*
|
||||
@@ -616,15 +544,18 @@ class MimeNode {
|
||||
return;
|
||||
}
|
||||
switch (header.key) {
|
||||
// The comments of a MIME header are not part of its value and are dropped, so a
|
||||
// caller supplied 'boundary=b (comment)' is the boundary b it names, and the
|
||||
// header goes out without the comment
|
||||
case 'Content-Disposition':
|
||||
structured = mimeFuncs.parseHeaderValue(value);
|
||||
structured = mimeFuncs.parseHeaderValue(value, { stripComments: true });
|
||||
if (this.filename) {
|
||||
structured.params.filename = this.filename;
|
||||
}
|
||||
value = mimeFuncs.buildHeaderValue(structured);
|
||||
break;
|
||||
case 'Content-Type':
|
||||
structured = mimeFuncs.parseHeaderValue(value);
|
||||
structured = mimeFuncs.parseHeaderValue(value, { stripComments: true });
|
||||
// the type token decides multipart and charset below, so clean it before
|
||||
// those run and not just on the way out, otherwise a control char makes
|
||||
// the checks miss and the header ends up claiming a type it is not set up for
|
||||
@@ -1261,7 +1192,7 @@ class MimeNode {
|
||||
.replace(/[\s\x00-\x20\x7f:]/g, '')
|
||||
.toLowerCase()
|
||||
// use uppercase words, except MIME
|
||||
.replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi, c => c.toUpperCase())
|
||||
.replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^OTP(?=-Token$)|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi, c => c.toUpperCase())
|
||||
// special case
|
||||
.replace(/^Content-Features$/i, 'Content-features');
|
||||
return key;
|
||||
@@ -1333,7 +1264,7 @@ class MimeNode {
|
||||
// values enclosed in <>
|
||||
case 'Message-ID':
|
||||
case 'In-Reply-To':
|
||||
case 'Content-Id':
|
||||
case 'Content-ID':
|
||||
// a msg-id is structured, so an encoded word inside the angle brackets would
|
||||
// be read as literal text. drop the characters that can not appear in a header
|
||||
// at all, but leave HT alone, it separates the ids of a multi id value
|
||||
@@ -1348,6 +1279,14 @@ class MimeNode {
|
||||
value = value + '>';
|
||||
}
|
||||
return value;
|
||||
// a structured field (RFC 9651) that can not be mime encoded, an encoded word would
|
||||
// turn its quoted strings into text that no structured field parser reads. Only
|
||||
// the characters that can not appear in a header at all are removed
|
||||
case 'OTP-Token':
|
||||
return (value || '')
|
||||
.toString()
|
||||
.replace(/\r?\n|\r/g, ' ')
|
||||
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
||||
// space separated list of values enclosed in <>
|
||||
case 'References': {
|
||||
const ids = [];
|
||||
@@ -1489,7 +1428,7 @@ class MimeNode {
|
||||
// symmetry on both sides of the '@' rather than being encoded to an A-label
|
||||
const smtputf8 = /[\x80-\uFFFF]/.test(user);
|
||||
try {
|
||||
encodedDomain = normalizeDomain(domain.toLowerCase(), smtputf8);
|
||||
encodedDomain = shared.normalizeDomain(domain, smtputf8);
|
||||
}
|
||||
catch (_err) {
|
||||
// keep domain as supplied
|
||||
|
||||
+1
-1
@@ -111,7 +111,7 @@ export type { Mail, MailDefaults, SentMessageInfo, Transport, TransportOptions }
|
||||
export type { SendMailOptions, Transporter } from './mailer/index.js';
|
||||
export type { NodemailerError, ErrorCode } from './errors.js';
|
||||
export type { MailMessage, MailMessageData, PluginFunction, VerifyCallback } from './mailer/index.js';
|
||||
export type { MailComposerOptions, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerIcalEvent as IcalAttachment, MailComposerListHeaders as ListHeaders } from './mail-composer/index.js';
|
||||
export type { MailComposerOptions, MailComposerAttachment as Attachment, MailComposerAlternative as AttachmentLike, MailComposerIcalEvent as IcalAttachment, MailComposerListHeaders as ListHeaders, MailComposerOtp as Otp } from './mail-composer/index.js';
|
||||
export type { MimeNodeAddress as Address, MimeNodeHeaders as Headers } from './mime-node/index.js';
|
||||
export type { SMTPConnectionOptions, SMTPConnectionAuth, SMTPEnvelope, SMTPEnvelopeDsn } from './smtp-connection/index.js';
|
||||
export type { DKIMOptions } from './dkim/index.js';
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
export declare const name = "nodemailer";
|
||||
export declare const version = "10.2.0";
|
||||
export declare const version = "10.6.1";
|
||||
export declare const homepage = "https://nodemailer.com/";
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
// Generated by scripts/build.js from package.json. Do not edit by hand.
|
||||
export const name = 'nodemailer';
|
||||
export const version = '10.2.0';
|
||||
export const version = '10.6.1';
|
||||
export const homepage = 'https://nodemailer.com/';
|
||||
+23
@@ -289,3 +289,26 @@ export declare function unreadableStreamError(stream: Readable): NodemailerError
|
||||
* @param callback Callback function with (err, value)
|
||||
*/
|
||||
export declare function resolveStream(stream: Readable, callback: (err: Error | null, value?: Buffer) => void): void;
|
||||
/**
|
||||
* Encodes a domain the way browsers, the WHATWG URL Standard and DNS facing resolvers do,
|
||||
* which is with UTS-46 mapping applied before the Punycode step.
|
||||
*
|
||||
* The bundled codec is plain RFC 3492 and maps nothing, so it disagrees with every
|
||||
* conformant parser on any domain holding a mapped or ignored code point. An invisible
|
||||
* U+00AD in 'compa\u00ADny.com' encoded to 'xn--company-pka.com' where a validator reads
|
||||
* 'company.com', which let an allow-listed domain be checked and a different one mailed.
|
||||
*
|
||||
* Anything the URL parser does not accept as a hostname, an address literal such as
|
||||
* '[127.0.0.1]' included, comes back empty and falls through to the bundled codec, which
|
||||
* leaves those as they were supplied apart from lowercasing them.
|
||||
*
|
||||
* The mapper gets the domain as supplied, since UTS-46 does its own case mapping and
|
||||
* toLowerCase() differs from it: it turns U+1E9E into U+00DF where Node 20 and 22 map it
|
||||
* to 'ss', and a word-final U+03A3 into U+03C2 where UTS-46 gives U+03C3. Lowercasing
|
||||
* first sent 'user@stra\u1E9Ee.de', which a validator reads as strasse.de, to xn--strae-oqa.de.
|
||||
*
|
||||
* @param domain Domain to encode
|
||||
* @param toUnicode Return the U-label form instead of the A-label form
|
||||
* @return Encoded domain
|
||||
*/
|
||||
export declare function normalizeDomain(domain: string, toUnicode: boolean): string;
|
||||
+78
@@ -8,6 +8,8 @@ import { isProtoKey, copyOwnKeys } from './objects.js';
|
||||
import dns from 'node:dns';
|
||||
import net from 'node:net';
|
||||
import os from 'node:os';
|
||||
import urlModule from 'node:url';
|
||||
import * as punycode from '../punycode/index.js';
|
||||
import { finished } from 'node:stream';
|
||||
// re-exported for the callers that already depend on this module, see ./objects
|
||||
export { isProtoKey, copyOwnKeys };
|
||||
@@ -717,3 +719,79 @@ function createDefaultLogger(levels) {
|
||||
});
|
||||
return logger;
|
||||
}
|
||||
// domainToASCII and domainToUnicode are WHATWG host parsers rather than plain IDNA
|
||||
// mappers, so they do more than map: they cut the host at '/', '\\', '?' and '#', drop C0
|
||||
// controls, and percent-decode. Handing them 'evil.example/mail.corp.example' returns the
|
||||
// deliverable 'evil.example', which would turn a value the bundled codec leaves as
|
||||
// unroutable garbage into mail for a domain the sender never named. None of these
|
||||
// characters are legal in a domain, so keep them away from the mapper.
|
||||
const URL_PARSER_UNSAFE = /[/\\?#%\x00-\x20\x7F]/;
|
||||
// RFC 1035 bounds a label at 63 octets and a domain at 253. An A-label is never shorter than
|
||||
// the code points it encodes, so anything past these bounds could not have become a valid
|
||||
// domain whichever way it is encoded. The bundled codec is super-linear in the length of a
|
||||
// label, a 60 KB label of distinct code points took seconds to encode, several times per
|
||||
// address, so it is only handed what could be a domain
|
||||
const MAX_DOMAIN_LENGTH = 253;
|
||||
const MAX_LABEL_LENGTH = 63;
|
||||
/**
|
||||
* Checks a domain against the DNS length limits, counted in code points per label and in
|
||||
* total. The label separators are the ones the bundled codec splits on.
|
||||
*
|
||||
* @param domain Domain to check
|
||||
* @return true if a label or the domain as a whole is too long to be a valid domain
|
||||
*/
|
||||
function exceedsDomainLimits(domain) {
|
||||
let total = 0;
|
||||
let label = 0;
|
||||
for (const char of domain) {
|
||||
total++;
|
||||
if (char === '.' || char === '。' || char === '.' || char === '。') {
|
||||
label = 0;
|
||||
}
|
||||
else if (++label > MAX_LABEL_LENGTH) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return total > MAX_DOMAIN_LENGTH;
|
||||
}
|
||||
/**
|
||||
* Encodes a domain the way browsers, the WHATWG URL Standard and DNS facing resolvers do,
|
||||
* which is with UTS-46 mapping applied before the Punycode step.
|
||||
*
|
||||
* The bundled codec is plain RFC 3492 and maps nothing, so it disagrees with every
|
||||
* conformant parser on any domain holding a mapped or ignored code point. An invisible
|
||||
* U+00AD in 'compa\u00ADny.com' encoded to 'xn--company-pka.com' where a validator reads
|
||||
* 'company.com', which let an allow-listed domain be checked and a different one mailed.
|
||||
*
|
||||
* Anything the URL parser does not accept as a hostname, an address literal such as
|
||||
* '[127.0.0.1]' included, comes back empty and falls through to the bundled codec, which
|
||||
* leaves those as they were supplied apart from lowercasing them.
|
||||
*
|
||||
* The mapper gets the domain as supplied, since UTS-46 does its own case mapping and
|
||||
* toLowerCase() differs from it: it turns U+1E9E into U+00DF where Node 20 and 22 map it
|
||||
* to 'ss', and a word-final U+03A3 into U+03C2 where UTS-46 gives U+03C3. Lowercasing
|
||||
* first sent 'user@stra\u1E9Ee.de', which a validator reads as strasse.de, to xn--strae-oqa.de.
|
||||
*
|
||||
* @param domain Domain to encode
|
||||
* @param toUnicode Return the U-label form instead of the A-label form
|
||||
* @return Encoded domain
|
||||
*/
|
||||
export function normalizeDomain(domain, toUnicode) {
|
||||
// domainToASCII and domainToUnicode landed in Node 7, the bundled codec covers Node 6
|
||||
if (typeof urlModule.domainToASCII === 'function' && typeof urlModule.domainToUnicode === 'function' && !URL_PARSER_UNSAFE.test(domain)) {
|
||||
// The U-label form is decoded from the A-label form rather than from the input:
|
||||
// Deno's domainToASCII returns an empty string for a label it cannot decode, while
|
||||
// its domainToUnicode returns the label with U+FFFD in place of the bad part
|
||||
const ascii = urlModule.domainToASCII(domain);
|
||||
const mapped = ascii && toUnicode ? urlModule.domainToUnicode(ascii) : ascii;
|
||||
if (mapped) {
|
||||
return mapped;
|
||||
}
|
||||
}
|
||||
domain = domain.toLowerCase();
|
||||
if (exceedsDomainLimits(domain)) {
|
||||
// too long to be a domain whichever way it is encoded, keep it as supplied
|
||||
return domain;
|
||||
}
|
||||
return toUnicode ? punycode.toUnicode(domain) : punycode.toASCII(domain);
|
||||
}
|
||||
+3
@@ -42,6 +42,8 @@ export interface SMTPConnectionOptions {
|
||||
greetingTimeout?: number | undefined;
|
||||
/** Time of inactivity in ms until the connection is closed, defaults to 10 minutes */
|
||||
socketTimeout?: number | undefined;
|
||||
/** 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 */
|
||||
socketCloseTimeout?: number | undefined;
|
||||
/** Largest single server response to accept in bytes, defaults to 1 MB */
|
||||
maxResponseSize?: number | undefined;
|
||||
/** 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;
|
||||
* * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 30 seconds)
|
||||
* * **connectionTimeout** - how many milliseconds to wait for the connection to establish (defaults to 2 minutes)
|
||||
* * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 10 minutes)
|
||||
* * **socketCloseTimeout** - Time in ms to wait for the peer to close after ending the socket (defaults to 5 seconds, 0 destroys immediately)
|
||||
* * **maxResponseSize** - Largest single server response to accept in bytes (defaults to 1 MB)
|
||||
* * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds)
|
||||
* * **lmtp** - if true, uses LMTP instead of SMTP protocol
|
||||
|
||||
+17
-3
@@ -107,6 +107,7 @@ function maskAuthCommand(cmd) {
|
||||
* * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 30 seconds)
|
||||
* * **connectionTimeout** - how many milliseconds to wait for the connection to establish (defaults to 2 minutes)
|
||||
* * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 10 minutes)
|
||||
* * **socketCloseTimeout** - Time in ms to wait for the peer to close after ending the socket (defaults to 5 seconds, 0 destroys immediately)
|
||||
* * **maxResponseSize** - Largest single server response to accept in bytes (defaults to 1 MB)
|
||||
* * **dnsTimeout** - Time to wait in ms for the DNS requests to be resolved (defaults to 30 seconds)
|
||||
* * **lmtp** - if true, uses LMTP instead of SMTP protocol
|
||||
@@ -249,6 +250,9 @@ class SMTPConnection extends EventEmitter {
|
||||
// socket object is set up but not yet connected
|
||||
this._socket = this.options.socket;
|
||||
return this._resolveAndConnect(opts, _resolved => {
|
||||
if (this._destroyed || this._closing) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this._socket.connect(this.port, this.host, () => {
|
||||
// a `secure` connection over a caller-provided socket must still
|
||||
@@ -427,11 +431,18 @@ class SMTPConnection extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
this._closing = true;
|
||||
const closeMethod = this.stage === 'init' ? 'destroy' : 'end';
|
||||
// anything but a non-negative finite number keeps the default grace period
|
||||
const configuredCloseTimeout = this.options.socketCloseTimeout;
|
||||
const socketCloseTimeout = typeof configuredCloseTimeout === 'number' && Number.isFinite(configuredCloseTimeout) && configuredCloseTimeout >= 0
|
||||
? configuredCloseTimeout
|
||||
: CLOSE_TIMEOUT;
|
||||
const closeMethod = this.stage === 'init' || socketCloseTimeout === 0 ? 'destroy' : 'end';
|
||||
this.logger.debug({
|
||||
tnx: 'smtp'
|
||||
}, 'Closing connection to the server using "%s"', closeMethod);
|
||||
const socket = (this._socket && this._socket.socket) || this._socket;
|
||||
// after STARTTLS this is the TLS socket, tear that one down and not the plain socket it
|
||||
// wraps (Node 27 exposes the wrapped socket as `.socket`)
|
||||
const socket = this._socket;
|
||||
// Detach any in-flight DATA stream from the socket so the source stream
|
||||
// can be garbage-collected once the socket is gone.
|
||||
if (this._currentDataStream) {
|
||||
@@ -473,7 +484,7 @@ class SMTPConnection extends EventEmitter {
|
||||
if (closeMethod === 'end') {
|
||||
// end() only closes our side, a server that never closes its own would keep
|
||||
// the socket, and the process with it, around for good
|
||||
const closeTimer = setTimeout(() => socket.destroy(), CLOSE_TIMEOUT);
|
||||
const closeTimer = setTimeout(() => socket.destroy(), socketCloseTimeout);
|
||||
if (typeof closeTimer.unref === 'function') {
|
||||
closeTimer.unref();
|
||||
}
|
||||
@@ -1039,6 +1050,9 @@ class SMTPConnection extends EventEmitter {
|
||||
* @internal
|
||||
*/
|
||||
_upgradeConnection(callback) {
|
||||
if (this._destroyed || this._closing) {
|
||||
return;
|
||||
}
|
||||
// RFC 3207 section 6: the client MUST discard any knowledge obtained from
|
||||
// the server that was not received over the TLS-protected session. Drop any
|
||||
// buffered input received before the handshake so a man-in-the-middle cannot
|
||||
|
||||
+10
-3
@@ -76,6 +76,7 @@ export interface SMTPPoolRateLimit {
|
||||
* @param options SMTP Connection options
|
||||
*/
|
||||
declare class SMTPPool extends EventEmitter {
|
||||
readonly supportsAbortSignal = true;
|
||||
options: SMTPPoolResolvedOptions;
|
||||
logger: shared.Logger;
|
||||
name: string;
|
||||
@@ -102,10 +103,16 @@ declare class SMTPPool extends EventEmitter {
|
||||
*/
|
||||
send(mail: MailMessage<SMTPPoolSentMessageInfo>, callback: SMTPPoolSendCallback): boolean;
|
||||
/**
|
||||
* Closes all connections in the pool. If there is a message being sent, the connection
|
||||
* is closed later
|
||||
* Closes the pool. Idle connections are closed at once and a connection in the middle of a
|
||||
* delivery finishes it first, unless `force` is set: then it is closed too and its message
|
||||
* fails. `force` is for a caller that has given up on a delivery, such as one a server is
|
||||
* stalling by trickling its replies, which no socket timeout notices.
|
||||
*
|
||||
* @param options.force - Also close connections that are delivering a message
|
||||
*/
|
||||
close(): void;
|
||||
close(options?: {
|
||||
force?: boolean;
|
||||
}): void;
|
||||
/**
|
||||
* Returns true if there are free slots in the queue
|
||||
*/
|
||||
|
||||
+70
-12
@@ -18,6 +18,7 @@ const REQUEUE_MAX_DELAY = 2000;
|
||||
class SMTPPool extends EventEmitter {
|
||||
constructor(options) {
|
||||
super();
|
||||
this.supportsAbortSignal = true;
|
||||
options = options || {};
|
||||
if (typeof options === 'string') {
|
||||
options = {
|
||||
@@ -96,20 +97,33 @@ class SMTPPool extends EventEmitter {
|
||||
return false;
|
||||
}
|
||||
// counted until the callback runs, whichever path runs it: delivered, failed, requeued
|
||||
// until it gives up, or drained by close()
|
||||
// until it gives up, aborted, or drained by close()
|
||||
let counted = true;
|
||||
let detachSignal;
|
||||
this._pending++;
|
||||
this._queue.push({
|
||||
const entry = {
|
||||
mail,
|
||||
requeueAttempts: 0,
|
||||
callback: (err, info) => {
|
||||
if (counted) {
|
||||
counted = false;
|
||||
this._pending--;
|
||||
if (!counted) {
|
||||
return;
|
||||
}
|
||||
counted = false;
|
||||
this._pending--;
|
||||
detachSignal?.();
|
||||
entry.resource = undefined;
|
||||
callback(err, info);
|
||||
}
|
||||
});
|
||||
};
|
||||
this._queue.push(entry);
|
||||
const signal = mail.data.signal;
|
||||
if (signal) {
|
||||
// one listener for the original entry, retained across connection-close retries
|
||||
detachSignal = this._watchAbortSignal(entry, signal, () => counted);
|
||||
if (signal.aborted) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (this.idling && this._queue.length >= this.options.maxConnections) {
|
||||
this.idling = false;
|
||||
}
|
||||
@@ -117,10 +131,49 @@ class SMTPPool extends EventEmitter {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Closes all connections in the pool. If there is a message being sent, the connection
|
||||
* is closed later
|
||||
* Fails a queued or assigned entry when its signal aborts: removes it from the queue, or
|
||||
* closes the connection delivering it, so other deliveries in the pool can continue.
|
||||
* Returns a function that removes the listener.
|
||||
* @internal
|
||||
*/
|
||||
close() {
|
||||
_watchAbortSignal(entry, signal, isPending) {
|
||||
const onAbort = () => {
|
||||
if (!isPending()) {
|
||||
return;
|
||||
}
|
||||
const index = this._queue.indexOf(entry);
|
||||
if (index !== -1) {
|
||||
this._queue.splice(index, 1);
|
||||
}
|
||||
const resource = entry.resource;
|
||||
if (resource && resource.queueEntry === entry) {
|
||||
// Detach before closing: the close handler must not retry this message.
|
||||
resource.queueEntry = false;
|
||||
resource.close();
|
||||
}
|
||||
try {
|
||||
entry.callback(errors.createAbortError(signal));
|
||||
}
|
||||
finally {
|
||||
// Removing a queued entry can make the pool idle again.
|
||||
setImmediate(() => this._processMessages());
|
||||
}
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
if (signal.aborted) {
|
||||
setImmediate(onAbort);
|
||||
}
|
||||
return () => signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
/**
|
||||
* Closes the pool. Idle connections are closed at once and a connection in the middle of a
|
||||
* delivery finishes it first, unless `force` is set: then it is closed too and its message
|
||||
* fails. `force` is for a caller that has given up on a delivery, such as one a server is
|
||||
* stalling by trickling its replies, which no socket timeout notices.
|
||||
*
|
||||
* @param options.force - Also close connections that are delivering a message
|
||||
*/
|
||||
close(options) {
|
||||
let connection;
|
||||
const len = this._connections.length;
|
||||
this._closed = true;
|
||||
@@ -131,9 +184,10 @@ class SMTPPool extends EventEmitter {
|
||||
if (!len && !this._queue.length) {
|
||||
return;
|
||||
}
|
||||
// remove all available connections
|
||||
// remove all available connections, and with `force` the busy ones too
|
||||
const force = !!options?.force;
|
||||
for (let i = len - 1; i >= 0; i--) {
|
||||
if (this._connections[i] && this._connections[i].available) {
|
||||
if (this._connections[i] && (force || this._connections[i].available)) {
|
||||
connection = this._connections[i];
|
||||
connection.close();
|
||||
this.logger.info({
|
||||
@@ -211,6 +265,7 @@ class SMTPPool extends EventEmitter {
|
||||
this.emit('idle');
|
||||
}
|
||||
const entry = (connection.queueEntry = this._queue.shift());
|
||||
entry.resource = connection;
|
||||
entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, '');
|
||||
connection.available = false;
|
||||
this.logger.debug({
|
||||
@@ -318,7 +373,9 @@ class SMTPPool extends EventEmitter {
|
||||
setTimeout(() => {
|
||||
let delay = 0;
|
||||
if (connection.queueEntry) {
|
||||
if (this._shouldRequeuOnConnectionClose(connection.queueEntry)) {
|
||||
// a closed pool (a forced close ends a delivery on purpose) fails the
|
||||
// message rather than queueing it for a retry that would never run
|
||||
if (!this._closed && this._shouldRequeuOnConnectionClose(connection.queueEntry)) {
|
||||
delay = this._requeueEntryOnConnectionClose(connection);
|
||||
}
|
||||
else {
|
||||
@@ -380,6 +437,7 @@ class SMTPPool extends EventEmitter {
|
||||
messageId: connection.queueEntry.messageId,
|
||||
action: 'requeue'
|
||||
}, 'Re-queued message <%s> for #%s. Attempt: #%s', connection.queueEntry.messageId, connection.id, connection.queueEntry.requeueAttempts);
|
||||
connection.queueEntry.resource = undefined;
|
||||
this._queue.unshift(connection.queueEntry);
|
||||
connection.queueEntry = false;
|
||||
return delay;
|
||||
|
||||
+26
-4
@@ -48,6 +48,7 @@ export default class PoolResource extends EventEmitter {
|
||||
}
|
||||
this._connection = false;
|
||||
this._connected = false;
|
||||
this._closed = false;
|
||||
this.messages = 0;
|
||||
this.available = true;
|
||||
this._failed = false;
|
||||
@@ -75,6 +76,10 @@ export default class PoolResource extends EventEmitter {
|
||||
// the proxy handshake, if any, counts against connectionTimeout as well
|
||||
const connectStartedAt = Date.now();
|
||||
this.pool.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
|
||||
if (this._closed) {
|
||||
socketOptions && socketOptions.connection?.destroy();
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
// nothing was connected, so no 'close' event is coming that would free the
|
||||
// slot this resource holds in the pool, report the failure the way a failed
|
||||
@@ -98,7 +103,7 @@ export default class PoolResource extends EventEmitter {
|
||||
this.connection = new SMTPConnection(options);
|
||||
this.connection._connectStartedAt = connectStartedAt;
|
||||
this.connection.on('error', (err) => {
|
||||
if (this._sending) {
|
||||
if (this._closed || this._sending) {
|
||||
// the send callback gets the same error and decides what it means for the message
|
||||
return;
|
||||
}
|
||||
@@ -112,7 +117,7 @@ export default class PoolResource extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
this._fail(err);
|
||||
if (returned) {
|
||||
if (returned || this._closed) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
@@ -123,7 +128,7 @@ export default class PoolResource extends EventEmitter {
|
||||
returned = true;
|
||||
});
|
||||
this.connection.connect(err => {
|
||||
if (returned) {
|
||||
if (returned || this._closed) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
@@ -134,7 +139,7 @@ export default class PoolResource extends EventEmitter {
|
||||
}
|
||||
if (this.auth && (this.connection.allowsAuth || options.forceAuth)) {
|
||||
this.connection.login(this.auth, err => {
|
||||
if (returned) {
|
||||
if (returned || this._closed) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
@@ -162,6 +167,9 @@ export default class PoolResource extends EventEmitter {
|
||||
* @param callback Callback function
|
||||
*/
|
||||
send(mail, callback) {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
if (!this._connected) {
|
||||
return this.connect(err => {
|
||||
if (err) {
|
||||
@@ -193,6 +201,9 @@ export default class PoolResource extends EventEmitter {
|
||||
const reused = this.messages > 0;
|
||||
const messageStream = mail.message.createReadStream();
|
||||
this.connection.send(envelope, messageStream, (err, info) => {
|
||||
if (mail.data.signal?.aborted) {
|
||||
return;
|
||||
}
|
||||
this._sending = false;
|
||||
this.messages++;
|
||||
if (err) {
|
||||
@@ -239,6 +250,9 @@ export default class PoolResource extends EventEmitter {
|
||||
* @internal
|
||||
*/
|
||||
_release() {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
if (this.messages >= this.options.maxMessages) {
|
||||
const err = new Error('Resource exhausted');
|
||||
err.code = errors.EMAXLIMIT;
|
||||
@@ -247,6 +261,9 @@ export default class PoolResource extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
this.pool._checkRateLimit(() => {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
this.available = true;
|
||||
this._startIdleTimer();
|
||||
this.emit('available');
|
||||
@@ -289,6 +306,11 @@ export default class PoolResource extends EventEmitter {
|
||||
* Closes the connection
|
||||
*/
|
||||
close() {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
this._closed = true;
|
||||
this.available = false;
|
||||
this._connected = false;
|
||||
this._stopIdleTimer();
|
||||
if (this.auth && this.auth.oauth2) {
|
||||
|
||||
+1
@@ -93,6 +93,7 @@ export type SMTPTransportSendCallback = ResultCallback<SMTPSentMessageInfo>;
|
||||
* @param options Connection options
|
||||
*/
|
||||
declare class SMTPTransport extends EventEmitter {
|
||||
readonly supportsAbortSignal = true;
|
||||
options: SMTPTransportOptions;
|
||||
logger: shared.Logger;
|
||||
name: string;
|
||||
|
||||
+47
-35
@@ -21,6 +21,7 @@ const MESSAGE_AUTH_KEYS = ['type', 'user', 'pass', 'accessToken', 'refreshToken'
|
||||
class SMTPTransport extends EventEmitter {
|
||||
constructor(options) {
|
||||
super();
|
||||
this.supportsAbortSignal = true;
|
||||
options = options || {};
|
||||
if (typeof options === 'string') {
|
||||
options = {
|
||||
@@ -115,13 +116,46 @@ class SMTPTransport extends EventEmitter {
|
||||
* @param callback Callback function
|
||||
*/
|
||||
send(mail, callback) {
|
||||
const signal = mail.data.signal;
|
||||
let returned = false;
|
||||
let connection;
|
||||
let perCallAuth;
|
||||
const cleanupPerCallAuth = () => {
|
||||
if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
|
||||
perCallAuth.oauth2.removeAllListeners();
|
||||
}
|
||||
perCallAuth = null;
|
||||
};
|
||||
const finish = (err, info) => {
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
cleanupPerCallAuth();
|
||||
connection?.close();
|
||||
callback(err, info);
|
||||
};
|
||||
function onAbort() {
|
||||
finish(errors.createAbortError(signal));
|
||||
}
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
if (signal.aborted) {
|
||||
setImmediate(onAbort);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// the proxy handshake, if any, counts against connectionTimeout as well
|
||||
const connectStartedAt = Date.now();
|
||||
this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
|
||||
if (returned) {
|
||||
socketOptions && socketOptions.connection?.destroy();
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
let returned = false;
|
||||
let options = this.options;
|
||||
if (socketOptions && socketOptions.connection) {
|
||||
this.logger.info({
|
||||
@@ -135,24 +169,9 @@ class SMTPTransport extends EventEmitter {
|
||||
// only copy options if we need to modify it
|
||||
options = Object.assign(shared.assign(false, options), socketOptions);
|
||||
}
|
||||
const connection = new SMTPConnection(options);
|
||||
connection._connectStartedAt = connectStartedAt;
|
||||
let perCallAuth;
|
||||
const cleanupPerCallAuth = () => {
|
||||
if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
|
||||
perCallAuth.oauth2.removeAllListeners();
|
||||
}
|
||||
perCallAuth = null;
|
||||
};
|
||||
connection.once('error', err => {
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
cleanupPerCallAuth();
|
||||
connection.close();
|
||||
return callback(err);
|
||||
});
|
||||
const smtp = (connection = new SMTPConnection(options));
|
||||
smtp._connectStartedAt = connectStartedAt;
|
||||
smtp.once('error', err => finish(err));
|
||||
const sendMessage = () => {
|
||||
const envelope = mail.message.getEnvelope();
|
||||
const messageId = mail.message.messageId();
|
||||
@@ -171,20 +190,17 @@ class SMTPTransport extends EventEmitter {
|
||||
tnx: 'send',
|
||||
messageId
|
||||
}, 'Sending message %s to <%s>', messageId, recipients.join(', '));
|
||||
connection.send(envelope, mail.message.createReadStream(), (err, info) => {
|
||||
smtp.send(envelope, mail.message.createReadStream(), (err, info) => {
|
||||
if (returned) {
|
||||
// the connection error handler has already reported this send
|
||||
return;
|
||||
}
|
||||
returned = true;
|
||||
cleanupPerCallAuth();
|
||||
connection.close();
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
err,
|
||||
tnx: 'send'
|
||||
}, 'Send error for %s: %s', messageId, err.message);
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
info.envelope = {
|
||||
from: envelope.from,
|
||||
@@ -192,7 +208,7 @@ class SMTPTransport extends EventEmitter {
|
||||
};
|
||||
info.messageId = messageId;
|
||||
try {
|
||||
return callback(null, info);
|
||||
return finish(null, info);
|
||||
}
|
||||
catch (E) {
|
||||
this.logger.error({
|
||||
@@ -202,27 +218,23 @@ class SMTPTransport extends EventEmitter {
|
||||
}
|
||||
});
|
||||
};
|
||||
connection.connect(err => {
|
||||
smtp.connect(err => {
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
// the server closed the connection before the greeting
|
||||
returned = true;
|
||||
connection.close();
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
perCallAuth = this.getAuth(mail.data.auth);
|
||||
if (perCallAuth && (connection.allowsAuth || options.forceAuth)) {
|
||||
connection.login(perCallAuth, err => {
|
||||
if (perCallAuth && (smtp.allowsAuth || options.forceAuth)) {
|
||||
smtp.login(perCallAuth, err => {
|
||||
cleanupPerCallAuth();
|
||||
if (returned) {
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
returned = true;
|
||||
connection.close();
|
||||
return callback(err);
|
||||
return finish(err);
|
||||
}
|
||||
sendMessage();
|
||||
});
|
||||
|
||||
+20
@@ -205,6 +205,13 @@ export const services = {
|
||||
"host": "smtp.europe.secureserver.net",
|
||||
"port": 25
|
||||
},
|
||||
"Groundmail": {
|
||||
"description": "Groundmail",
|
||||
"host": "smtp.groundmail.dev",
|
||||
"port": 587,
|
||||
"secure": false,
|
||||
"requireTLS": true
|
||||
},
|
||||
"hot.ee": {
|
||||
"description": "Hot.ee (Estonian email provider)",
|
||||
"host": "mail.hot.ee"
|
||||
@@ -453,6 +460,12 @@ export const services = {
|
||||
"host": "smtp-relay.brevo.com",
|
||||
"port": 587
|
||||
},
|
||||
"Sendora": {
|
||||
"description": "Sendora",
|
||||
"host": "smtp.sendora.se",
|
||||
"port": 465,
|
||||
"secure": true
|
||||
},
|
||||
"SendPulse": {
|
||||
"description": "SendPulse",
|
||||
"host": "smtp-pulse.com",
|
||||
@@ -599,6 +612,13 @@ export const services = {
|
||||
"host": "mail.smtp2go.com",
|
||||
"port": 2525
|
||||
},
|
||||
"SpacePost": {
|
||||
"description": "SpacePost",
|
||||
"host": "smtp.spacepost.dev",
|
||||
"port": 25976,
|
||||
"secure": false,
|
||||
"requireTLS": true
|
||||
},
|
||||
"Sparkpost": {
|
||||
"description": "SparkPost",
|
||||
"aliases": [
|
||||
|
||||
+23
@@ -180,6 +180,14 @@
|
||||
"port": 25
|
||||
},
|
||||
|
||||
"Groundmail": {
|
||||
"description": "Groundmail",
|
||||
"host": "smtp.groundmail.dev",
|
||||
"port": 587,
|
||||
"secure": false,
|
||||
"requireTLS": true
|
||||
},
|
||||
|
||||
"hot.ee": {
|
||||
"description": "Hot.ee (Estonian email provider)",
|
||||
"host": "mail.hot.ee"
|
||||
@@ -415,6 +423,13 @@
|
||||
"port": 587
|
||||
},
|
||||
|
||||
"Sendora": {
|
||||
"description": "Sendora",
|
||||
"host": "smtp.sendora.se",
|
||||
"port": 465,
|
||||
"secure": true
|
||||
},
|
||||
|
||||
"SendPulse": {
|
||||
"description": "SendPulse",
|
||||
"host": "smtp-pulse.com",
|
||||
@@ -577,6 +592,14 @@
|
||||
"port": 2525
|
||||
},
|
||||
|
||||
"SpacePost": {
|
||||
"description": "SpacePost",
|
||||
"host": "smtp.spacepost.dev",
|
||||
"port": 25976,
|
||||
"secure": false,
|
||||
"requireTLS": true
|
||||
},
|
||||
|
||||
"Sparkpost": {
|
||||
"description": "SparkPost",
|
||||
"aliases": ["SparkPost", "SparkPost Mail"],
|
||||
|
||||
+16
-11
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nodemailer",
|
||||
"version": "10.2.0",
|
||||
"version": "10.6.1",
|
||||
"description": "Easy as cake e-mail sending from your Node.js applications",
|
||||
"type": "module",
|
||||
"main": "./dist/cjs/nodemailer.js",
|
||||
@@ -132,6 +132,7 @@
|
||||
"test:cjs": "NODE_OPTIONS=--no-experimental-require-module node test/package/cjs-smoke.cjs",
|
||||
"pretest:bun": "npm run build",
|
||||
"test:bun": "bun test --timeout 60000 $(find ./test \\( -name '*-test.ts' -o -name '*.test.ts' \\))",
|
||||
"fuzz:addressparser": "node --import tsx scripts/fuzz-addressparser.js",
|
||||
"format": "prettier --write \"**/*.{js,cjs,ts,json,md}\"",
|
||||
"format:check": "prettier --check \"**/*.{js,cjs,ts,json,md}\"",
|
||||
"lint": "eslint . && npm run typecheck",
|
||||
@@ -153,26 +154,30 @@
|
||||
},
|
||||
"homepage": "https://nodemailer.com/",
|
||||
"devDependencies": {
|
||||
"@aws-sdk/client-sesv2": "3.1151.0",
|
||||
"@aws-sdk/client-sesv2": "3.1173.0",
|
||||
"@types/node": "20.19.43",
|
||||
"bunyan": "1.8.15",
|
||||
"c8": "12.0.0",
|
||||
"eslint": "10.13.0",
|
||||
"eslint": "10.15.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"globals": "17.13.0",
|
||||
"libbase64": "1.3.2",
|
||||
"libmime": "5.4.7",
|
||||
"libqp": "2.1.2",
|
||||
"mailauth": "7.3.0",
|
||||
"prettier": "3.9.10",
|
||||
"globals": "17.14.0",
|
||||
"libbase64": "1.4.1",
|
||||
"libmime": "5.6.5",
|
||||
"libqp": "3.0.2",
|
||||
"mailauth": "8.1.0",
|
||||
"prettier": "3.10.1",
|
||||
"proxy": "1.0.2",
|
||||
"proxy-test-server": "1.0.0",
|
||||
"smtp-server": "3.19.21",
|
||||
"smtp-server": "3.21.6",
|
||||
"tsx": "4.23.15",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.71.2"
|
||||
"typescript-eslint": "8.73.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"overrides": {
|
||||
"glob": "14.0.6",
|
||||
"minimatch": "11.0.8"
|
||||
}
|
||||
}
|
||||
+2
@@ -29,6 +29,8 @@ Returns: `Client`
|
||||
* **webSocket** `WebSocketOptions` (optional) - WebSocket-specific configuration options.
|
||||
* **maxFragments** `number` (optional) - Default: `131072` - Maximum number of fragments in a message. Set to 0 to disable the limit.
|
||||
* **maxPayloadSize** `number` (optional) - Default: `134217728` (128 MB) - Maximum allowed payload size in bytes for WebSocket messages. Applied to uncompressed messages, compressed frame payloads, and decompressed (permessage-deflate) messages. Set to 0 to disable the limit.
|
||||
* **eventSource** `EventSourceOptions` (optional) - EventSource-specific configuration options.
|
||||
* **maxEventSize** `number` (optional) - The maximum total bytes of data and metadata field values retained for a pending EventSource event. Each unfinished line is separately limited to this value plus seven syntax bytes. The number of `data:` lines per event and input chunks buffered for an unfinished line are each limited to `min(131072, max(1024, floor(maxEventSize / 128)))` to bound object overhead. Set to `0` to disable these limits. Default: `buffer.kStringMaxLength`.
|
||||
* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections.
|
||||
* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`.
|
||||
* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body.
|
||||
|
||||
+6
-2
@@ -23,7 +23,7 @@ function defaultFactory (origin, opts) {
|
||||
}
|
||||
|
||||
class Agent extends DispatcherBase {
|
||||
constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
|
||||
constructor ({ factory = defaultFactory, maxRedirections = 0, connect, tls, ...options } = {}) {
|
||||
if (typeof factory !== 'function') {
|
||||
throw new InvalidArgumentError('factory must be a function.')
|
||||
}
|
||||
@@ -42,11 +42,15 @@ class Agent extends DispatcherBase {
|
||||
connect = { ...connect }
|
||||
}
|
||||
|
||||
if (tls && typeof tls !== 'function') {
|
||||
tls = { ...tls }
|
||||
}
|
||||
|
||||
this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent)
|
||||
? options.interceptors.Agent
|
||||
: [createRedirectInterceptor({ maxRedirections })]
|
||||
|
||||
this[kOptions] = { ...util.deepClone(options), connect }
|
||||
this[kOptions] = { ...util.deepClone(options), connect, tls }
|
||||
this[kOptions].interceptors = options.interceptors
|
||||
? { ...options.interceptors }
|
||||
: undefined
|
||||
|
||||
-2
@@ -727,8 +727,6 @@ async function connectH1 (client, socket) {
|
||||
socket[kParser] = new Parser(client, socket, llhttpInstance)
|
||||
|
||||
addListener(socket, 'error', function (err) {
|
||||
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
||||
|
||||
const parser = this[kParser]
|
||||
|
||||
// On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
|
||||
|
||||
-4
@@ -136,8 +136,6 @@ async function connectH2 (client, socket) {
|
||||
socket[kHTTP2Session] = session
|
||||
|
||||
util.addListener(socket, 'error', function (err) {
|
||||
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
||||
|
||||
this[kError] = err
|
||||
|
||||
this[kClient][kOnError](err)
|
||||
@@ -211,8 +209,6 @@ function resumeH2 (client) {
|
||||
}
|
||||
|
||||
function onHttp2SessionError (err) {
|
||||
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
||||
|
||||
this[kSocket][kError] = err
|
||||
this[kClient][kOnError](err)
|
||||
}
|
||||
|
||||
+3
-2
@@ -107,9 +107,10 @@ class Client extends DispatcherBase {
|
||||
// h2
|
||||
maxConcurrentStreams,
|
||||
allowH2,
|
||||
webSocket
|
||||
webSocket,
|
||||
eventSource
|
||||
} = {}) {
|
||||
super({ webSocket })
|
||||
super({ webSocket, eventSource })
|
||||
|
||||
if (keepAlive !== undefined) {
|
||||
throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
|
||||
|
||||
+9
@@ -1,5 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const buffer = require('node:buffer')
|
||||
const Dispatcher = require('./dispatcher')
|
||||
const {
|
||||
ClientDestroyedError,
|
||||
@@ -12,6 +13,7 @@ const kOnDestroyed = Symbol('onDestroyed')
|
||||
const kOnClosed = Symbol('onClosed')
|
||||
const kInterceptedDispatch = Symbol('Intercepted Dispatch')
|
||||
const kWebSocketOptions = Symbol('webSocketOptions')
|
||||
const kEventSourceOptions = Symbol('eventSourceOptions')
|
||||
|
||||
class DispatcherBase extends Dispatcher {
|
||||
constructor (opts) {
|
||||
@@ -22,6 +24,7 @@ class DispatcherBase extends Dispatcher {
|
||||
this[kClosed] = false
|
||||
this[kOnClosed] = []
|
||||
this[kWebSocketOptions] = opts?.webSocket ?? {}
|
||||
this[kEventSourceOptions] = opts?.eventSource ?? {}
|
||||
}
|
||||
|
||||
get webSocketOptions () {
|
||||
@@ -31,6 +34,12 @@ class DispatcherBase extends Dispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
get eventSourceOptions () {
|
||||
return {
|
||||
maxEventSize: this[kEventSourceOptions].maxEventSize ?? buffer.kStringMaxLength
|
||||
}
|
||||
}
|
||||
|
||||
get destroyed () {
|
||||
return this[kDestroyed]
|
||||
}
|
||||
|
||||
+91
-10
@@ -1,4 +1,5 @@
|
||||
'use strict'
|
||||
const buffer = require('node:buffer')
|
||||
const { Transform } = require('node:stream')
|
||||
const { isASCIINumber, isValidLastEventId } = require('./util')
|
||||
|
||||
@@ -23,11 +24,19 @@ const COLON = 0x3A
|
||||
*/
|
||||
const SPACE = 0x20
|
||||
|
||||
const defaultMaxEventSize = buffer.kStringMaxLength
|
||||
|
||||
const DATA = Buffer.from('data')
|
||||
const EVENT = Buffer.from('event')
|
||||
const ID = Buffer.from('id')
|
||||
const RETRY = Buffer.from('retry')
|
||||
|
||||
// Each data field creates a string node, and each unconsumed input chunk keeps
|
||||
// a Buffer wrapper. The absolute ceiling protects the large default byte limit.
|
||||
const minParserItems = 1024
|
||||
const maxParserItems = 131072
|
||||
const bytesPerParserItem = 128
|
||||
|
||||
function isASCIINumberBytes (buffer, start) {
|
||||
if (start >= buffer.length) {
|
||||
return false
|
||||
@@ -66,6 +75,12 @@ function isFieldName (line, length, field) {
|
||||
return true
|
||||
}
|
||||
|
||||
function createMaxEventSizeExceededError () {
|
||||
const error = new Error('EventSource message size exceeded')
|
||||
error.aborted = false
|
||||
return error
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} EventSourceStreamEvent
|
||||
* @type {object}
|
||||
@@ -114,6 +129,13 @@ class EventSourceStream extends Transform {
|
||||
pos = 0
|
||||
lineChunkIndex = 0
|
||||
linePos = 0
|
||||
lineLength = 0
|
||||
eventSize = 0
|
||||
eventFieldSizes = { data: 0, event: 0, id: 0, retry: 0 }
|
||||
dataLineCount = 0
|
||||
maxEventSize
|
||||
maxDataLines
|
||||
maxBufferedChunks
|
||||
|
||||
event = {
|
||||
data: undefined,
|
||||
@@ -124,6 +146,7 @@ class EventSourceStream extends Transform {
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {number} [options.maxEventSize]
|
||||
* @param {eventSourceSettings} options.eventSourceSettings
|
||||
* @param {Function} [options.push]
|
||||
*/
|
||||
@@ -135,6 +158,12 @@ class EventSourceStream extends Transform {
|
||||
super(options)
|
||||
|
||||
this.state = options.eventSourceSettings || {}
|
||||
this.maxEventSize = options.maxEventSize ?? defaultMaxEventSize
|
||||
const parserItemLimit = this.maxEventSize > 0
|
||||
? Math.min(maxParserItems, Math.max(minParserItems, Math.floor(this.maxEventSize / bytesPerParserItem)))
|
||||
: 0
|
||||
this.maxDataLines = parserItemLimit
|
||||
this.maxBufferedChunks = parserItemLimit
|
||||
if (options.push) {
|
||||
this.push = options.push
|
||||
}
|
||||
@@ -152,6 +181,14 @@ class EventSourceStream extends Transform {
|
||||
return
|
||||
}
|
||||
|
||||
// A leading line ending can immediately release the currently buffered
|
||||
// line, even when it uses the final allowed chunk slot.
|
||||
if (this.maxEventSize > 0 &&
|
||||
this.chunks.length >= this.maxBufferedChunks &&
|
||||
chunk[0] !== LF && chunk[0] !== CR) {
|
||||
callback(createMaxEventSizeExceededError())
|
||||
return
|
||||
}
|
||||
this.chunks.push(chunk)
|
||||
|
||||
// Strip leading byte-order-mark if we opened the stream and started
|
||||
@@ -230,7 +267,12 @@ class EventSourceStream extends Transform {
|
||||
|
||||
// In any case, we can process the line as we reached an
|
||||
// end-of-line character
|
||||
this.parseLine(this.readLine(), this.event)
|
||||
try {
|
||||
this.parseLine(this.readLine(), this.event)
|
||||
} catch (error) {
|
||||
callback(error)
|
||||
return
|
||||
}
|
||||
this.consumeCurrentByte()
|
||||
// A line was processed and this could be the end of the event. We need
|
||||
// to check if the next line is empty to determine if the event is
|
||||
@@ -239,15 +281,28 @@ class EventSourceStream extends Transform {
|
||||
continue
|
||||
}
|
||||
|
||||
// readLine() is only called after CR or LF. Reject an unfinished line
|
||||
// before it can retain an unbounded number of decoded chunks. The seven
|
||||
// extra bytes allow the longest field prefix ("event: " or "retry: ").
|
||||
if (this.maxEventSize > 0 && ++this.lineLength > this.maxEventSize + 7) {
|
||||
callback(createMaxEventSizeExceededError())
|
||||
return
|
||||
}
|
||||
this.advanceCursor()
|
||||
}
|
||||
|
||||
callback()
|
||||
}
|
||||
|
||||
_destroy (error, callback) {
|
||||
this.chunks.length = 0
|
||||
this.clearEvent()
|
||||
super._destroy(error, callback)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Buffer} line
|
||||
* @param {EventStreamEvent} event
|
||||
* @param {EventSourceStreamEvent} event
|
||||
*/
|
||||
parseLine (line, event) {
|
||||
// If the line is empty (a blank line)
|
||||
@@ -281,6 +336,13 @@ class EventSourceStream extends Transform {
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, DATA)) {
|
||||
if (this.maxEventSize > 0 && this.dataLineCount >= this.maxDataLines) {
|
||||
throw createMaxEventSizeExceededError()
|
||||
}
|
||||
const valueBytes = line.length - valueStart
|
||||
const dataSize = this.eventFieldSizes.data + (event.data === undefined ? 0 : 1) + valueBytes
|
||||
this.setEventFieldSize('data', dataSize)
|
||||
|
||||
const value = line.toString('utf8', valueStart)
|
||||
|
||||
if (event.data === undefined) {
|
||||
@@ -288,11 +350,13 @@ class EventSourceStream extends Transform {
|
||||
} else {
|
||||
event.data += `\n${value}`
|
||||
}
|
||||
this.dataLineCount++
|
||||
return
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, RETRY)) {
|
||||
if (isASCIINumberBytes(line, valueStart)) {
|
||||
this.setEventFieldSize('retry', line.length - valueStart)
|
||||
event.retry = line.toString('utf8', valueStart)
|
||||
}
|
||||
return
|
||||
@@ -300,20 +364,29 @@ class EventSourceStream extends Transform {
|
||||
|
||||
if (isFieldName(line, fieldLength, ID)) {
|
||||
if (isValidLastEventIdBytes(line, valueStart)) {
|
||||
this.setEventFieldSize('id', line.length - valueStart)
|
||||
event.id = line.toString('utf8', valueStart)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isFieldName(line, fieldLength, EVENT)) {
|
||||
const value = line.toString('utf8', valueStart)
|
||||
|
||||
if (value.length > 0) {
|
||||
event.event = value
|
||||
if (valueStart < line.length) {
|
||||
this.setEventFieldSize('event', line.length - valueStart)
|
||||
event.event = line.toString('utf8', valueStart)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setEventFieldSize (field, size) {
|
||||
const eventSize = this.eventSize - this.eventFieldSizes[field] + size
|
||||
if (this.maxEventSize > 0 && eventSize > this.maxEventSize) {
|
||||
throw createMaxEventSizeExceededError()
|
||||
}
|
||||
this.eventSize = eventSize
|
||||
this.eventFieldSizes[field] = size
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {EventSourceStreamEvent} event
|
||||
*/
|
||||
@@ -344,6 +417,12 @@ class EventSourceStream extends Transform {
|
||||
this.event.event = undefined
|
||||
this.event.id = undefined
|
||||
this.event.retry = undefined
|
||||
this.eventSize = 0
|
||||
this.dataLineCount = 0
|
||||
this.eventFieldSizes.data = 0
|
||||
this.eventFieldSizes.event = 0
|
||||
this.eventFieldSizes.id = 0
|
||||
this.eventFieldSizes.retry = 0
|
||||
}
|
||||
|
||||
hasPendingEvent () {
|
||||
@@ -379,14 +458,16 @@ class EventSourceStream extends Transform {
|
||||
syncLineStartToCursor () {
|
||||
this.lineChunkIndex = this.chunkIndex
|
||||
this.linePos = this.pos
|
||||
this.lineLength = 0
|
||||
this.dropConsumedChunks()
|
||||
}
|
||||
|
||||
dropConsumedChunks () {
|
||||
while (this.lineChunkIndex > 0) {
|
||||
this.chunks.shift()
|
||||
this.lineChunkIndex--
|
||||
this.chunkIndex--
|
||||
if (this.lineChunkIndex > 0) {
|
||||
const consumed = this.lineChunkIndex
|
||||
this.chunks.splice(0, consumed)
|
||||
this.lineChunkIndex = 0
|
||||
this.chunkIndex -= consumed
|
||||
}
|
||||
|
||||
if (this.chunkIndex === this.chunks.length) {
|
||||
|
||||
+4
-1
@@ -11,6 +11,7 @@ const { isNetworkError } = require('../fetch/response')
|
||||
const { delay } = require('./util')
|
||||
const { kEnumerableProperty } = require('../../core/util')
|
||||
const { environmentSettingsObject } = require('../fetch/util')
|
||||
const { getGlobalDispatcher } = require('../../global')
|
||||
|
||||
let experimentalWarned = false
|
||||
|
||||
@@ -292,6 +293,7 @@ class EventSource extends EventTarget {
|
||||
|
||||
const eventSourceStream = new EventSourceStream({
|
||||
eventSourceSettings: this.#state,
|
||||
maxEventSize: this.#dispatcher.eventSourceOptions?.maxEventSize,
|
||||
push: (event) => {
|
||||
this.dispatchEvent(createFastMessageEvent(
|
||||
event.type,
|
||||
@@ -470,7 +472,8 @@ webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
|
||||
},
|
||||
{
|
||||
key: 'dispatcher', // undici only
|
||||
converter: webidl.converters.any
|
||||
converter: webidl.converters.any,
|
||||
defaultValue: () => getGlobalDispatcher()
|
||||
}
|
||||
])
|
||||
|
||||
|
||||
+7
-9
@@ -1950,8 +1950,10 @@ async function httpNetworkFetch (
|
||||
// 19. Run these steps in parallel:
|
||||
|
||||
// 1. Run these steps, but abort when fetchParams is canceled:
|
||||
fetchParams.controller.onAborted = onAborted
|
||||
fetchParams.controller.on('terminated', onAborted)
|
||||
if (!fetchParams.controller.resume) {
|
||||
fetchParams.controller.on('terminated', onAborted)
|
||||
}
|
||||
|
||||
fetchParams.controller.resume = async () => {
|
||||
// 1. While true
|
||||
while (true) {
|
||||
@@ -2120,8 +2122,6 @@ async function httpNetworkFetch (
|
||||
}
|
||||
location = headersList.get('location', true)
|
||||
|
||||
this.body = new Readable({ read: resume })
|
||||
|
||||
const decoders = []
|
||||
|
||||
const willFollow = location && request.redirect === 'follow' &&
|
||||
@@ -2139,7 +2139,7 @@ async function httpNetworkFetch (
|
||||
// CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
|
||||
const maxContentEncodings = 5
|
||||
if (codings.length > maxContentEncodings) {
|
||||
reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
|
||||
this.abort(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -2172,6 +2172,8 @@ async function httpNetworkFetch (
|
||||
}
|
||||
}
|
||||
|
||||
this.body = new Readable({ read: resume })
|
||||
|
||||
const onError = this.onError.bind(this)
|
||||
|
||||
resolve({
|
||||
@@ -2218,10 +2220,6 @@ async function httpNetworkFetch (
|
||||
fetchParams.controller.off('terminated', this.abort)
|
||||
}
|
||||
|
||||
if (fetchParams.controller.onAborted) {
|
||||
fetchParams.controller.off('terminated', fetchParams.controller.onAborted)
|
||||
}
|
||||
|
||||
fetchParams.controller.ended = true
|
||||
|
||||
this.body.push(null)
|
||||
|
||||
+14
@@ -249,6 +249,20 @@ class ByteParser extends Writable {
|
||||
if (isControlFrame(this.#info.opcode)) {
|
||||
this.#loop = this.parseControlFrame(body)
|
||||
this.#state = parserStates.INFO
|
||||
|
||||
// If the automatic PONG/CLOSE reply filled the socket's write buffer,
|
||||
// stop parsing and resume on drain so a PING flood cannot grow the
|
||||
// outbound queue without bound.
|
||||
const socket = this.ws[kResponse].socket
|
||||
if (this.#loop && socket.writableNeedDrain) {
|
||||
this.#loop = false
|
||||
socket.once('drain', () => {
|
||||
if (this.destroyed) return
|
||||
this.#loop = true
|
||||
this.run(callback)
|
||||
})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if (!this.#info.compressed) {
|
||||
if (!this.writeFragments(body)) {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "undici",
|
||||
"version": "6.29.0",
|
||||
"version": "6.29.1",
|
||||
"description": "An HTTP/1.1 client, written from scratch for Node.js",
|
||||
"homepage": "https://undici.nodejs.org",
|
||||
"bugs": {
|
||||
|
||||
+14
@@ -80,6 +80,8 @@ export declare namespace Client {
|
||||
maxResponseSize?: number;
|
||||
/** WebSocket-specific options */
|
||||
webSocket?: Client.WebSocketOptions;
|
||||
/** EventSource-specific options */
|
||||
eventSource?: Client.EventSourceOptions;
|
||||
/** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
|
||||
autoSelectFamily?: boolean;
|
||||
/** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
|
||||
@@ -120,6 +122,18 @@ export declare namespace Client {
|
||||
*/
|
||||
maxPayloadSize?: number;
|
||||
}
|
||||
export interface EventSourceOptions {
|
||||
/**
|
||||
* Maximum total bytes of data and metadata field values retained for a
|
||||
* pending EventSource event. Each unfinished line is separately bounded
|
||||
* to this value plus seven syntax bytes. The number of data lines per
|
||||
* event and buffered input chunks are each limited to
|
||||
* min(131072, max(1024, floor(maxEventSize / 128))).
|
||||
* Set to 0 to disable these limits.
|
||||
* @default buffer.kStringMaxLength
|
||||
*/
|
||||
maxEventSize?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export default Client;
|
||||
Generated
+6
-6
@@ -103,9 +103,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "10.2.0",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.2.0.tgz",
|
||||
"integrity": "sha512-/XyGw6kX2stMdKGUJdAQmYAeY1FscWfdRydfd2NtK3A3KDfUUXCqZzExSNAt2xhh90X2qLCR+o2Gd48YPJcJwA==",
|
||||
"version": "10.6.1",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz",
|
||||
"integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
@@ -137,9 +137,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.29.0",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz",
|
||||
"integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==",
|
||||
"version": "6.29.1",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
|
||||
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
|
||||
Reference in new issue
Block a user