node_modules: update (#362)

Co-authored-by: dawidd6 <9713907+dawidd6@users.noreply.github.com>
This commit is contained in:
Dawid Dziurlaanddawidd6 authored and GitHub committed 2026-11-11 07:38:40 +01:00
1 parent 4a48500d96
commit aefdaa6a6c
49 files changed
+1314 -293

No files matched your search

+3 -3
View File
@@ -94,9 +94,9 @@
} }
}, },
"node_modules/nodemailer": { "node_modules/nodemailer": {
"version": "10.3.1", "version": "10.5.0",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.3.1.tgz", "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.5.0.tgz",
"integrity": "sha512-uF0AFsJC07Y1vdW7p580DKAnh7rAO+4UPSSB3mDCPNDufoiaOebV6JmrzpxB14OjEEEiBsNdYoM2Y+fN8M7BBA==", "integrity": "sha512-L/w/HH5MqpzMDuZD7fQdt/+KqymuvrpaApaIjAH2XA3ILePwlcvXCVVvP75xVrXCEt2ggK2marrrHHFB5Qu0kA==",
"license": "MIT-0", "license": "MIT-0",
"engines": { "engines": {
"node": ">=20.0.0" "node": ">=20.0.0"
+28
View File
@@ -1,5 +1,33 @@
# CHANGELOG # CHANGELOG
## [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) ## [10.3.1](https://github.com/nodemailer/nodemailer/compare/v10.3.0...v10.3.1) (2026-10-29)
+21
View File
@@ -14,6 +14,27 @@ 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. 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.
## Having an issue? ## Having an issue?
#### First review the docs #### First review the docs
+185 -2
View File
@@ -48,6 +48,30 @@ class TokenList {
this.slots[at + 2] = end; this.slots[at + 2] = end;
return this.length++; 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 * The character of an operator token, an empty string for a text run
*/ */
@@ -183,6 +207,44 @@ function _isSpaceCode(code) {
code === 0x3000 || code === 0x3000 ||
code === 0xfeff); 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 * 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, * 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 * The scan is by index, a pattern such as /\s+@/ backtracks over a long whitespace run that
* no '@' follows. * no '@' follows.
* *
* The whitespace around the dots of the domain that follows is dropped as well, see
* _joinDomainDotSpacing.
*
* @param value Value holding the '@' * @param value Value holding the '@'
* @param at Offset of the '@', or -1 * @param at Offset of the '@', or -1
* @return The value with the whitespace beside that '@' removed * @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))) { while (end < value.length && _isSpaceCode(value.charCodeAt(end))) {
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 '@' * 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 // 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 // local part is until the '@' after it joins the run
let lastTextPureQuoted = false; 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 // 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 // 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 // every token, which is quadratic over an address built from many comment-joined atoms
@@ -570,18 +723,27 @@ function _collectAddressParts(tokens, from, to) {
case '<': case '<':
state = 'address'; state = 'address';
insideQuotes = false; insideQuotes = false;
lastTextOpen = false;
break; break;
case '(': case '(':
state = 'comment'; state = 'comment';
insideQuotes = false; insideQuotes = false;
gapsFolding = gapsFolding && _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
break; break;
case '"': case '"':
insideQuotes = !insideQuotes; insideQuotes = !insideQuotes;
state = 'text'; state = 'text';
lastTextOpen = false;
break; break;
default: default:
state = 'text'; state = 'text';
insideQuotes = false; insideQuotes = false;
if (value !== ')') {
lastTextOpen = false;
}
else {
gapFrom = tokens.contentEnd(i);
}
break; 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 // 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 // 'user@example.com(x)evil.com' as the single domain 'example.comevil.com' and
// deliver to a domain the sender never named. // 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 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) { if (joins) {
const last = data[state].length - 1; const last = data[state].length - 1;
if (state === 'text' && !insideQuotes) { if (state === 'text' && !insideQuotes) {
@@ -624,6 +801,12 @@ function _collectAddressParts(tokens, from, to) {
lastTextPureQuoted = insideQuotes; 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 // If there is no text but a comment, replace the two. A comment is never part of a
+2 -2
View File
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); 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 mimeFuncs = __importStar(require("../mime-funcs/index.js"));
const node_crypto_1 = __importDefault(require("node:crypto")); const node_crypto_1 = __importDefault(require("node:crypto"));
const errors = __importStar(require("../errors.js")); const errors = __importStar(require("../errors.js"));
@@ -103,7 +103,7 @@ function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyH
'v=1', 'v=1',
'a=rsa-' + hashAlgo, 'a=rsa-' + hashAlgo,
'c=relaxed/relaxed', 'c=relaxed/relaxed',
'd=' + punycode.toASCII(cleanTagValue(domainName)), 'd=' + shared.normalizeDomain(cleanTagValue(domainName), false),
'q=dns/txt', 'q=dns/txt',
's=' + cleanTagValue(keySelector), 's=' + cleanTagValue(keySelector),
'bh=' + bodyHash, 'bh=' + bodyHash,
+2
View File
@@ -23,6 +23,7 @@ export declare const ERROR_CODES: {
readonly EMESSAGE: "Message delivery error"; readonly EMESSAGE: "Message delivery error";
readonly EOTP: "Invalid one-time passcode data (otp option)"; readonly EOTP: "Invalid one-time passcode data (otp option)";
readonly ESTREAM: "Stream processing error"; readonly ESTREAM: "Stream processing error";
readonly EABORT: "Message sending aborted";
readonly EAUTH: "Authentication failed"; readonly EAUTH: "Authentication failed";
readonly ENOAUTH: "Authentication credentials not provided"; readonly ENOAUTH: "Authentication credentials not provided";
readonly EOAUTH2: "OAuth2 token generation or refresh error"; readonly EOAUTH2: "OAuth2 token generation or refresh error";
@@ -51,6 +52,7 @@ export declare const EENVELOPE = "EENVELOPE";
export declare const EMESSAGE = "EMESSAGE"; export declare const EMESSAGE = "EMESSAGE";
export declare const EOTP = "EOTP"; export declare const EOTP = "EOTP";
export declare const ESTREAM = "ESTREAM"; export declare const ESTREAM = "ESTREAM";
export declare const EABORT = "EABORT";
export declare const EAUTH = "EAUTH"; export declare const EAUTH = "EAUTH";
export declare const ENOAUTH = "ENOAUTH"; export declare const ENOAUTH = "ENOAUTH";
export declare const EOAUTH2 = "EOAUTH2"; export declare const EOAUTH2 = "EOAUTH2";
+11 -1
View File
@@ -10,7 +10,7 @@
* err.code = errors.ECONNECTION; * err.code = errors.ECONNECTION;
*/ */
Object.defineProperty(exports, "__esModule", { value: true }); 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.EOTP = 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 * Error code descriptions for documentation and debugging
*/ */
@@ -29,6 +29,7 @@ exports.ERROR_CODES = {
EMESSAGE: 'Message delivery error', EMESSAGE: 'Message delivery error',
EOTP: 'Invalid one-time passcode data (otp option)', EOTP: 'Invalid one-time passcode data (otp option)',
ESTREAM: 'Stream processing error', ESTREAM: 'Stream processing error',
EABORT: 'Message sending aborted',
// Authentication errors // Authentication errors
EAUTH: 'Authentication failed', EAUTH: 'Authentication failed',
ENOAUTH: 'Authentication credentials not provided', ENOAUTH: 'Authentication credentials not provided',
@@ -58,6 +59,7 @@ exports.EENVELOPE = 'EENVELOPE';
exports.EMESSAGE = 'EMESSAGE'; exports.EMESSAGE = 'EMESSAGE';
exports.EOTP = 'EOTP'; exports.EOTP = 'EOTP';
exports.ESTREAM = 'ESTREAM'; exports.ESTREAM = 'ESTREAM';
exports.EABORT = 'EABORT';
exports.EAUTH = 'EAUTH'; exports.EAUTH = 'EAUTH';
exports.ENOAUTH = 'ENOAUTH'; exports.ENOAUTH = 'ENOAUTH';
exports.EOAUTH2 = 'EOAUTH2'; exports.EOAUTH2 = 'EOAUTH2';
@@ -70,6 +72,14 @@ exports.EPROXY = 'EPROXY';
exports.EFILEACCESS = 'EFILEACCESS'; exports.EFILEACCESS = 'EFILEACCESS';
exports.EURLACCESS = 'EURLACCESS'; exports.EURLACCESS = 'EURLACCESS';
exports.EFETCH = 'EFETCH'; 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 * Tells whether the error ended the connection rather than rejected what was sent over it
*/ */
+2
View File
@@ -83,6 +83,8 @@ class JSONTransport {
} }
delete data.envelope; delete data.envelope;
delete data.normalizedHeaders; delete data.normalizedHeaders;
// the per-message AbortSignal is not message data
delete data.signal;
// the message field is the object itself with skipEncoding, the // the message field is the object itself with skipEncoding, the
// createTransport overload for that option types the result accordingly // createTransport overload for that option types the result accordingly
return done(null, { return done(null, {
+12 -2
View File
@@ -112,6 +112,11 @@ export interface MailMeta {
* declared on Transport, Transporter and Mail * declared on Transport, Transporter and Mail
*/ */
export interface Transport<T = SentMessageInfo, D extends TransportOptions = TransportOptions> { 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 */ /** Transport name, used for logging */
name: string; name: string;
/** Transport version, used for logging */ /** Transport version, used for logging */
@@ -176,8 +181,13 @@ declare class Mail<out T = SentMessageInfo, out D extends TransportOptions = Tra
dkim: DKIM | false; dkim: DKIM | false;
transporter: Transport<T, D>; transporter: Transport<T, D>;
logger: shared.Logger; 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 */ /** Tells whether the transport can take a message right away */
isIdle: () => boolean; isIdle: () => boolean;
/** Checks the configuration, the SMTP transports connect and authenticate for it */ /** Checks the configuration, the SMTP transports connect and authenticate for it */
+56 -4
View File
@@ -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. * asks a server to accept 100, so a real send is bounded far below this.
*/ */
const DEFAULT_MAX_RECIPIENTS = 100000; 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 * Creates an object for exposing the Mail API
* *
@@ -157,11 +167,43 @@ class Mail extends node_events_1.EventEmitter {
this.getSocket = false; this.getSocket = false;
} }
const mail = new mail_message_js_1.default(this, data); 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 // a failed message is not going to be read anymore, release its content streams
const fail = (err) => { const fail = (err) => {
mail.releaseStreams(); finish(err);
done(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({ this.logger.debug({
tnx: 'transport', tnx: 'transport',
name: this.transporter.name, name: this.transporter.name,
@@ -169,6 +211,9 @@ class Mail extends node_events_1.EventEmitter {
action: 'send' action: 'send'
}, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version); }, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version);
this._processPlugins('compile', mail, err => { this._processPlugins('compile', mail, err => {
if (settled) {
return;
}
if (err) { if (err) {
this.logger.error({ this.logger.error({
err, err,
@@ -206,6 +251,9 @@ class Mail extends node_events_1.EventEmitter {
return fail(err); return fail(err);
} }
this._processPlugins('stream', mail, err => { this._processPlugins('stream', mail, err => {
if (settled) {
return;
}
if (err) { if (err) {
this.logger.error({ this.logger.error({
err, err,
@@ -225,16 +273,17 @@ class Mail extends node_events_1.EventEmitter {
return dkim.sign(input, mail.data._dkim); return dkim.sign(input, mail.data._dkim);
}); });
} }
// The transport takes ownership of cancellation from here, including queued work.
removeAbortListener();
this.transporter.send(mail, (...args) => { this.transporter.send(mail, (...args) => {
if (args[0]) { if (args[0]) {
mail.releaseStreams();
this.logger.error({ this.logger.error({
err: args[0], err: args[0],
tnx: 'transport', tnx: 'transport',
action: 'send' action: 'send'
}, 'Send Error: %s', args[0].message); }, '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 pos = 0;
let block = 'default'; let block = 'default';
const processPlugins = () => { const processPlugins = () => {
if (mail.data.signal?.aborted) {
return callback(errors.createAbortError(mail.data.signal));
}
let curplugins = block === 'default' ? defaultPlugins : userPlugins; let curplugins = block === 'default' ? defaultPlugins : userPlugins;
if (pos >= curplugins.length) { if (pos >= curplugins.length) {
if (block === 'default' && userPlugins.length) { if (block === 'default' && userPlugins.length) {
+10
View File
@@ -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 * tree is built from, the fields below are the ones the mailer reads on top of those
*/ */
export interface SendMailOptions extends MailComposerOptions { 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 signing options for this message, used instead of the ones of the transporter */
dkim?: DKIMOptions | undefined; 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 */ /** 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 */
+2 -1
View File
@@ -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; 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 value String to be encoded
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
+72 -2
View File
@@ -181,8 +181,75 @@ function encodeWord(data, mimeWordEncoding, maxLength) {
} }
return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?='); 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 value String to be encoded
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
@@ -206,11 +273,14 @@ function encodeWords(value, mimeWordEncoding, maxLength, encodeAll) {
lastSpecial = i; lastSpecial = i;
} }
} }
if (value.indexOf('=?') >= 0) {
[firstSpecial, lastSpecial] = _markInvalidEncodedWords(value, [firstSpecial, lastSpecial]);
}
if (firstSpecial < 0) { if (firstSpecial < 0) {
return value; return value;
} }
if (encodeAll) { 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); return encodeWord(value, mimeWordEncoding, maxLength);
} }
// encode from the start of the word holding the first such character to the end of the // encode from the start of the word holding the first such character to the end of the
+1 -73
View File
@@ -39,10 +39,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const node_crypto_1 = __importDefault(require("node:crypto")); const node_crypto_1 = __importDefault(require("node:crypto"));
const node_fs_1 = __importDefault(require("node:fs")); const node_fs_1 = __importDefault(require("node:fs"));
const punycode = __importStar(require("../punycode/index.js"));
const node_stream_1 = require("node:stream"); const node_stream_1 = require("node:stream");
const shared = __importStar(require("../shared/index.js")); const shared = __importStar(require("../shared/index.js"));
const node_url_1 = __importDefault(require("node:url"));
const mimeFuncs = __importStar(require("../mime-funcs/index.js")); const mimeFuncs = __importStar(require("../mime-funcs/index.js"));
const qp = __importStar(require("../qp/index.js")); const qp = __importStar(require("../qp/index.js"));
const base64 = __importStar(require("../base64/index.js")); const base64 = __importStar(require("../base64/index.js"));
@@ -93,20 +91,6 @@ function stripWhitespaceInAngleBrackets(value) {
} }
return result + value.slice(pos); 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 // pipeline() needs a callback to not throw, the errors it sees reach the last stream anyway
const PIPELINE_NOOP = () => false; const PIPELINE_NOOP = () => false;
// The error a node streaming into an output that was destroyed stops with // The error a node streaming into an output that was destroyed stops with
@@ -115,62 +99,6 @@ function abortedError() {
err.code = errors.ESTREAM; err.code = errors.ESTREAM;
return err; 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. * Removes the characters that must never reach a multipart delimiter line.
* *
@@ -1538,7 +1466,7 @@ class MimeNode {
// symmetry on both sides of the '@' rather than being encoded to an A-label // symmetry on both sides of the '@' rather than being encoded to an A-label
const smtputf8 = /[\x80-\uFFFF]/.test(user); const smtputf8 = /[\x80-\uFFFF]/.test(user);
try { try {
encodedDomain = normalizeDomain(domain.toLowerCase(), smtputf8); encodedDomain = shared.normalizeDomain(domain, smtputf8);
} }
catch (_err) { catch (_err) {
// keep domain as supplied // keep domain as supplied
+1 -1
View File
@@ -1,3 +1,3 @@
export declare const name = "nodemailer"; export declare const name = "nodemailer";
export declare const version = "10.3.1"; export declare const version = "10.5.0";
export declare const homepage = "https://nodemailer.com/"; export declare const homepage = "https://nodemailer.com/";
+1 -1
View File
@@ -3,5 +3,5 @@
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.homepage = exports.version = exports.name = void 0; exports.homepage = exports.version = exports.name = void 0;
exports.name = 'nodemailer'; exports.name = 'nodemailer';
exports.version = '10.3.1'; exports.version = '10.5.0';
exports.homepage = 'https://nodemailer.com/'; exports.homepage = 'https://nodemailer.com/';
+23
View File
@@ -289,3 +289,26 @@ export declare function unreadableStreamError(stream: Readable): NodemailerError
* @param callback Callback function with (err, value) * @param callback Callback function with (err, value)
*/ */
export declare function resolveStream(stream: Readable, callback: (err: Error | null, value?: Buffer) => void): void; 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
View File
@@ -43,6 +43,7 @@ exports.recordStreamErrors = recordStreamErrors;
exports.destroyStream = destroyStream; exports.destroyStream = destroyStream;
exports.unreadableStreamError = unreadableStreamError; exports.unreadableStreamError = unreadableStreamError;
exports.resolveStream = resolveStream; exports.resolveStream = resolveStream;
exports.normalizeDomain = normalizeDomain;
const urllib = __importStar(require("./url.js")); const urllib = __importStar(require("./url.js"));
const node_util_1 = __importDefault(require("node:util")); const node_util_1 = __importDefault(require("node:util"));
const node_fs_1 = __importDefault(require("node:fs")); 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_dns_1 = __importDefault(require("node:dns"));
const node_net_1 = __importDefault(require("node:net")); const node_net_1 = __importDefault(require("node:net"));
const node_os_1 = __importDefault(require("node:os")); 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 node_stream_1 = require("node:stream");
const DNS_TTL = 5 * 60 * 1000; const DNS_TTL = 5 * 60 * 1000;
const CACHE_CLEANUP_INTERVAL = 30 * 1000; // Minimum 30 seconds between cleanups const CACHE_CLEANUP_INTERVAL = 30 * 1000; // Minimum 30 seconds between cleanups
@@ -771,3 +774,79 @@ function createDefaultLogger(levels) {
}); });
return logger; 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);
}
+6
View File
@@ -287,6 +287,9 @@ class SMTPConnection extends node_events_1.EventEmitter {
// socket object is set up but not yet connected // socket object is set up but not yet connected
this._socket = this.options.socket; this._socket = this.options.socket;
return this._resolveAndConnect(opts, _resolved => { return this._resolveAndConnect(opts, _resolved => {
if (this._destroyed || this._closing) {
return;
}
try { try {
this._socket.connect(this.port, this.host, () => { this._socket.connect(this.port, this.host, () => {
// a `secure` connection over a caller-provided socket must still // a `secure` connection over a caller-provided socket must still
@@ -1077,6 +1080,9 @@ class SMTPConnection extends node_events_1.EventEmitter {
* @internal * @internal
*/ */
_upgradeConnection(callback) { _upgradeConnection(callback) {
if (this._destroyed || this._closing) {
return;
}
// RFC 3207 section 6: the client MUST discard any knowledge obtained from // 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 // 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 // buffered input received before the handshake so a man-in-the-middle cannot
+10 -3
View File
@@ -76,6 +76,7 @@ export interface SMTPPoolRateLimit {
* @param options SMTP Connection options * @param options SMTP Connection options
*/ */
declare class SMTPPool extends EventEmitter { declare class SMTPPool extends EventEmitter {
readonly supportsAbortSignal = true;
options: SMTPPoolResolvedOptions; options: SMTPPoolResolvedOptions;
logger: shared.Logger; logger: shared.Logger;
name: string; name: string;
@@ -102,10 +103,16 @@ declare class SMTPPool extends EventEmitter {
*/ */
send(mail: MailMessage<SMTPPoolSentMessageInfo>, callback: SMTPPoolSendCallback): boolean; send(mail: MailMessage<SMTPPoolSentMessageInfo>, callback: SMTPPoolSendCallback): boolean;
/** /**
* Closes all connections in the pool. If there is a message being sent, the connection * Closes the pool. Idle connections are closed at once and a connection in the middle of a
* is closed later * 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 * Returns true if there are free slots in the queue
*/ */
+69 -11
View File
@@ -56,6 +56,7 @@ const REQUEUE_MAX_DELAY = 2000;
class SMTPPool extends node_events_1.EventEmitter { class SMTPPool extends node_events_1.EventEmitter {
constructor(options) { constructor(options) {
super(); super();
this.supportsAbortSignal = true;
options = options || {}; options = options || {};
if (typeof options === 'string') { if (typeof options === 'string') {
options = { options = {
@@ -134,20 +135,33 @@ class SMTPPool extends node_events_1.EventEmitter {
return false; return false;
} }
// counted until the callback runs, whichever path runs it: delivered, failed, requeued // 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 counted = true;
let detachSignal;
this._pending++; this._pending++;
this._queue.push({ const entry = {
mail, mail,
requeueAttempts: 0, requeueAttempts: 0,
callback: (err, info) => { callback: (err, info) => {
if (counted) { if (!counted) {
return;
}
counted = false; counted = false;
this._pending--; this._pending--;
} detachSignal?.();
entry.resource = undefined;
callback(err, info); 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) { if (this.idling && this._queue.length >= this.options.maxConnections) {
this.idling = false; this.idling = false;
} }
@@ -155,10 +169,49 @@ class SMTPPool extends node_events_1.EventEmitter {
return true; return true;
} }
/** /**
* Closes all connections in the pool. If there is a message being sent, the connection * Fails a queued or assigned entry when its signal aborts: removes it from the queue, or
* is closed later * 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; let connection;
const len = this._connections.length; const len = this._connections.length;
this._closed = true; this._closed = true;
@@ -169,9 +222,10 @@ class SMTPPool extends node_events_1.EventEmitter {
if (!len && !this._queue.length) { if (!len && !this._queue.length) {
return; 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--) { 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 = this._connections[i];
connection.close(); connection.close();
this.logger.info({ this.logger.info({
@@ -249,6 +303,7 @@ class SMTPPool extends node_events_1.EventEmitter {
this.emit('idle'); this.emit('idle');
} }
const entry = (connection.queueEntry = this._queue.shift()); const entry = (connection.queueEntry = this._queue.shift());
entry.resource = connection;
entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, ''); entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, '');
connection.available = false; connection.available = false;
this.logger.debug({ this.logger.debug({
@@ -356,7 +411,9 @@ class SMTPPool extends node_events_1.EventEmitter {
setTimeout(() => { setTimeout(() => {
let delay = 0; let delay = 0;
if (connection.queueEntry) { 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); delay = this._requeueEntryOnConnectionClose(connection);
} }
else { else {
@@ -418,6 +475,7 @@ class SMTPPool extends node_events_1.EventEmitter {
messageId: connection.queueEntry.messageId, messageId: connection.queueEntry.messageId,
action: 'requeue' action: 'requeue'
}, 'Re-queued message <%s> for #%s. Attempt: #%s', connection.queueEntry.messageId, connection.id, connection.queueEntry.requeueAttempts); }, '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); this._queue.unshift(connection.queueEntry);
connection.queueEntry = false; connection.queueEntry = false;
return delay; return delay;
+26 -4
View File
@@ -86,6 +86,7 @@ class PoolResource extends node_events_1.EventEmitter {
} }
this._connection = false; this._connection = false;
this._connected = false; this._connected = false;
this._closed = false;
this.messages = 0; this.messages = 0;
this.available = true; this.available = true;
this._failed = false; this._failed = false;
@@ -113,6 +114,10 @@ class PoolResource extends node_events_1.EventEmitter {
// the proxy handshake, if any, counts against connectionTimeout as well // the proxy handshake, if any, counts against connectionTimeout as well
const connectStartedAt = Date.now(); const connectStartedAt = Date.now();
this.pool.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => { this.pool.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
if (this._closed) {
socketOptions && socketOptions.connection?.destroy();
return;
}
if (err) { if (err) {
// nothing was connected, so no 'close' event is coming that would free the // 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 // 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 = new index_js_1.default(options);
this.connection._connectStartedAt = connectStartedAt; this.connection._connectStartedAt = connectStartedAt;
this.connection.on('error', (err) => { 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 // the send callback gets the same error and decides what it means for the message
return; return;
} }
@@ -150,7 +155,7 @@ class PoolResource extends node_events_1.EventEmitter {
return; return;
} }
this._fail(err); this._fail(err);
if (returned) { if (returned || this._closed) {
return; return;
} }
returned = true; returned = true;
@@ -161,7 +166,7 @@ class PoolResource extends node_events_1.EventEmitter {
returned = true; returned = true;
}); });
this.connection.connect(err => { this.connection.connect(err => {
if (returned) { if (returned || this._closed) {
return; return;
} }
if (err) { if (err) {
@@ -172,7 +177,7 @@ class PoolResource extends node_events_1.EventEmitter {
} }
if (this.auth && (this.connection.allowsAuth || options.forceAuth)) { if (this.auth && (this.connection.allowsAuth || options.forceAuth)) {
this.connection.login(this.auth, err => { this.connection.login(this.auth, err => {
if (returned) { if (returned || this._closed) {
return; return;
} }
returned = true; returned = true;
@@ -200,6 +205,9 @@ class PoolResource extends node_events_1.EventEmitter {
* @param callback Callback function * @param callback Callback function
*/ */
send(mail, callback) { send(mail, callback) {
if (this._closed) {
return;
}
if (!this._connected) { if (!this._connected) {
return this.connect(err => { return this.connect(err => {
if (err) { if (err) {
@@ -231,6 +239,9 @@ class PoolResource extends node_events_1.EventEmitter {
const reused = this.messages > 0; const reused = this.messages > 0;
const messageStream = mail.message.createReadStream(); const messageStream = mail.message.createReadStream();
this.connection.send(envelope, messageStream, (err, info) => { this.connection.send(envelope, messageStream, (err, info) => {
if (mail.data.signal?.aborted) {
return;
}
this._sending = false; this._sending = false;
this.messages++; this.messages++;
if (err) { if (err) {
@@ -277,6 +288,9 @@ class PoolResource extends node_events_1.EventEmitter {
* @internal * @internal
*/ */
_release() { _release() {
if (this._closed) {
return;
}
if (this.messages >= this.options.maxMessages) { if (this.messages >= this.options.maxMessages) {
const err = new Error('Resource exhausted'); const err = new Error('Resource exhausted');
err.code = errors.EMAXLIMIT; err.code = errors.EMAXLIMIT;
@@ -285,6 +299,9 @@ class PoolResource extends node_events_1.EventEmitter {
return; return;
} }
this.pool._checkRateLimit(() => { this.pool._checkRateLimit(() => {
if (this._closed) {
return;
}
this.available = true; this.available = true;
this._startIdleTimer(); this._startIdleTimer();
this.emit('available'); this.emit('available');
@@ -327,6 +344,11 @@ class PoolResource extends node_events_1.EventEmitter {
* Closes the connection * Closes the connection
*/ */
close() { close() {
if (this._closed) {
return;
}
this._closed = true;
this.available = false;
this._connected = false; this._connected = false;
this._stopIdleTimer(); this._stopIdleTimer();
if (this.auth && this.auth.oauth2) { if (this.auth && this.auth.oauth2) {
+1
View File
@@ -93,6 +93,7 @@ export type SMTPTransportSendCallback = ResultCallback<SMTPSentMessageInfo>;
* @param options Connection options * @param options Connection options
*/ */
declare class SMTPTransport extends EventEmitter { declare class SMTPTransport extends EventEmitter {
readonly supportsAbortSignal = true;
options: SMTPTransportOptions; options: SMTPTransportOptions;
logger: shared.Logger; logger: shared.Logger;
name: string; name: string;
+47 -35
View File
@@ -59,6 +59,7 @@ const MESSAGE_AUTH_KEYS = ['type', 'user', 'pass', 'accessToken', 'refreshToken'
class SMTPTransport extends node_events_1.EventEmitter { class SMTPTransport extends node_events_1.EventEmitter {
constructor(options) { constructor(options) {
super(); super();
this.supportsAbortSignal = true;
options = options || {}; options = options || {};
if (typeof options === 'string') { if (typeof options === 'string') {
options = { options = {
@@ -153,13 +154,46 @@ class SMTPTransport extends node_events_1.EventEmitter {
* @param callback Callback function * @param callback Callback function
*/ */
send(mail, callback) { 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 // the proxy handshake, if any, counts against connectionTimeout as well
const connectStartedAt = Date.now(); const connectStartedAt = Date.now();
this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => { this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
if (returned) {
socketOptions && socketOptions.connection?.destroy();
return;
}
if (err) { if (err) {
return callback(err); return finish(err);
} }
let returned = false;
let options = this.options; let options = this.options;
if (socketOptions && socketOptions.connection) { if (socketOptions && socketOptions.connection) {
this.logger.info({ this.logger.info({
@@ -173,24 +207,9 @@ class SMTPTransport extends node_events_1.EventEmitter {
// only copy options if we need to modify it // only copy options if we need to modify it
options = Object.assign(shared.assign(false, options), socketOptions); options = Object.assign(shared.assign(false, options), socketOptions);
} }
const connection = new index_js_1.default(options); const smtp = (connection = new index_js_1.default(options));
connection._connectStartedAt = connectStartedAt; smtp._connectStartedAt = connectStartedAt;
let perCallAuth; smtp.once('error', err => finish(err));
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 sendMessage = () => { const sendMessage = () => {
const envelope = mail.message.getEnvelope(); const envelope = mail.message.getEnvelope();
const messageId = mail.message.messageId(); const messageId = mail.message.messageId();
@@ -209,20 +228,17 @@ class SMTPTransport extends node_events_1.EventEmitter {
tnx: 'send', tnx: 'send',
messageId messageId
}, 'Sending message %s to <%s>', messageId, recipients.join(', ')); }, '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) { if (returned) {
// the connection error handler has already reported this send // the connection error handler has already reported this send
return; return;
} }
returned = true;
cleanupPerCallAuth();
connection.close();
if (err) { if (err) {
this.logger.error({ this.logger.error({
err, err,
tnx: 'send' tnx: 'send'
}, 'Send error for %s: %s', messageId, err.message); }, 'Send error for %s: %s', messageId, err.message);
return callback(err); return finish(err);
} }
info.envelope = { info.envelope = {
from: envelope.from, from: envelope.from,
@@ -230,7 +246,7 @@ class SMTPTransport extends node_events_1.EventEmitter {
}; };
info.messageId = messageId; info.messageId = messageId;
try { try {
return callback(null, info); return finish(null, info);
} }
catch (E) { catch (E) {
this.logger.error({ this.logger.error({
@@ -240,27 +256,23 @@ class SMTPTransport extends node_events_1.EventEmitter {
} }
}); });
}; };
connection.connect(err => { smtp.connect(err => {
if (returned) { if (returned) {
return; return;
} }
if (err) { if (err) {
// the server closed the connection before the greeting // the server closed the connection before the greeting
returned = true; return finish(err);
connection.close();
return callback(err);
} }
perCallAuth = this.getAuth(mail.data.auth); perCallAuth = this.getAuth(mail.data.auth);
if (perCallAuth && (connection.allowsAuth || options.forceAuth)) { if (perCallAuth && (smtp.allowsAuth || options.forceAuth)) {
connection.login(perCallAuth, err => { smtp.login(perCallAuth, err => {
cleanupPerCallAuth(); cleanupPerCallAuth();
if (returned) { if (returned) {
return; return;
} }
if (err) { if (err) {
returned = true; return finish(err);
connection.close();
return callback(err);
} }
sendMessage(); sendMessage();
}); });
+7
View File
@@ -609,6 +609,13 @@ exports.services = {
"host": "mail.smtp2go.com", "host": "mail.smtp2go.com",
"port": 2525 "port": 2525
}, },
"SpacePost": {
"description": "SpacePost",
"host": "smtp.spacepost.dev",
"port": 25976,
"secure": false,
"requireTLS": true
},
"Sparkpost": { "Sparkpost": {
"description": "SparkPost", "description": "SparkPost",
"aliases": [ "aliases": [
+185 -2
View File
@@ -46,6 +46,30 @@ class TokenList {
this.slots[at + 2] = end; this.slots[at + 2] = end;
return this.length++; 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 * The character of an operator token, an empty string for a text run
*/ */
@@ -181,6 +205,44 @@ function _isSpaceCode(code) {
code === 0x3000 || code === 0x3000 ||
code === 0xfeff); 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 * 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, * 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 * The scan is by index, a pattern such as /\s+@/ backtracks over a long whitespace run that
* no '@' follows. * no '@' follows.
* *
* The whitespace around the dots of the domain that follows is dropped as well, see
* _joinDomainDotSpacing.
*
* @param value Value holding the '@' * @param value Value holding the '@'
* @param at Offset of the '@', or -1 * @param at Offset of the '@', or -1
* @return The value with the whitespace beside that '@' removed * @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))) { while (end < value.length && _isSpaceCode(value.charCodeAt(end))) {
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 '@' * 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 // 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 // local part is until the '@' after it joins the run
let lastTextPureQuoted = false; 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 // 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 // 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 // every token, which is quadratic over an address built from many comment-joined atoms
@@ -568,18 +721,27 @@ function _collectAddressParts(tokens, from, to) {
case '<': case '<':
state = 'address'; state = 'address';
insideQuotes = false; insideQuotes = false;
lastTextOpen = false;
break; break;
case '(': case '(':
state = 'comment'; state = 'comment';
insideQuotes = false; insideQuotes = false;
gapsFolding = gapsFolding && _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
break; break;
case '"': case '"':
insideQuotes = !insideQuotes; insideQuotes = !insideQuotes;
state = 'text'; state = 'text';
lastTextOpen = false;
break; break;
default: default:
state = 'text'; state = 'text';
insideQuotes = false; insideQuotes = false;
if (value !== ')') {
lastTextOpen = false;
}
else {
gapFrom = tokens.contentEnd(i);
}
break; 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 // 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 // 'user@example.com(x)evil.com' as the single domain 'example.comevil.com' and
// deliver to a domain the sender never named. // 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 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) { if (joins) {
const last = data[state].length - 1; const last = data[state].length - 1;
if (state === 'text' && !insideQuotes) { if (state === 'text' && !insideQuotes) {
@@ -622,6 +799,12 @@ function _collectAddressParts(tokens, from, to) {
lastTextPureQuoted = insideQuotes; 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 // If there is no text but a comment, replace the two. A comment is never part of a
+2 -2
View File
@@ -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 * as mimeFuncs from '../mime-funcs/index.js';
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import * as errors from '../errors.js'; import * as errors from '../errors.js';
@@ -65,7 +65,7 @@ function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyH
'v=1', 'v=1',
'a=rsa-' + hashAlgo, 'a=rsa-' + hashAlgo,
'c=relaxed/relaxed', 'c=relaxed/relaxed',
'd=' + punycode.toASCII(cleanTagValue(domainName)), 'd=' + shared.normalizeDomain(cleanTagValue(domainName), false),
'q=dns/txt', 'q=dns/txt',
's=' + cleanTagValue(keySelector), 's=' + cleanTagValue(keySelector),
'bh=' + bodyHash, 'bh=' + bodyHash,
+2
View File
@@ -23,6 +23,7 @@ export declare const ERROR_CODES: {
readonly EMESSAGE: "Message delivery error"; readonly EMESSAGE: "Message delivery error";
readonly EOTP: "Invalid one-time passcode data (otp option)"; readonly EOTP: "Invalid one-time passcode data (otp option)";
readonly ESTREAM: "Stream processing error"; readonly ESTREAM: "Stream processing error";
readonly EABORT: "Message sending aborted";
readonly EAUTH: "Authentication failed"; readonly EAUTH: "Authentication failed";
readonly ENOAUTH: "Authentication credentials not provided"; readonly ENOAUTH: "Authentication credentials not provided";
readonly EOAUTH2: "OAuth2 token generation or refresh error"; readonly EOAUTH2: "OAuth2 token generation or refresh error";
@@ -51,6 +52,7 @@ export declare const EENVELOPE = "EENVELOPE";
export declare const EMESSAGE = "EMESSAGE"; export declare const EMESSAGE = "EMESSAGE";
export declare const EOTP = "EOTP"; export declare const EOTP = "EOTP";
export declare const ESTREAM = "ESTREAM"; export declare const ESTREAM = "ESTREAM";
export declare const EABORT = "EABORT";
export declare const EAUTH = "EAUTH"; export declare const EAUTH = "EAUTH";
export declare const ENOAUTH = "ENOAUTH"; export declare const ENOAUTH = "ENOAUTH";
export declare const EOAUTH2 = "EOAUTH2"; export declare const EOAUTH2 = "EOAUTH2";
+9
View File
@@ -26,6 +26,7 @@ export const ERROR_CODES = {
EMESSAGE: 'Message delivery error', EMESSAGE: 'Message delivery error',
EOTP: 'Invalid one-time passcode data (otp option)', EOTP: 'Invalid one-time passcode data (otp option)',
ESTREAM: 'Stream processing error', ESTREAM: 'Stream processing error',
EABORT: 'Message sending aborted',
// Authentication errors // Authentication errors
EAUTH: 'Authentication failed', EAUTH: 'Authentication failed',
ENOAUTH: 'Authentication credentials not provided', ENOAUTH: 'Authentication credentials not provided',
@@ -55,6 +56,7 @@ export const EENVELOPE = 'EENVELOPE';
export const EMESSAGE = 'EMESSAGE'; export const EMESSAGE = 'EMESSAGE';
export const EOTP = 'EOTP'; export const EOTP = 'EOTP';
export const ESTREAM = 'ESTREAM'; export const ESTREAM = 'ESTREAM';
export const EABORT = 'EABORT';
export const EAUTH = 'EAUTH'; export const EAUTH = 'EAUTH';
export const ENOAUTH = 'ENOAUTH'; export const ENOAUTH = 'ENOAUTH';
export const EOAUTH2 = 'EOAUTH2'; export const EOAUTH2 = 'EOAUTH2';
@@ -67,6 +69,13 @@ export const EPROXY = 'EPROXY';
export const EFILEACCESS = 'EFILEACCESS'; export const EFILEACCESS = 'EFILEACCESS';
export const EURLACCESS = 'EURLACCESS'; export const EURLACCESS = 'EURLACCESS';
export const EFETCH = 'EFETCH'; 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 * Tells whether the error ended the connection rather than rejected what was sent over it
*/ */
+2
View File
@@ -48,6 +48,8 @@ class JSONTransport {
} }
delete data.envelope; delete data.envelope;
delete data.normalizedHeaders; delete data.normalizedHeaders;
// the per-message AbortSignal is not message data
delete data.signal;
// the message field is the object itself with skipEncoding, the // the message field is the object itself with skipEncoding, the
// createTransport overload for that option types the result accordingly // createTransport overload for that option types the result accordingly
return done(null, { return done(null, {
+12 -2
View File
@@ -112,6 +112,11 @@ export interface MailMeta {
* declared on Transport, Transporter and Mail * declared on Transport, Transporter and Mail
*/ */
export interface Transport<T = SentMessageInfo, D extends TransportOptions = TransportOptions> { 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 */ /** Transport name, used for logging */
name: string; name: string;
/** Transport version, used for logging */ /** Transport version, used for logging */
@@ -176,8 +181,13 @@ declare class Mail<out T = SentMessageInfo, out D extends TransportOptions = Tra
dkim: DKIM | false; dkim: DKIM | false;
transporter: Transport<T, D>; transporter: Transport<T, D>;
logger: shared.Logger; 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 */ /** Tells whether the transport can take a message right away */
isIdle: () => boolean; isIdle: () => boolean;
/** Checks the configuration, the SMTP transports connect and authenticate for it */ /** Checks the configuration, the SMTP transports connect and authenticate for it */
+56 -4
View File
@@ -18,6 +18,16 @@ import crypto from 'node:crypto';
* asks a server to accept 100, so a real send is bounded far below this. * asks a server to accept 100, so a real send is bounded far below this.
*/ */
const DEFAULT_MAX_RECIPIENTS = 100000; 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 * Creates an object for exposing the Mail API
* *
@@ -119,11 +129,43 @@ class Mail extends EventEmitter {
this.getSocket = false; this.getSocket = false;
} }
const mail = new MailMessage(this, data); 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 // a failed message is not going to be read anymore, release its content streams
const fail = (err) => { const fail = (err) => {
mail.releaseStreams(); finish(err);
done(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({ this.logger.debug({
tnx: 'transport', tnx: 'transport',
name: this.transporter.name, name: this.transporter.name,
@@ -131,6 +173,9 @@ class Mail extends EventEmitter {
action: 'send' action: 'send'
}, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version); }, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version);
this._processPlugins('compile', mail, err => { this._processPlugins('compile', mail, err => {
if (settled) {
return;
}
if (err) { if (err) {
this.logger.error({ this.logger.error({
err, err,
@@ -168,6 +213,9 @@ class Mail extends EventEmitter {
return fail(err); return fail(err);
} }
this._processPlugins('stream', mail, err => { this._processPlugins('stream', mail, err => {
if (settled) {
return;
}
if (err) { if (err) {
this.logger.error({ this.logger.error({
err, err,
@@ -187,16 +235,17 @@ class Mail extends EventEmitter {
return dkim.sign(input, mail.data._dkim); return dkim.sign(input, mail.data._dkim);
}); });
} }
// The transport takes ownership of cancellation from here, including queued work.
removeAbortListener();
this.transporter.send(mail, (...args) => { this.transporter.send(mail, (...args) => {
if (args[0]) { if (args[0]) {
mail.releaseStreams();
this.logger.error({ this.logger.error({
err: args[0], err: args[0],
tnx: 'transport', tnx: 'transport',
action: 'send' action: 'send'
}, 'Send Error: %s', args[0].message); }, 'Send Error: %s', args[0].message);
} }
done(...args); finish(...args);
}); });
}); });
}); });
@@ -226,6 +275,9 @@ class Mail extends EventEmitter {
let pos = 0; let pos = 0;
let block = 'default'; let block = 'default';
const processPlugins = () => { const processPlugins = () => {
if (mail.data.signal?.aborted) {
return callback(errors.createAbortError(mail.data.signal));
}
let curplugins = block === 'default' ? defaultPlugins : userPlugins; let curplugins = block === 'default' ? defaultPlugins : userPlugins;
if (pos >= curplugins.length) { if (pos >= curplugins.length) {
if (block === 'default' && userPlugins.length) { if (block === 'default' && userPlugins.length) {
+10
View File
@@ -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 * tree is built from, the fields below are the ones the mailer reads on top of those
*/ */
export interface SendMailOptions extends MailComposerOptions { 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 signing options for this message, used instead of the ones of the transporter */
dkim?: DKIMOptions | undefined; 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 */ /** 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 */
+2 -1
View File
@@ -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; 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 value String to be encoded
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
+72 -2
View File
@@ -132,8 +132,75 @@ export function encodeWord(data, mimeWordEncoding, maxLength) {
} }
return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?='); 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 value String to be encoded
* @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B * @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; lastSpecial = i;
} }
} }
if (value.indexOf('=?') >= 0) {
[firstSpecial, lastSpecial] = _markInvalidEncodedWords(value, [firstSpecial, lastSpecial]);
}
if (firstSpecial < 0) { if (firstSpecial < 0) {
return value; return value;
} }
if (encodeAll) { 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); return encodeWord(value, mimeWordEncoding, maxLength);
} }
// encode from the start of the word holding the first such character to the end of the // encode from the start of the word holding the first such character to the end of the
+1 -73
View File
@@ -1,10 +1,8 @@
/* eslint no-undefined: 0, prefer-spread: 0, no-control-regex: 0 */ /* eslint no-undefined: 0, prefer-spread: 0, no-control-regex: 0 */
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import fs from 'node:fs'; import fs from 'node:fs';
import * as punycode from '../punycode/index.js';
import { PassThrough, finished, pipeline } from 'node:stream'; import { PassThrough, finished, pipeline } from 'node:stream';
import * as shared from '../shared/index.js'; import * as shared from '../shared/index.js';
import urlModule from 'node:url';
import * as mimeFuncs from '../mime-funcs/index.js'; import * as mimeFuncs from '../mime-funcs/index.js';
import * as qp from '../qp/index.js'; import * as qp from '../qp/index.js';
import * as base64 from '../base64/index.js'; import * as base64 from '../base64/index.js';
@@ -55,20 +53,6 @@ function stripWhitespaceInAngleBrackets(value) {
} }
return result + value.slice(pos); 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 // pipeline() needs a callback to not throw, the errors it sees reach the last stream anyway
const PIPELINE_NOOP = () => false; const PIPELINE_NOOP = () => false;
// The error a node streaming into an output that was destroyed stops with // The error a node streaming into an output that was destroyed stops with
@@ -77,62 +61,6 @@ function abortedError() {
err.code = errors.ESTREAM; err.code = errors.ESTREAM;
return err; 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. * Removes the characters that must never reach a multipart delimiter line.
* *
@@ -1500,7 +1428,7 @@ class MimeNode {
// symmetry on both sides of the '@' rather than being encoded to an A-label // symmetry on both sides of the '@' rather than being encoded to an A-label
const smtputf8 = /[\x80-\uFFFF]/.test(user); const smtputf8 = /[\x80-\uFFFF]/.test(user);
try { try {
encodedDomain = normalizeDomain(domain.toLowerCase(), smtputf8); encodedDomain = shared.normalizeDomain(domain, smtputf8);
} }
catch (_err) { catch (_err) {
// keep domain as supplied // keep domain as supplied
+1 -1
View File
@@ -1,3 +1,3 @@
export declare const name = "nodemailer"; export declare const name = "nodemailer";
export declare const version = "10.3.1"; export declare const version = "10.5.0";
export declare const homepage = "https://nodemailer.com/"; export declare const homepage = "https://nodemailer.com/";
+1 -1
View File
@@ -1,4 +1,4 @@
// Generated by scripts/build.js from package.json. Do not edit by hand. // Generated by scripts/build.js from package.json. Do not edit by hand.
export const name = 'nodemailer'; export const name = 'nodemailer';
export const version = '10.3.1'; export const version = '10.5.0';
export const homepage = 'https://nodemailer.com/'; export const homepage = 'https://nodemailer.com/';
+23
View File
@@ -289,3 +289,26 @@ export declare function unreadableStreamError(stream: Readable): NodemailerError
* @param callback Callback function with (err, value) * @param callback Callback function with (err, value)
*/ */
export declare function resolveStream(stream: Readable, callback: (err: Error | null, value?: Buffer) => void): void; 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
View File
@@ -8,6 +8,8 @@ import { isProtoKey, copyOwnKeys } from './objects.js';
import dns from 'node:dns'; import dns from 'node:dns';
import net from 'node:net'; import net from 'node:net';
import os from 'node:os'; import os from 'node:os';
import urlModule from 'node:url';
import * as punycode from '../punycode/index.js';
import { finished } from 'node:stream'; import { finished } from 'node:stream';
// re-exported for the callers that already depend on this module, see ./objects // re-exported for the callers that already depend on this module, see ./objects
export { isProtoKey, copyOwnKeys }; export { isProtoKey, copyOwnKeys };
@@ -717,3 +719,79 @@ function createDefaultLogger(levels) {
}); });
return logger; 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);
}
+6
View File
@@ -249,6 +249,9 @@ class SMTPConnection extends EventEmitter {
// socket object is set up but not yet connected // socket object is set up but not yet connected
this._socket = this.options.socket; this._socket = this.options.socket;
return this._resolveAndConnect(opts, _resolved => { return this._resolveAndConnect(opts, _resolved => {
if (this._destroyed || this._closing) {
return;
}
try { try {
this._socket.connect(this.port, this.host, () => { this._socket.connect(this.port, this.host, () => {
// a `secure` connection over a caller-provided socket must still // a `secure` connection over a caller-provided socket must still
@@ -1039,6 +1042,9 @@ class SMTPConnection extends EventEmitter {
* @internal * @internal
*/ */
_upgradeConnection(callback) { _upgradeConnection(callback) {
if (this._destroyed || this._closing) {
return;
}
// RFC 3207 section 6: the client MUST discard any knowledge obtained from // 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 // 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 // buffered input received before the handshake so a man-in-the-middle cannot
+10 -3
View File
@@ -76,6 +76,7 @@ export interface SMTPPoolRateLimit {
* @param options SMTP Connection options * @param options SMTP Connection options
*/ */
declare class SMTPPool extends EventEmitter { declare class SMTPPool extends EventEmitter {
readonly supportsAbortSignal = true;
options: SMTPPoolResolvedOptions; options: SMTPPoolResolvedOptions;
logger: shared.Logger; logger: shared.Logger;
name: string; name: string;
@@ -102,10 +103,16 @@ declare class SMTPPool extends EventEmitter {
*/ */
send(mail: MailMessage<SMTPPoolSentMessageInfo>, callback: SMTPPoolSendCallback): boolean; send(mail: MailMessage<SMTPPoolSentMessageInfo>, callback: SMTPPoolSendCallback): boolean;
/** /**
* Closes all connections in the pool. If there is a message being sent, the connection * Closes the pool. Idle connections are closed at once and a connection in the middle of a
* is closed later * 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 * Returns true if there are free slots in the queue
*/ */
+69 -11
View File
@@ -18,6 +18,7 @@ const REQUEUE_MAX_DELAY = 2000;
class SMTPPool extends EventEmitter { class SMTPPool extends EventEmitter {
constructor(options) { constructor(options) {
super(); super();
this.supportsAbortSignal = true;
options = options || {}; options = options || {};
if (typeof options === 'string') { if (typeof options === 'string') {
options = { options = {
@@ -96,20 +97,33 @@ class SMTPPool extends EventEmitter {
return false; return false;
} }
// counted until the callback runs, whichever path runs it: delivered, failed, requeued // 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 counted = true;
let detachSignal;
this._pending++; this._pending++;
this._queue.push({ const entry = {
mail, mail,
requeueAttempts: 0, requeueAttempts: 0,
callback: (err, info) => { callback: (err, info) => {
if (counted) { if (!counted) {
return;
}
counted = false; counted = false;
this._pending--; this._pending--;
} detachSignal?.();
entry.resource = undefined;
callback(err, info); 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) { if (this.idling && this._queue.length >= this.options.maxConnections) {
this.idling = false; this.idling = false;
} }
@@ -117,10 +131,49 @@ class SMTPPool extends EventEmitter {
return true; return true;
} }
/** /**
* Closes all connections in the pool. If there is a message being sent, the connection * Fails a queued or assigned entry when its signal aborts: removes it from the queue, or
* is closed later * 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; let connection;
const len = this._connections.length; const len = this._connections.length;
this._closed = true; this._closed = true;
@@ -131,9 +184,10 @@ class SMTPPool extends EventEmitter {
if (!len && !this._queue.length) { if (!len && !this._queue.length) {
return; 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--) { 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 = this._connections[i];
connection.close(); connection.close();
this.logger.info({ this.logger.info({
@@ -211,6 +265,7 @@ class SMTPPool extends EventEmitter {
this.emit('idle'); this.emit('idle');
} }
const entry = (connection.queueEntry = this._queue.shift()); const entry = (connection.queueEntry = this._queue.shift());
entry.resource = connection;
entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, ''); entry.messageId = (connection.queueEntry.mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, '');
connection.available = false; connection.available = false;
this.logger.debug({ this.logger.debug({
@@ -318,7 +373,9 @@ class SMTPPool extends EventEmitter {
setTimeout(() => { setTimeout(() => {
let delay = 0; let delay = 0;
if (connection.queueEntry) { 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); delay = this._requeueEntryOnConnectionClose(connection);
} }
else { else {
@@ -380,6 +437,7 @@ class SMTPPool extends EventEmitter {
messageId: connection.queueEntry.messageId, messageId: connection.queueEntry.messageId,
action: 'requeue' action: 'requeue'
}, 'Re-queued message <%s> for #%s. Attempt: #%s', connection.queueEntry.messageId, connection.id, connection.queueEntry.requeueAttempts); }, '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); this._queue.unshift(connection.queueEntry);
connection.queueEntry = false; connection.queueEntry = false;
return delay; return delay;
+26 -4
View File
@@ -48,6 +48,7 @@ export default class PoolResource extends EventEmitter {
} }
this._connection = false; this._connection = false;
this._connected = false; this._connected = false;
this._closed = false;
this.messages = 0; this.messages = 0;
this.available = true; this.available = true;
this._failed = false; this._failed = false;
@@ -75,6 +76,10 @@ export default class PoolResource extends EventEmitter {
// the proxy handshake, if any, counts against connectionTimeout as well // the proxy handshake, if any, counts against connectionTimeout as well
const connectStartedAt = Date.now(); const connectStartedAt = Date.now();
this.pool.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => { this.pool.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
if (this._closed) {
socketOptions && socketOptions.connection?.destroy();
return;
}
if (err) { if (err) {
// nothing was connected, so no 'close' event is coming that would free the // 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 // 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 = new SMTPConnection(options);
this.connection._connectStartedAt = connectStartedAt; this.connection._connectStartedAt = connectStartedAt;
this.connection.on('error', (err) => { 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 // the send callback gets the same error and decides what it means for the message
return; return;
} }
@@ -112,7 +117,7 @@ export default class PoolResource extends EventEmitter {
return; return;
} }
this._fail(err); this._fail(err);
if (returned) { if (returned || this._closed) {
return; return;
} }
returned = true; returned = true;
@@ -123,7 +128,7 @@ export default class PoolResource extends EventEmitter {
returned = true; returned = true;
}); });
this.connection.connect(err => { this.connection.connect(err => {
if (returned) { if (returned || this._closed) {
return; return;
} }
if (err) { if (err) {
@@ -134,7 +139,7 @@ export default class PoolResource extends EventEmitter {
} }
if (this.auth && (this.connection.allowsAuth || options.forceAuth)) { if (this.auth && (this.connection.allowsAuth || options.forceAuth)) {
this.connection.login(this.auth, err => { this.connection.login(this.auth, err => {
if (returned) { if (returned || this._closed) {
return; return;
} }
returned = true; returned = true;
@@ -162,6 +167,9 @@ export default class PoolResource extends EventEmitter {
* @param callback Callback function * @param callback Callback function
*/ */
send(mail, callback) { send(mail, callback) {
if (this._closed) {
return;
}
if (!this._connected) { if (!this._connected) {
return this.connect(err => { return this.connect(err => {
if (err) { if (err) {
@@ -193,6 +201,9 @@ export default class PoolResource extends EventEmitter {
const reused = this.messages > 0; const reused = this.messages > 0;
const messageStream = mail.message.createReadStream(); const messageStream = mail.message.createReadStream();
this.connection.send(envelope, messageStream, (err, info) => { this.connection.send(envelope, messageStream, (err, info) => {
if (mail.data.signal?.aborted) {
return;
}
this._sending = false; this._sending = false;
this.messages++; this.messages++;
if (err) { if (err) {
@@ -239,6 +250,9 @@ export default class PoolResource extends EventEmitter {
* @internal * @internal
*/ */
_release() { _release() {
if (this._closed) {
return;
}
if (this.messages >= this.options.maxMessages) { if (this.messages >= this.options.maxMessages) {
const err = new Error('Resource exhausted'); const err = new Error('Resource exhausted');
err.code = errors.EMAXLIMIT; err.code = errors.EMAXLIMIT;
@@ -247,6 +261,9 @@ export default class PoolResource extends EventEmitter {
return; return;
} }
this.pool._checkRateLimit(() => { this.pool._checkRateLimit(() => {
if (this._closed) {
return;
}
this.available = true; this.available = true;
this._startIdleTimer(); this._startIdleTimer();
this.emit('available'); this.emit('available');
@@ -289,6 +306,11 @@ export default class PoolResource extends EventEmitter {
* Closes the connection * Closes the connection
*/ */
close() { close() {
if (this._closed) {
return;
}
this._closed = true;
this.available = false;
this._connected = false; this._connected = false;
this._stopIdleTimer(); this._stopIdleTimer();
if (this.auth && this.auth.oauth2) { if (this.auth && this.auth.oauth2) {
+1
View File
@@ -93,6 +93,7 @@ export type SMTPTransportSendCallback = ResultCallback<SMTPSentMessageInfo>;
* @param options Connection options * @param options Connection options
*/ */
declare class SMTPTransport extends EventEmitter { declare class SMTPTransport extends EventEmitter {
readonly supportsAbortSignal = true;
options: SMTPTransportOptions; options: SMTPTransportOptions;
logger: shared.Logger; logger: shared.Logger;
name: string; name: string;
+47 -35
View File
@@ -21,6 +21,7 @@ const MESSAGE_AUTH_KEYS = ['type', 'user', 'pass', 'accessToken', 'refreshToken'
class SMTPTransport extends EventEmitter { class SMTPTransport extends EventEmitter {
constructor(options) { constructor(options) {
super(); super();
this.supportsAbortSignal = true;
options = options || {}; options = options || {};
if (typeof options === 'string') { if (typeof options === 'string') {
options = { options = {
@@ -115,13 +116,46 @@ class SMTPTransport extends EventEmitter {
* @param callback Callback function * @param callback Callback function
*/ */
send(mail, callback) { 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 // the proxy handshake, if any, counts against connectionTimeout as well
const connectStartedAt = Date.now(); const connectStartedAt = Date.now();
this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => { this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
if (returned) {
socketOptions && socketOptions.connection?.destroy();
return;
}
if (err) { if (err) {
return callback(err); return finish(err);
} }
let returned = false;
let options = this.options; let options = this.options;
if (socketOptions && socketOptions.connection) { if (socketOptions && socketOptions.connection) {
this.logger.info({ this.logger.info({
@@ -135,24 +169,9 @@ class SMTPTransport extends EventEmitter {
// only copy options if we need to modify it // only copy options if we need to modify it
options = Object.assign(shared.assign(false, options), socketOptions); options = Object.assign(shared.assign(false, options), socketOptions);
} }
const connection = new SMTPConnection(options); const smtp = (connection = new SMTPConnection(options));
connection._connectStartedAt = connectStartedAt; smtp._connectStartedAt = connectStartedAt;
let perCallAuth; smtp.once('error', err => finish(err));
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 sendMessage = () => { const sendMessage = () => {
const envelope = mail.message.getEnvelope(); const envelope = mail.message.getEnvelope();
const messageId = mail.message.messageId(); const messageId = mail.message.messageId();
@@ -171,20 +190,17 @@ class SMTPTransport extends EventEmitter {
tnx: 'send', tnx: 'send',
messageId messageId
}, 'Sending message %s to <%s>', messageId, recipients.join(', ')); }, '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) { if (returned) {
// the connection error handler has already reported this send // the connection error handler has already reported this send
return; return;
} }
returned = true;
cleanupPerCallAuth();
connection.close();
if (err) { if (err) {
this.logger.error({ this.logger.error({
err, err,
tnx: 'send' tnx: 'send'
}, 'Send error for %s: %s', messageId, err.message); }, 'Send error for %s: %s', messageId, err.message);
return callback(err); return finish(err);
} }
info.envelope = { info.envelope = {
from: envelope.from, from: envelope.from,
@@ -192,7 +208,7 @@ class SMTPTransport extends EventEmitter {
}; };
info.messageId = messageId; info.messageId = messageId;
try { try {
return callback(null, info); return finish(null, info);
} }
catch (E) { catch (E) {
this.logger.error({ this.logger.error({
@@ -202,27 +218,23 @@ class SMTPTransport extends EventEmitter {
} }
}); });
}; };
connection.connect(err => { smtp.connect(err => {
if (returned) { if (returned) {
return; return;
} }
if (err) { if (err) {
// the server closed the connection before the greeting // the server closed the connection before the greeting
returned = true; return finish(err);
connection.close();
return callback(err);
} }
perCallAuth = this.getAuth(mail.data.auth); perCallAuth = this.getAuth(mail.data.auth);
if (perCallAuth && (connection.allowsAuth || options.forceAuth)) { if (perCallAuth && (smtp.allowsAuth || options.forceAuth)) {
connection.login(perCallAuth, err => { smtp.login(perCallAuth, err => {
cleanupPerCallAuth(); cleanupPerCallAuth();
if (returned) { if (returned) {
return; return;
} }
if (err) { if (err) {
returned = true; return finish(err);
connection.close();
return callback(err);
} }
sendMessage(); sendMessage();
}); });
+7
View File
@@ -606,6 +606,13 @@ export const services = {
"host": "mail.smtp2go.com", "host": "mail.smtp2go.com",
"port": 2525 "port": 2525
}, },
"SpacePost": {
"description": "SpacePost",
"host": "smtp.spacepost.dev",
"port": 25976,
"secure": false,
"requireTLS": true
},
"Sparkpost": { "Sparkpost": {
"description": "SparkPost", "description": "SparkPost",
"aliases": [ "aliases": [
+8
View File
@@ -585,6 +585,14 @@
"port": 2525 "port": 2525
}, },
"SpacePost": {
"description": "SpacePost",
"host": "smtp.spacepost.dev",
"port": 25976,
"secure": false,
"requireTLS": true
},
"Sparkpost": { "Sparkpost": {
"description": "SparkPost", "description": "SparkPost",
"aliases": ["SparkPost", "SparkPost Mail"], "aliases": ["SparkPost", "SparkPost Mail"],
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "nodemailer", "name": "nodemailer",
"version": "10.3.1", "version": "10.5.0",
"description": "Easy as cake e-mail sending from your Node.js applications", "description": "Easy as cake e-mail sending from your Node.js applications",
"type": "module", "type": "module",
"main": "./dist/cjs/nodemailer.js", "main": "./dist/cjs/nodemailer.js",
@@ -153,24 +153,24 @@
}, },
"homepage": "https://nodemailer.com/", "homepage": "https://nodemailer.com/",
"devDependencies": { "devDependencies": {
"@aws-sdk/client-sesv2": "3.1159.0", "@aws-sdk/client-sesv2": "3.1165.0",
"@types/node": "20.19.43", "@types/node": "20.19.43",
"bunyan": "1.8.15", "bunyan": "1.8.15",
"c8": "12.0.0", "c8": "12.0.0",
"eslint": "10.13.0", "eslint": "10.14.0",
"eslint-config-prettier": "10.1.8", "eslint-config-prettier": "10.1.8",
"globals": "17.13.0", "globals": "17.14.0",
"libbase64": "1.4.1", "libbase64": "1.4.1",
"libmime": "5.6.3", "libmime": "5.6.4",
"libqp": "3.0.1", "libqp": "3.0.1",
"mailauth": "8.0.4", "mailauth": "8.0.4",
"prettier": "3.9.10", "prettier": "3.9.10",
"proxy": "1.0.2", "proxy": "1.0.2",
"proxy-test-server": "1.0.0", "proxy-test-server": "1.0.0",
"smtp-server": "3.21.2", "smtp-server": "3.21.3",
"tsx": "4.23.15", "tsx": "4.23.15",
"typescript": "6.0.3", "typescript": "6.0.3",
"typescript-eslint": "8.72.1" "typescript-eslint": "8.72.2"
}, },
"engines": { "engines": {
"node": ">=20.0.0" "node": ">=20.0.0"